Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
package.dist.plotly-strict.js Maven / Gradle / Ivy
Go to download
The open source javascript graphing library that powers plotly
/**
* plotly.js (strict) v2.34.0
* Copyright 2012-2024, Plotly, Inc.
* All rights reserved.
* Licensed under the MIT license
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Plotly"] = factory();
else
root["Plotly"] = factory();
})(self, function() {
return /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 79288:
/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var rules = {
"X,X div": "direction:ltr;font-family:\"Open Sans\",verdana,arial,sans-serif;margin:0;padding:0;",
"X input,X button": "font-family:\"Open Sans\",verdana,arial,sans-serif;",
"X input:focus,X button:focus": "outline:none;",
"X a": "text-decoration:none;",
"X a:hover": "text-decoration:none;",
"X .crisp": "shape-rendering:crispEdges;",
"X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;",
"X svg": "overflow:hidden;",
"X svg a": "fill:#447adb;",
"X svg a:hover": "fill:#3c6dc5;",
"X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;",
"X .main-svg .draglayer": "pointer-events:all;",
"X .cursor-default": "cursor:default;",
"X .cursor-pointer": "cursor:pointer;",
"X .cursor-crosshair": "cursor:crosshair;",
"X .cursor-move": "cursor:move;",
"X .cursor-col-resize": "cursor:col-resize;",
"X .cursor-row-resize": "cursor:row-resize;",
"X .cursor-ns-resize": "cursor:ns-resize;",
"X .cursor-ew-resize": "cursor:ew-resize;",
"X .cursor-sw-resize": "cursor:sw-resize;",
"X .cursor-s-resize": "cursor:s-resize;",
"X .cursor-se-resize": "cursor:se-resize;",
"X .cursor-w-resize": "cursor:w-resize;",
"X .cursor-e-resize": "cursor:e-resize;",
"X .cursor-nw-resize": "cursor:nw-resize;",
"X .cursor-n-resize": "cursor:n-resize;",
"X .cursor-ne-resize": "cursor:ne-resize;",
"X .cursor-grab": "cursor:-webkit-grab;cursor:grab;",
"X .modebar": "position:absolute;top:2px;right:2px;",
"X .ease-bg": "-webkit-transition:background-color .3s ease 0s;-moz-transition:background-color .3s ease 0s;-ms-transition:background-color .3s ease 0s;-o-transition:background-color .3s ease 0s;transition:background-color .3s ease 0s;",
"X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity .3s ease 0s;-moz-transition:opacity .3s ease 0s;-ms-transition:opacity .3s ease 0s;-o-transition:opacity .3s ease 0s;transition:opacity .3s ease 0s;",
"X:hover .modebar--hover .modebar-group": "opacity:1;",
"X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;padding-left:8px;position:relative;vertical-align:middle;white-space:nowrap;",
"X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;",
"X .modebar-btn svg": "position:relative;top:2px;",
"X .modebar.vertical": "display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;",
"X .modebar.vertical svg": "top:-1px;",
"X .modebar.vertical .modebar-group": "display:block;float:none;padding-left:0px;padding-bottom:8px;",
"X .modebar.vertical .modebar-group .modebar-btn": "display:block;text-align:center;",
"X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;",
"X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;",
"X [data-title]:before": "content:\"\";position:absolute;background:rgba(0,0,0,0);border:6px solid rgba(0,0,0,0);z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;",
"X [data-title]:after": "content:attr(data-title);background:#69738a;color:#fff;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;",
"X .vertical [data-title]:before,X .vertical [data-title]:after": "top:0%;right:200%;",
"X .vertical [data-title]:before": "border:6px solid rgba(0,0,0,0);border-left-color:#69738a;margin-top:8px;margin-right:-30px;",
Y: "font-family:\"Open Sans\",verdana,arial,sans-serif;position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;",
"Y p": "margin:0;",
"Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;",
"Y .notifier-close": "color:#fff;opacity:.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;",
"Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;"
};
for (var selector in rules) {
var fullSelector = selector.replace(/^,/, ' ,').replace(/X/g, '.js-plotly-plot .plotly').replace(/Y/g, '.plotly-notifier');
Lib.addStyleRule(fullSelector, rules[selector]);
}
/***/ }),
/***/ 86712:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(84224);
/***/ }),
/***/ 37240:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(51132);
/***/ }),
/***/ 29744:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(94456);
/***/ }),
/***/ 29352:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(67244);
/***/ }),
/***/ 96144:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(97776);
/***/ }),
/***/ 53219:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(61712);
/***/ }),
/***/ 4624:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(95856);
/***/ }),
/***/ 54543:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(54272);
/***/ }),
/***/ 45000:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(85404);
/***/ }),
/***/ 62300:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(26048);
/***/ }),
/***/ 6920:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(66240);
/***/ }),
/***/ 10264:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(40448);
/***/ }),
/***/ 32016:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(64884);
/***/ }),
/***/ 27528:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(15088);
/***/ }),
/***/ 75556:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(76744);
/***/ }),
/***/ 39204:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(94704);
/***/ }),
/***/ 73996:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(62396);
/***/ }),
/***/ 16489:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(32028);
/***/ }),
/***/ 5000:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(81932);
/***/ }),
/***/ 77280:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(45536);
/***/ }),
/***/ 33992:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(42600);
/***/ }),
/***/ 17600:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(21536);
/***/ }),
/***/ 49116:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(65664);
/***/ }),
/***/ 46808:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(29044);
/***/ }),
/***/ 36168:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(48928);
/***/ }),
/***/ 64456:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Plotly = __webpack_require__(32016);
Plotly.register([
// traces
__webpack_require__(37240), __webpack_require__(29352), __webpack_require__(5000), __webpack_require__(33992), __webpack_require__(17600), __webpack_require__(49116), __webpack_require__(6920), __webpack_require__(67484), __webpack_require__(79440), __webpack_require__(39204), __webpack_require__(83096), __webpack_require__(36168), __webpack_require__(20260), __webpack_require__(63560), __webpack_require__(65832), __webpack_require__(46808), __webpack_require__(73996), __webpack_require__(48824), __webpack_require__(89904), __webpack_require__(25120), __webpack_require__(13752), __webpack_require__(4340), __webpack_require__(62300), __webpack_require__(29800), __webpack_require__(8363), __webpack_require__(54543), __webpack_require__(75819), __webpack_require__(15680), __webpack_require__(32140), __webpack_require__(77280), __webpack_require__(19960), __webpack_require__(56816), __webpack_require__(70192), __webpack_require__(45000), __webpack_require__(27528), __webpack_require__(84764), __webpack_require__(3920), __webpack_require__(50248), __webpack_require__(4624), __webpack_require__(69967), __webpack_require__(10264), __webpack_require__(86152), __webpack_require__(53219), __webpack_require__(81604), __webpack_require__(58400), __webpack_require__(29744), __webpack_require__(89336),
// transforms
__webpack_require__(86712), __webpack_require__(75556), __webpack_require__(16489), __webpack_require__(97312),
// components
__webpack_require__(96144)]);
module.exports = Plotly;
/***/ }),
/***/ 3920:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(43480);
/***/ }),
/***/ 25120:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(6296);
/***/ }),
/***/ 4340:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(7404);
/***/ }),
/***/ 86152:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(65456);
/***/ }),
/***/ 56816:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(22020);
/***/ }),
/***/ 20260:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(75792);
/***/ }),
/***/ 32140:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(156);
/***/ }),
/***/ 84764:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(45499);
/***/ }),
/***/ 48824:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(3296);
/***/ }),
/***/ 69967:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(4184);
/***/ }),
/***/ 8363:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(36952);
/***/ }),
/***/ 70192:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(11572);
/***/ }),
/***/ 81604:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(76924);
/***/ }),
/***/ 89336:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(95443);
/***/ }),
/***/ 67484:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(34864);
/***/ }),
/***/ 97312:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(76272);
/***/ }),
/***/ 29800:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(15436);
/***/ }),
/***/ 63560:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(5621);
/***/ }),
/***/ 89904:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(91304);
/***/ }),
/***/ 50248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(41724);
/***/ }),
/***/ 65832:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(31991);
/***/ }),
/***/ 79440:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(22869);
/***/ }),
/***/ 13752:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(67776);
/***/ }),
/***/ 83096:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(95952);
/***/ }),
/***/ 72196:
/***/ (function(module) {
"use strict";
/**
* All paths are tuned for maximum scalability of the arrowhead,
* ie throughout arrowwidth=0.3..3 the head is joined smoothly
* to the line, with the line coming from the left and ending at (0, 0).
*
* `backoff` is the distance to move the arrowhead and the end of the line,
* in order that the arrowhead points to the desired place, either at
* the tip of the arrow or (in the case of circle or square)
* the center of the symbol.
*
* `noRotate`, if truthy, says that this arrowhead should not rotate with the
* arrow. That's the case for squares, which should always be straight, and
* circles, for which it's irrelevant.
*/
module.exports = [
// no arrow
{
path: '',
backoff: 0
},
// wide with flat back
{
path: 'M-2.4,-3V3L0.6,0Z',
backoff: 0.6
},
// narrower with flat back
{
path: 'M-3.7,-2.5V2.5L1.3,0Z',
backoff: 1.3
},
// barbed
{
path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z',
backoff: 1.55
},
// wide line-drawn
{
path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z',
backoff: 1.6
},
// narrower line-drawn
{
path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z',
backoff: 2
},
// circle
{
path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z',
backoff: 0,
noRotate: true
},
// square
{
path: 'M2,2V-2H-2V2Z',
backoff: 0,
noRotate: true
}];
/***/ }),
/***/ 13916:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var ARROWPATHS = __webpack_require__(72196);
var fontAttrs = __webpack_require__(25376);
var cartesianConstants = __webpack_require__(33816);
var templatedArray = (__webpack_require__(31780).templatedArray);
var axisPlaceableObjs = __webpack_require__(36208);
function arrowAxisRefDescription(axis) {
return ['In order for absolute positioning of the arrow to work, *a' + axis + 'ref* must be exactly the same as *' + axis + 'ref*, otherwise *a' + axis + 'ref* will revert to *pixel* (explained next).', 'For relative positioning, *a' + axis + 'ref* can be set to *pixel*,', 'in which case the *a' + axis + '* value is specified in pixels', 'relative to *' + axis + '*.', 'Absolute positioning is useful', 'for trendline annotations which should continue to indicate', 'the correct trend when zoomed. Relative positioning is useful', 'for specifying the text offset for an annotated point.'].join(' ');
}
function arrowCoordinateDescription(axis, lower, upper) {
return ['Sets the', axis, 'component of the arrow tail about the arrow head.', 'If `a' + axis + 'ref` is `pixel`, a positive (negative)', 'component corresponds to an arrow pointing', 'from', upper, 'to', lower, '(' + lower, 'to', upper + ').', 'If `a' + axis + 'ref` is not `pixel` and is exactly the same as `' + axis + 'ref`,', 'this is an absolute value on that axis,', 'like `' + axis + '`, specified in the same coordinates as `' + axis + 'ref`.'].join(' ');
}
module.exports = templatedArray('annotation', {
visible: {
valType: 'boolean',
dflt: true,
editType: 'calc+arraydraw'
},
text: {
valType: 'string',
editType: 'calc+arraydraw'
},
textangle: {
valType: 'angle',
dflt: 0,
editType: 'calc+arraydraw'
},
font: fontAttrs({
editType: 'calc+arraydraw',
colorEditType: 'arraydraw'
}),
width: {
valType: 'number',
min: 1,
dflt: null,
editType: 'calc+arraydraw'
},
height: {
valType: 'number',
min: 1,
dflt: null,
editType: 'calc+arraydraw'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1,
editType: 'arraydraw'
},
align: {
valType: 'enumerated',
values: ['left', 'center', 'right'],
dflt: 'center',
editType: 'arraydraw'
},
valign: {
valType: 'enumerated',
values: ['top', 'middle', 'bottom'],
dflt: 'middle',
editType: 'arraydraw'
},
bgcolor: {
valType: 'color',
dflt: 'rgba(0,0,0,0)',
editType: 'arraydraw'
},
bordercolor: {
valType: 'color',
dflt: 'rgba(0,0,0,0)',
editType: 'arraydraw'
},
borderpad: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'calc+arraydraw'
},
borderwidth: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'calc+arraydraw'
},
// arrow
showarrow: {
valType: 'boolean',
dflt: true,
editType: 'calc+arraydraw'
},
arrowcolor: {
valType: 'color',
editType: 'arraydraw'
},
arrowhead: {
valType: 'integer',
min: 0,
max: ARROWPATHS.length,
dflt: 1,
editType: 'arraydraw'
},
startarrowhead: {
valType: 'integer',
min: 0,
max: ARROWPATHS.length,
dflt: 1,
editType: 'arraydraw'
},
arrowside: {
valType: 'flaglist',
flags: ['end', 'start'],
extras: ['none'],
dflt: 'end',
editType: 'arraydraw'
},
arrowsize: {
valType: 'number',
min: 0.3,
dflt: 1,
editType: 'calc+arraydraw'
},
startarrowsize: {
valType: 'number',
min: 0.3,
dflt: 1,
editType: 'calc+arraydraw'
},
arrowwidth: {
valType: 'number',
min: 0.1,
editType: 'calc+arraydraw'
},
standoff: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'calc+arraydraw'
},
startstandoff: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'calc+arraydraw'
},
ax: {
valType: 'any',
editType: 'calc+arraydraw'
},
ay: {
valType: 'any',
editType: 'calc+arraydraw'
},
axref: {
valType: 'enumerated',
dflt: 'pixel',
values: ['pixel', cartesianConstants.idRegex.x.toString()],
editType: 'calc'
},
ayref: {
valType: 'enumerated',
dflt: 'pixel',
values: ['pixel', cartesianConstants.idRegex.y.toString()],
editType: 'calc'
},
// positioning
xref: {
valType: 'enumerated',
values: ['paper', cartesianConstants.idRegex.x.toString()],
editType: 'calc'
},
x: {
valType: 'any',
editType: 'calc+arraydraw'
},
xanchor: {
valType: 'enumerated',
values: ['auto', 'left', 'center', 'right'],
dflt: 'auto',
editType: 'calc+arraydraw'
},
xshift: {
valType: 'number',
dflt: 0,
editType: 'calc+arraydraw'
},
yref: {
valType: 'enumerated',
values: ['paper', cartesianConstants.idRegex.y.toString()],
editType: 'calc'
},
y: {
valType: 'any',
editType: 'calc+arraydraw'
},
yanchor: {
valType: 'enumerated',
values: ['auto', 'top', 'middle', 'bottom'],
dflt: 'auto',
editType: 'calc+arraydraw'
},
yshift: {
valType: 'number',
dflt: 0,
editType: 'calc+arraydraw'
},
clicktoshow: {
valType: 'enumerated',
values: [false, 'onoff', 'onout'],
dflt: false,
editType: 'arraydraw'
},
xclick: {
valType: 'any',
editType: 'arraydraw'
},
yclick: {
valType: 'any',
editType: 'arraydraw'
},
hovertext: {
valType: 'string',
editType: 'arraydraw'
},
hoverlabel: {
bgcolor: {
valType: 'color',
editType: 'arraydraw'
},
bordercolor: {
valType: 'color',
editType: 'arraydraw'
},
font: fontAttrs({
editType: 'arraydraw'
}),
editType: 'arraydraw'
},
captureevents: {
valType: 'boolean',
editType: 'arraydraw'
},
editType: 'calc',
_deprecated: {
ref: {
valType: 'string',
editType: 'calc'
}
}
});
/***/ }),
/***/ 90272:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var draw = (__webpack_require__(23816).draw);
module.exports = function calcAutorange(gd) {
var fullLayout = gd._fullLayout;
var annotationList = Lib.filterVisible(fullLayout.annotations);
if (annotationList.length && gd._fullData.length) {
return Lib.syncOrAsync([draw, annAutorange], gd);
}
};
function annAutorange(gd) {
var fullLayout = gd._fullLayout;
// find the bounding boxes for each of these annotations'
// relative to their anchor points
// use the arrow and the text bg rectangle,
// as the whole anno may include hidden text in its bbox
Lib.filterVisible(fullLayout.annotations).forEach(function (ann) {
var xa = Axes.getFromId(gd, ann.xref);
var ya = Axes.getFromId(gd, ann.yref);
var xRefType = Axes.getRefType(ann.xref);
var yRefType = Axes.getRefType(ann.yref);
ann._extremes = {};
if (xRefType === 'range') calcAxisExpansion(ann, xa);
if (yRefType === 'range') calcAxisExpansion(ann, ya);
});
}
function calcAxisExpansion(ann, ax) {
var axId = ax._id;
var letter = axId.charAt(0);
var pos = ann[letter];
var apos = ann['a' + letter];
var ref = ann[letter + 'ref'];
var aref = ann['a' + letter + 'ref'];
var padplus = ann['_' + letter + 'padplus'];
var padminus = ann['_' + letter + 'padminus'];
var shift = {
x: 1,
y: -1
}[letter] * ann[letter + 'shift'];
var headSize = 3 * ann.arrowsize * ann.arrowwidth || 0;
var headPlus = headSize + shift;
var headMinus = headSize - shift;
var startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0;
var startHeadPlus = startHeadSize + shift;
var startHeadMinus = startHeadSize - shift;
var extremes;
if (aref === ref) {
// expand for the arrowhead (padded by arrowhead)
var extremeArrowHead = Axes.findExtremes(ax, [ax.r2c(pos)], {
ppadplus: headPlus,
ppadminus: headMinus
});
// again for the textbox (padded by textbox)
var extremeText = Axes.findExtremes(ax, [ax.r2c(apos)], {
ppadplus: Math.max(padplus, startHeadPlus),
ppadminus: Math.max(padminus, startHeadMinus)
});
extremes = {
min: [extremeArrowHead.min[0], extremeText.min[0]],
max: [extremeArrowHead.max[0], extremeText.max[0]]
};
} else {
startHeadPlus = apos ? startHeadPlus + apos : startHeadPlus;
startHeadMinus = apos ? startHeadMinus - apos : startHeadMinus;
extremes = Axes.findExtremes(ax, [ax.r2c(pos)], {
ppadplus: Math.max(padplus, headPlus, startHeadPlus),
ppadminus: Math.max(padminus, headMinus, startHeadMinus)
});
}
ann._extremes[axId] = extremes;
}
/***/ }),
/***/ 42300:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var arrayEditor = (__webpack_require__(31780).arrayEditor);
module.exports = {
hasClickToShow: hasClickToShow,
onClick: onClick
};
/*
* hasClickToShow: does the given hoverData have ANY annotations which will
* turn ON if we click here? (used by hover events to set cursor)
*
* gd: graphDiv
* hoverData: a hoverData array, as included with the *plotly_hover* or
* *plotly_click* events in the `points` attribute
*
* returns: boolean
*/
function hasClickToShow(gd, hoverData) {
var sets = getToggleSets(gd, hoverData);
return sets.on.length > 0 || sets.explicitOff.length > 0;
}
/*
* onClick: perform the toggling (via Plotly.update) implied by clicking
* at this hoverData
*
* gd: graphDiv
* hoverData: a hoverData array, as included with the *plotly_hover* or
* *plotly_click* events in the `points` attribute
*
* returns: Promise that the update is complete
*/
function onClick(gd, hoverData) {
var toggleSets = getToggleSets(gd, hoverData);
var onSet = toggleSets.on;
var offSet = toggleSets.off.concat(toggleSets.explicitOff);
var update = {};
var annotationsOut = gd._fullLayout.annotations;
var i, editHelpers;
if (!(onSet.length || offSet.length)) return;
for (i = 0; i < onSet.length; i++) {
editHelpers = arrayEditor(gd.layout, 'annotations', annotationsOut[onSet[i]]);
editHelpers.modifyItem('visible', true);
Lib.extendFlat(update, editHelpers.getUpdateObj());
}
for (i = 0; i < offSet.length; i++) {
editHelpers = arrayEditor(gd.layout, 'annotations', annotationsOut[offSet[i]]);
editHelpers.modifyItem('visible', false);
Lib.extendFlat(update, editHelpers.getUpdateObj());
}
return Registry.call('update', gd, {}, update);
}
/*
* getToggleSets: find the annotations which will turn on or off at this
* hoverData
*
* gd: graphDiv
* hoverData: a hoverData array, as included with the *plotly_hover* or
* *plotly_click* events in the `points` attribute
*
* returns: {
* on: Array (indices of annotations to turn on),
* off: Array (indices to turn off because you're not hovering on them),
* explicitOff: Array (indices to turn off because you *are* hovering on them)
* }
*/
function getToggleSets(gd, hoverData) {
var annotations = gd._fullLayout.annotations;
var onSet = [];
var offSet = [];
var explicitOffSet = [];
var hoverLen = (hoverData || []).length;
var i, j, anni, showMode, pointj, xa, ya, toggleType;
for (i = 0; i < annotations.length; i++) {
anni = annotations[i];
showMode = anni.clicktoshow;
if (showMode) {
for (j = 0; j < hoverLen; j++) {
pointj = hoverData[j];
xa = pointj.xaxis;
ya = pointj.yaxis;
if (xa._id === anni.xref && ya._id === anni.yref && xa.d2r(pointj.x) === clickData2r(anni._xclick, xa) && ya.d2r(pointj.y) === clickData2r(anni._yclick, ya)) {
// match! toggle this annotation
// regardless of its clicktoshow mode
// but if it's onout mode, off is implicit
if (anni.visible) {
if (showMode === 'onout') toggleType = offSet;else toggleType = explicitOffSet;
} else {
toggleType = onSet;
}
toggleType.push(i);
break;
}
}
if (j === hoverLen) {
// no match - only turn this annotation OFF, and only if
// showmode is 'onout'
if (anni.visible && showMode === 'onout') offSet.push(i);
}
}
}
return {
on: onSet,
off: offSet,
explicitOff: explicitOffSet
};
}
// to handle log axes until v3
function clickData2r(d, ax) {
return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d);
}
/***/ }),
/***/ 87192:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
// defaults common to 'annotations' and 'annotations3d'
module.exports = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) {
coerce('opacity');
var bgColor = coerce('bgcolor');
var borderColor = coerce('bordercolor');
var borderOpacity = Color.opacity(borderColor);
coerce('borderpad');
var borderWidth = coerce('borderwidth');
var showArrow = coerce('showarrow');
coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation);
coerce('textangle');
Lib.coerceFont(coerce, 'font', fullLayout.font);
coerce('width');
coerce('align');
var h = coerce('height');
if (h) coerce('valign');
if (showArrow) {
var arrowside = coerce('arrowside');
var arrowhead;
var arrowsize;
if (arrowside.indexOf('end') !== -1) {
arrowhead = coerce('arrowhead');
arrowsize = coerce('arrowsize');
}
if (arrowside.indexOf('start') !== -1) {
coerce('startarrowhead', arrowhead);
coerce('startarrowsize', arrowsize);
}
coerce('arrowcolor', borderOpacity ? annOut.bordercolor : Color.defaultLine);
coerce('arrowwidth', (borderOpacity && borderWidth || 1) * 2);
coerce('standoff');
coerce('startstandoff');
}
var hoverText = coerce('hovertext');
var globalHoverLabel = fullLayout.hoverlabel || {};
if (hoverText) {
var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || (Color.opacity(bgColor) ? Color.rgb(bgColor) : Color.defaultLine));
var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || Color.contrast(hoverBG));
var fontDflt = Lib.extendFlat({}, globalHoverLabel.font);
if (!fontDflt.color) {
fontDflt.color = hoverBorder;
}
Lib.coerceFont(coerce, 'hoverlabel.font', fontDflt);
}
coerce('captureevents', !!hoverText);
};
/***/ }),
/***/ 26828:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var toLogRange = __webpack_require__(36896);
/*
* convertCoords: when converting an axis between log and linear
* you need to alter any annotations on that axis to keep them
* pointing at the same data point.
* In v3.0 this will become obsolete
*
* gd: the plot div
* ax: the axis being changed
* newType: the type it's getting
* doExtra: function(attr, val) from inside relayout that sets the attribute.
* Use this to make the changes as it's aware if any other changes in the
* same relayout call should override this conversion.
*/
module.exports = function convertCoords(gd, ax, newType, doExtra) {
ax = ax || {};
var toLog = newType === 'log' && ax.type === 'linear';
var fromLog = newType === 'linear' && ax.type === 'log';
if (!(toLog || fromLog)) return;
var annotations = gd._fullLayout.annotations;
var axLetter = ax._id.charAt(0);
var ann;
var attrPrefix;
function convert(attr) {
var currentVal = ann[attr];
var newVal = null;
if (toLog) newVal = toLogRange(currentVal, ax.range);else newVal = Math.pow(10, currentVal);
// if conversion failed, delete the value so it gets a default value
if (!isNumeric(newVal)) newVal = null;
doExtra(attrPrefix + attr, newVal);
}
for (var i = 0; i < annotations.length; i++) {
ann = annotations[i];
attrPrefix = 'annotations[' + i + '].';
if (ann[axLetter + 'ref'] === ax._id) convert(axLetter);
if (ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter);
}
};
/***/ }),
/***/ 45216:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var handleArrayContainerDefaults = __webpack_require__(51272);
var handleAnnotationCommonDefaults = __webpack_require__(87192);
var attributes = __webpack_require__(13916);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
handleArrayContainerDefaults(layoutIn, layoutOut, {
name: 'annotations',
handleItemDefaults: handleAnnotationDefaults
});
};
function handleAnnotationDefaults(annIn, annOut, fullLayout) {
function coerce(attr, dflt) {
return Lib.coerce(annIn, annOut, attributes, attr, dflt);
}
var visible = coerce('visible');
var clickToShow = coerce('clicktoshow');
if (!(visible || clickToShow)) return;
handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce);
var showArrow = annOut.showarrow;
// positioning
var axLetters = ['x', 'y'];
var arrowPosDflt = [-10, -30];
var gdMock = {
_fullLayout: fullLayout
};
for (var i = 0; i < 2; i++) {
var axLetter = axLetters[i];
// xref, yref
var axRef = Axes.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper');
if (axRef !== 'paper') {
var ax = Axes.getFromId(gdMock, axRef);
ax._annIndices.push(annOut._index);
}
// x, y
Axes.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5);
if (showArrow) {
var arrowPosAttr = 'a' + axLetter;
// axref, ayref
var aaxRef = Axes.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel', ['pixel', 'paper']);
// for now the arrow can only be on the same axis or specified as pixels
// TODO: sometime it might be interesting to allow it to be on *any* axis
// but that would require updates to drawing & autorange code and maybe more
if (aaxRef !== 'pixel' && aaxRef !== axRef) {
aaxRef = annOut[arrowPosAttr] = 'pixel';
}
// ax, ay
var aDflt = aaxRef === 'pixel' ? arrowPosDflt[i] : 0.4;
Axes.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt);
}
// xanchor, yanchor
coerce(axLetter + 'anchor');
// xshift, yshift
coerce(axLetter + 'shift');
}
// if you have one coordinate you should have both
Lib.noneOrAll(annIn, annOut, ['x', 'y']);
// if you have one part of arrow length you should have both
if (showArrow) {
Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
}
if (clickToShow) {
var xClick = coerce('xclick');
var yClick = coerce('yclick');
// put the actual click data to bind to into private attributes
// so we don't have to do this little bit of logic on every hover event
annOut._xclick = xClick === undefined ? annOut.x : Axes.cleanPosition(xClick, gdMock, annOut.xref);
annOut._yclick = yClick === undefined ? annOut.y : Axes.cleanPosition(yClick, gdMock, annOut.yref);
}
}
/***/ }),
/***/ 23816:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Registry = __webpack_require__(24040);
var Plots = __webpack_require__(7316);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var Axes = __webpack_require__(54460);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Fx = __webpack_require__(93024);
var svgTextUtils = __webpack_require__(72736);
var setCursor = __webpack_require__(93972);
var dragElement = __webpack_require__(86476);
var arrayEditor = (__webpack_require__(31780).arrayEditor);
var drawArrowHead = __webpack_require__(33652);
// Annotations are stored in gd.layout.annotations, an array of objects
// index can point to one item in this array,
// or non-numeric to simply add a new one
// or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
// or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
// annotation at that point in the array, or 'remove' to delete this one
module.exports = {
draw: draw,
drawOne: drawOne,
drawRaw: drawRaw
};
/*
* draw: draw all annotations without any new modifications
*/
function draw(gd) {
var fullLayout = gd._fullLayout;
fullLayout._infolayer.selectAll('.annotation').remove();
for (var i = 0; i < fullLayout.annotations.length; i++) {
if (fullLayout.annotations[i].visible) {
drawOne(gd, i);
}
}
return Plots.previousPromises(gd);
}
/*
* drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications
*
* index (int): the annotation to draw
*/
function drawOne(gd, index) {
var fullLayout = gd._fullLayout;
var options = fullLayout.annotations[index] || {};
var xa = Axes.getFromId(gd, options.xref);
var ya = Axes.getFromId(gd, options.yref);
if (xa) xa.setScale();
if (ya) ya.setScale();
drawRaw(gd, options, index, false, xa, ya);
}
// Convert pixels to the coordinates relevant for the axis referred to. For
// example, for paper it would convert to a value normalized by the dimension of
// the plot.
// axDomainRef: if true and axa defined, draws relative to axis domain,
// otherwise draws relative to data (if axa defined) or paper (if not).
function shiftPosition(axa, dAx, axLetter, gs, options) {
var optAx = options[axLetter];
var axRef = options[axLetter + 'ref'];
var vertical = axLetter.indexOf('y') !== -1;
var axDomainRef = Axes.getRefType(axRef) === 'domain';
var gsDim = vertical ? gs.h : gs.w;
if (axa) {
if (axDomainRef) {
// here optAx normalized to length of axis (e.g., normally in range
// 0 to 1). But dAx is in pixels. So we normalize dAx to length of
// axis before doing the math.
return optAx + (vertical ? -dAx : dAx) / axa._length;
} else {
return axa.p2r(axa.r2p(optAx) + dAx);
}
} else {
return optAx + (vertical ? -dAx : dAx) / gsDim;
}
}
/**
* drawRaw: draw a single annotation, potentially with modifications
*
* @param {DOM element} gd
* @param {object} options : this annotation's fullLayout options
* @param {integer} index : index in 'annotations' container of the annotation to draw
* @param {string} subplotId : id of the annotation's subplot
* - use false for 2d (i.e. cartesian or paper-ref) annotations
* @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px
* @param {object | undefined} ya : ... y-axis
*/
function drawRaw(gd, options, index, subplotId, xa, ya) {
var fullLayout = gd._fullLayout;
var gs = gd._fullLayout._size;
var edits = gd._context.edits;
var className, containerStr;
if (subplotId) {
className = 'annotation-' + subplotId;
containerStr = subplotId + '.annotations';
} else {
className = 'annotation';
containerStr = 'annotations';
}
var editHelpers = arrayEditor(gd.layout, containerStr, options);
var modifyBase = editHelpers.modifyBase;
var modifyItem = editHelpers.modifyItem;
var getUpdateObj = editHelpers.getUpdateObj;
// remove the existing annotation if there is one
fullLayout._infolayer.selectAll('.' + className + '[data-index="' + index + '"]').remove();
var annClipID = 'clip' + fullLayout._uid + '_ann' + index;
// this annotation is gone - quit now after deleting it
// TODO: use d3 idioms instead of deleting and redrawing every time
if (!options._input || options.visible === false) {
d3.selectAll('#' + annClipID).remove();
return;
}
// calculated pixel positions
// x & y each will get text, head, and tail as appropriate
var annPosPx = {
x: {},
y: {}
};
var textangle = +options.textangle || 0;
// create the components
// made a single group to contain all, so opacity can work right
// with border/arrow together this could handle a whole bunch of
// cleanup at this point, but works for now
var annGroup = fullLayout._infolayer.append('g').classed(className, true).attr('data-index', String(index)).style('opacity', options.opacity);
// another group for text+background so that they can rotate together
var annTextGroup = annGroup.append('g').classed('annotation-text-g', true);
var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition'];
var textEvents = options.captureevents || edits.annotationText || editTextPosition;
function makeEventData(initialEvent) {
var eventData = {
index: index,
annotation: options._input,
fullAnnotation: options,
event: initialEvent
};
if (subplotId) {
eventData.subplotId = subplotId;
}
return eventData;
}
var annTextGroupInner = annTextGroup.append('g').style('pointer-events', textEvents ? 'all' : null).call(setCursor, 'pointer').on('click', function () {
gd._dragging = false;
gd.emit('plotly_clickannotation', makeEventData(d3.event));
});
if (options.hovertext) {
annTextGroupInner.on('mouseover', function () {
var hoverOptions = options.hoverlabel;
var hoverFont = hoverOptions.font;
var bBox = this.getBoundingClientRect();
var bBoxRef = gd.getBoundingClientRect();
Fx.loneHover({
x0: bBox.left - bBoxRef.left,
x1: bBox.right - bBoxRef.left,
y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top,
text: options.hovertext,
color: hoverOptions.bgcolor,
borderColor: hoverOptions.bordercolor,
fontFamily: hoverFont.family,
fontSize: hoverFont.size,
fontColor: hoverFont.color,
fontWeight: hoverFont.weight,
fontStyle: hoverFont.style,
fontVariant: hoverFont.variant,
fontShadow: hoverFont.fontShadow,
fontLineposition: hoverFont.fontLineposition,
fontTextcase: hoverFont.fontTextcase
}, {
container: fullLayout._hoverlayer.node(),
outerContainer: fullLayout._paper.node(),
gd: gd
});
}).on('mouseout', function () {
Fx.loneUnhover(fullLayout._hoverlayer.node());
});
}
var borderwidth = options.borderwidth;
var borderpad = options.borderpad;
var borderfull = borderwidth + borderpad;
var annTextBG = annTextGroupInner.append('rect').attr('class', 'bg').style('stroke-width', borderwidth + 'px').call(Color.stroke, options.bordercolor).call(Color.fill, options.bgcolor);
var isSizeConstrained = options.width || options.height;
var annTextClip = fullLayout._topclips.selectAll('#' + annClipID).data(isSizeConstrained ? [0] : []);
annTextClip.enter().append('clipPath').classed('annclip', true).attr('id', annClipID).append('rect');
annTextClip.exit().remove();
var font = options.font;
var text = fullLayout._meta ? Lib.templateString(options.text, fullLayout._meta) : options.text;
var annText = annTextGroupInner.append('text').classed('annotation-text', true).text(text);
function textLayout(s) {
s.call(Drawing.font, font).attr({
'text-anchor': {
left: 'start',
right: 'end'
}[options.align] || 'middle'
});
svgTextUtils.convertToTspans(s, gd, drawGraphicalElements);
return s;
}
function drawGraphicalElements() {
// if the text has *only* a link, make the whole box into a link
var anchor3 = annText.selectAll('a');
if (anchor3.size() === 1 && anchor3.text() === annText.text()) {
var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({
'xlink:xlink:href': anchor3.attr('xlink:href'),
'xlink:xlink:show': anchor3.attr('xlink:show')
}).style({
cursor: 'pointer'
});
wholeLink.node().appendChild(annTextBG.node());
}
var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group');
var hasMathjax = !mathjaxGroup.empty();
var anntextBB = Drawing.bBox((hasMathjax ? mathjaxGroup : annText).node());
var textWidth = anntextBB.width;
var textHeight = anntextBB.height;
var annWidth = options.width || textWidth;
var annHeight = options.height || textHeight;
var outerWidth = Math.round(annWidth + 2 * borderfull);
var outerHeight = Math.round(annHeight + 2 * borderfull);
function shiftFraction(v, anchor) {
if (anchor === 'auto') {
if (v < 1 / 3) anchor = 'left';else if (v > 2 / 3) anchor = 'right';else anchor = 'center';
}
return {
center: 0,
middle: 0,
left: 0.5,
bottom: -0.5,
right: -0.5,
top: 0.5
}[anchor];
}
var annotationIsOffscreen = false;
var letters = ['x', 'y'];
for (var i = 0; i < letters.length; i++) {
var axLetter = letters[i];
var axRef = options[axLetter + 'ref'] || axLetter;
var tailRef = options['a' + axLetter + 'ref'];
var ax = {
x: xa,
y: ya
}[axLetter];
var dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180;
// note that these two can be either positive or negative
var annSizeFromWidth = outerWidth * Math.cos(dimAngle);
var annSizeFromHeight = outerHeight * Math.sin(dimAngle);
// but this one is the positive total size
var annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight);
var anchor = options[axLetter + 'anchor'];
var overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1);
var posPx = annPosPx[axLetter];
var basePx;
var textPadShift;
var alignPosition;
var autoAlignFraction;
var textShift;
var axRefType = Axes.getRefType(axRef);
/*
* calculate the *primary* pixel position
* which is the arrowhead if there is one,
* otherwise the text anchor point
*/
if (ax && axRefType !== 'domain') {
// check if annotation is off screen, to bypass DOM manipulations
var posFraction = ax.r2fraction(options[axLetter]);
if (posFraction < 0 || posFraction > 1) {
if (tailRef === axRef) {
posFraction = ax.r2fraction(options['a' + axLetter]);
if (posFraction < 0 || posFraction > 1) {
annotationIsOffscreen = true;
}
} else {
annotationIsOffscreen = true;
}
}
basePx = ax._offset + ax.r2p(options[axLetter]);
autoAlignFraction = 0.5;
} else {
var axRefTypeEqDomain = axRefType === 'domain';
if (axLetter === 'x') {
alignPosition = options[axLetter];
basePx = axRefTypeEqDomain ? ax._offset + ax._length * alignPosition : basePx = gs.l + gs.w * alignPosition;
} else {
alignPosition = 1 - options[axLetter];
basePx = axRefTypeEqDomain ? ax._offset + ax._length * alignPosition : basePx = gs.t + gs.h * alignPosition;
}
autoAlignFraction = options.showarrow ? 0.5 : alignPosition;
}
// now translate this into pixel positions of head, tail, and text
// as well as paddings for autorange
if (options.showarrow) {
posPx.head = basePx;
var arrowLength = options['a' + axLetter];
// with an arrow, the text rotates around the anchor point
textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) - annSizeFromHeight * shiftFraction(0.5, options.yanchor);
if (tailRef === axRef) {
// In the case tailRefType is 'domain' or 'paper', the arrow's
// position is set absolutely, which is consistent with how
// it behaves when its position is set in data ('range')
// coordinates.
var tailRefType = Axes.getRefType(tailRef);
if (tailRefType === 'domain') {
if (axLetter === 'y') {
arrowLength = 1 - arrowLength;
}
posPx.tail = ax._offset + ax._length * arrowLength;
} else if (tailRefType === 'paper') {
if (axLetter === 'y') {
arrowLength = 1 - arrowLength;
posPx.tail = gs.t + gs.h * arrowLength;
} else {
posPx.tail = gs.l + gs.w * arrowLength;
}
} else {
// assumed tailRef is range or paper referenced
posPx.tail = ax._offset + ax.r2p(arrowLength);
}
// tail is range- or domain-referenced: autorange pads the
// text in px from the tail
textPadShift = textShift;
} else {
posPx.tail = basePx + arrowLength;
// tail is specified in px from head, so autorange also pads vs head
textPadShift = textShift + arrowLength;
}
posPx.text = posPx.tail + textShift;
// constrain pixel/paper referenced so the draggers are at least
// partially visible
var maxPx = fullLayout[axLetter === 'x' ? 'width' : 'height'];
if (axRef === 'paper') {
posPx.head = Lib.constrain(posPx.head, 1, maxPx - 1);
}
if (tailRef === 'pixel') {
var shiftPlus = -Math.max(posPx.tail - 3, posPx.text);
var shiftMinus = Math.min(posPx.tail + 3, posPx.text) - maxPx;
if (shiftPlus > 0) {
posPx.tail += shiftPlus;
posPx.text += shiftPlus;
} else if (shiftMinus > 0) {
posPx.tail -= shiftMinus;
posPx.text -= shiftMinus;
}
}
posPx.tail += overallShift;
posPx.head += overallShift;
} else {
// with no arrow, the text rotates and *then* we put the anchor
// relative to the new bounding box
textShift = annSize * shiftFraction(autoAlignFraction, anchor);
textPadShift = textShift;
posPx.text = basePx + textShift;
}
posPx.text += overallShift;
textShift += overallShift;
textPadShift += overallShift;
// padplus/minus are used by autorange
options['_' + axLetter + 'padplus'] = annSize / 2 + textPadShift;
options['_' + axLetter + 'padminus'] = annSize / 2 - textPadShift;
// size/shift are used during dragging
options['_' + axLetter + 'size'] = annSize;
options['_' + axLetter + 'shift'] = textShift;
}
if (annotationIsOffscreen) {
annTextGroupInner.remove();
return;
}
var xShift = 0;
var yShift = 0;
if (options.align !== 'left') {
xShift = (annWidth - textWidth) * (options.align === 'center' ? 0.5 : 1);
}
if (options.valign !== 'top') {
yShift = (annHeight - textHeight) * (options.valign === 'middle' ? 0.5 : 1);
}
if (hasMathjax) {
mathjaxGroup.select('svg').attr({
x: borderfull + xShift - 1,
y: borderfull + yShift
}).call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
} else {
var texty = borderfull + yShift - anntextBB.top;
var textx = borderfull + xShift - anntextBB.left;
annText.call(svgTextUtils.positionText, textx, texty).call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
}
annTextClip.select('rect').call(Drawing.setRect, borderfull, borderfull, annWidth, annHeight);
annTextBG.call(Drawing.setRect, borderwidth / 2, borderwidth / 2, outerWidth - borderwidth, outerHeight - borderwidth);
annTextGroupInner.call(Drawing.setTranslate, Math.round(annPosPx.x.text - outerWidth / 2), Math.round(annPosPx.y.text - outerHeight / 2));
/*
* rotate text and background
* we already calculated the text center position *as rotated*
* because we needed that for autoranging anyway, so now whether
* we have an arrow or not, we rotate about the text center.
*/
annTextGroup.attr({
transform: 'rotate(' + textangle + ',' + annPosPx.x.text + ',' + annPosPx.y.text + ')'
});
/*
* add the arrow
* uses options[arrowwidth,arrowcolor,arrowhead] for styling
* dx and dy are normally zero, but when you are dragging the textbox
* while the head stays put, dx and dy are the pixel offsets
*/
var drawArrow = function (dx, dy) {
annGroup.selectAll('.annotation-arrow-g').remove();
var headX = annPosPx.x.head;
var headY = annPosPx.y.head;
var tailX = annPosPx.x.tail + dx;
var tailY = annPosPx.y.tail + dy;
var textX = annPosPx.x.text + dx;
var textY = annPosPx.y.text + dy;
// find the edge of the text box, where we'll start the arrow:
// create transform matrix to rotate the text box corners
var transform = Lib.rotationXYMatrix(textangle, textX, textY);
var applyTransform = Lib.apply2DTransform(transform);
var applyTransform2 = Lib.apply2DTransform2(transform);
// calculate and transform bounding box
var width = +annTextBG.attr('width');
var height = +annTextBG.attr('height');
var xLeft = textX - 0.5 * width;
var xRight = xLeft + width;
var yTop = textY - 0.5 * height;
var yBottom = yTop + height;
var edges = [[xLeft, yTop, xLeft, yBottom], [xLeft, yBottom, xRight, yBottom], [xRight, yBottom, xRight, yTop], [xRight, yTop, xLeft, yTop]].map(applyTransform2);
// Remove the line if it ends inside the box. Use ray
// casting for rotated boxes: see which edges intersect a
// line from the arrowhead to far away and reduce with xor
// to get the parity of the number of intersections.
if (edges.reduce(function (a, x) {
return a ^ !!Lib.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, x[0], x[1], x[2], x[3]);
}, false)) {
// no line or arrow - so quit drawArrow now
return;
}
edges.forEach(function (x) {
var p = Lib.segmentsIntersect(tailX, tailY, headX, headY, x[0], x[1], x[2], x[3]);
if (p) {
tailX = p.x;
tailY = p.y;
}
});
var strokewidth = options.arrowwidth;
var arrowColor = options.arrowcolor;
var arrowSide = options.arrowside;
var arrowGroup = annGroup.append('g').style({
opacity: Color.opacity(arrowColor)
}).classed('annotation-arrow-g', true);
var arrow = arrowGroup.append('path').attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY).style('stroke-width', strokewidth + 'px').call(Color.stroke, Color.rgb(arrowColor));
drawArrowHead(arrow, arrowSide, options);
// the arrow dragger is a small square right at the head, then a line to the tail,
// all expanded by a stroke width of 6px plus the arrow line width
if (edits.annotationPosition && arrow.node().parentNode && !subplotId) {
var arrowDragHeadX = headX;
var arrowDragHeadY = headY;
if (options.standoff) {
var arrowLength = Math.sqrt(Math.pow(headX - tailX, 2) + Math.pow(headY - tailY, 2));
arrowDragHeadX += options.standoff * (tailX - headX) / arrowLength;
arrowDragHeadY += options.standoff * (tailY - headY) / arrowLength;
}
var arrowDrag = arrowGroup.append('path').classed('annotation-arrow', true).classed('anndrag', true).classed('cursor-move', true).attr({
d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY),
transform: strTranslate(arrowDragHeadX, arrowDragHeadY)
}).style('stroke-width', strokewidth + 6 + 'px').call(Color.stroke, 'rgba(0,0,0,0)').call(Color.fill, 'rgba(0,0,0,0)');
var annx0, anny0;
// dragger for the arrow & head: translates the whole thing
// (head/tail/text) all together
dragElement.init({
element: arrowDrag.node(),
gd: gd,
prepFn: function () {
var pos = Drawing.getTranslate(annTextGroupInner);
annx0 = pos.x;
anny0 = pos.y;
if (xa && xa.autorange) {
modifyBase(xa._name + '.autorange', true);
}
if (ya && ya.autorange) {
modifyBase(ya._name + '.autorange', true);
}
},
moveFn: function (dx, dy) {
var annxy0 = applyTransform(annx0, anny0);
var xcenter = annxy0[0] + dx;
var ycenter = annxy0[1] + dy;
annTextGroupInner.call(Drawing.setTranslate, xcenter, ycenter);
modifyItem('x', shiftPosition(xa, dx, 'x', gs, options));
modifyItem('y', shiftPosition(ya, dy, 'y', gs, options));
// for these 2 calls to shiftPosition, it is assumed xa, ya are
// defined, so gsDim will not be used, but we put it in
// anyways for consistency
if (options.axref === options.xref) {
modifyItem('ax', shiftPosition(xa, dx, 'ax', gs, options));
}
if (options.ayref === options.yref) {
modifyItem('ay', shiftPosition(ya, dy, 'ay', gs, options));
}
arrowGroup.attr('transform', strTranslate(dx, dy));
annTextGroup.attr({
transform: 'rotate(' + textangle + ',' + xcenter + ',' + ycenter + ')'
});
},
doneFn: function () {
Registry.call('_guiRelayout', gd, getUpdateObj());
var notesBox = document.querySelector('.js-notes-box-panel');
if (notesBox) notesBox.redraw(notesBox.selectedObj);
}
});
}
};
if (options.showarrow) drawArrow(0, 0);
// user dragging the annotation (text, not arrow)
if (editTextPosition) {
var baseTextTransform;
// dragger for the textbox: if there's an arrow, just drag the
// textbox and tail, leave the head untouched
dragElement.init({
element: annTextGroupInner.node(),
gd: gd,
prepFn: function () {
baseTextTransform = annTextGroup.attr('transform');
},
moveFn: function (dx, dy) {
var csr = 'pointer';
if (options.showarrow) {
// for these 2 calls to shiftPosition, it is assumed xa, ya are
// defined, so gsDim will not be used, but we put it in
// anyways for consistency
if (options.axref === options.xref) {
modifyItem('ax', shiftPosition(xa, dx, 'ax', gs, options));
} else {
modifyItem('ax', options.ax + dx);
}
if (options.ayref === options.yref) {
modifyItem('ay', shiftPosition(ya, dy, 'ay', gs.w, options));
} else {
modifyItem('ay', options.ay + dy);
}
drawArrow(dx, dy);
} else if (!subplotId) {
var xUpdate, yUpdate;
if (xa) {
// shiftPosition will not execute code where xa was
// undefined, so we use to calculate xUpdate too
xUpdate = shiftPosition(xa, dx, 'x', gs, options);
} else {
var widthFraction = options._xsize / gs.w;
var xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2;
xUpdate = dragElement.align(xLeft + dx / gs.w, widthFraction, 0, 1, options.xanchor);
}
if (ya) {
// shiftPosition will not execute code where ya was
// undefined, so we use to calculate yUpdate too
yUpdate = shiftPosition(ya, dy, 'y', gs, options);
} else {
var heightFraction = options._ysize / gs.h;
var yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2;
yUpdate = dragElement.align(yBottom - dy / gs.h, heightFraction, 0, 1, options.yanchor);
}
modifyItem('x', xUpdate);
modifyItem('y', yUpdate);
if (!xa || !ya) {
csr = dragElement.getCursor(xa ? 0.5 : xUpdate, ya ? 0.5 : yUpdate, options.xanchor, options.yanchor);
}
} else return;
annTextGroup.attr({
transform: strTranslate(dx, dy) + baseTextTransform
});
setCursor(annTextGroupInner, csr);
},
clickFn: function (_, initialEvent) {
if (options.captureevents) {
gd.emit('plotly_clickannotation', makeEventData(initialEvent));
}
},
doneFn: function () {
setCursor(annTextGroupInner);
Registry.call('_guiRelayout', gd, getUpdateObj());
var notesBox = document.querySelector('.js-notes-box-panel');
if (notesBox) notesBox.redraw(notesBox.selectedObj);
}
});
}
}
if (edits.annotationText) {
annText.call(svgTextUtils.makeEditable, {
delegate: annTextGroupInner,
gd: gd
}).call(textLayout).on('edit', function (_text) {
options.text = _text;
this.call(textLayout);
modifyItem('text', _text);
if (xa && xa.autorange) {
modifyBase(xa._name + '.autorange', true);
}
if (ya && ya.autorange) {
modifyBase(ya._name + '.autorange', true);
}
Registry.call('_guiRelayout', gd, getUpdateObj());
});
} else annText.call(textLayout);
}
/***/ }),
/***/ 33652:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
var ARROWPATHS = __webpack_require__(72196);
var Lib = __webpack_require__(3400);
var strScale = Lib.strScale;
var strRotate = Lib.strRotate;
var strTranslate = Lib.strTranslate;
/**
* Add arrowhead(s) to a path or line element
*
* @param {d3.selection} el3: a d3-selected line or path element
*
* @param {string} ends: 'none', 'start', 'end', or 'start+end' for which ends get arrowheads
*
* @param {object} options: style information. Must have all the following:
* @param {number} options.arrowhead: end head style - see ./arrow_paths
* @param {number} options.startarrowhead: start head style - see ./arrow_paths
* @param {number} options.arrowsize: relative size of the end head vs line width
* @param {number} options.startarrowsize: relative size of the start head vs line width
* @param {number} options.standoff: distance in px to move the end arrow point from its target
* @param {number} options.startstandoff: distance in px to move the start arrow point from its target
* @param {number} options.arrowwidth: width of the arrow line
* @param {string} options.arrowcolor: color of the arrow line, for the head to match
* Note that the opacity of this color is ignored, as it's assumed the container
* of both the line and head has opacity applied to it so there isn't greater opacity
* where they overlap.
*/
module.exports = function drawArrowHead(el3, ends, options) {
var el = el3.node();
var headStyle = ARROWPATHS[options.arrowhead || 0];
var startHeadStyle = ARROWPATHS[options.startarrowhead || 0];
var scale = (options.arrowwidth || 1) * (options.arrowsize || 1);
var startScale = (options.arrowwidth || 1) * (options.startarrowsize || 1);
var doStart = ends.indexOf('start') >= 0;
var doEnd = ends.indexOf('end') >= 0;
var backOff = headStyle.backoff * scale + options.standoff;
var startBackOff = startHeadStyle.backoff * startScale + options.startstandoff;
var start, end, startRot, endRot;
if (el.nodeName === 'line') {
start = {
x: +el3.attr('x1'),
y: +el3.attr('y1')
};
end = {
x: +el3.attr('x2'),
y: +el3.attr('y2')
};
var dx = start.x - end.x;
var dy = start.y - end.y;
startRot = Math.atan2(dy, dx);
endRot = startRot + Math.PI;
if (backOff && startBackOff) {
if (backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) {
hideLine();
return;
}
}
if (backOff) {
if (backOff * backOff > dx * dx + dy * dy) {
hideLine();
return;
}
var backOffX = backOff * Math.cos(startRot);
var backOffY = backOff * Math.sin(startRot);
end.x += backOffX;
end.y += backOffY;
el3.attr({
x2: end.x,
y2: end.y
});
}
if (startBackOff) {
if (startBackOff * startBackOff > dx * dx + dy * dy) {
hideLine();
return;
}
var startBackOffX = startBackOff * Math.cos(startRot);
var startbackOffY = startBackOff * Math.sin(startRot);
start.x -= startBackOffX;
start.y -= startbackOffY;
el3.attr({
x1: start.x,
y1: start.y
});
}
} else if (el.nodeName === 'path') {
var pathlen = el.getTotalLength();
// using dash to hide the backOff region of the path.
// if we ever allow dash for the arrow we'll have to
// do better than this hack... maybe just manually
// combine the two
var dashArray = '';
if (pathlen < backOff + startBackOff) {
hideLine();
return;
}
var start0 = el.getPointAtLength(0);
var dstart = el.getPointAtLength(0.1);
startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x);
start = el.getPointAtLength(Math.min(startBackOff, pathlen));
dashArray = '0px,' + startBackOff + 'px,';
var end0 = el.getPointAtLength(pathlen);
var dend = el.getPointAtLength(pathlen - 0.1);
endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x);
end = el.getPointAtLength(Math.max(0, pathlen - backOff));
var shortening = dashArray ? startBackOff + backOff : backOff;
dashArray += pathlen - shortening + 'px,' + pathlen + 'px';
el3.style('stroke-dasharray', dashArray);
}
function hideLine() {
el3.style('stroke-dasharray', '0px,100px');
}
function drawhead(arrowHeadStyle, p, rot, arrowScale) {
if (!arrowHeadStyle.path) return;
if (arrowHeadStyle.noRotate) rot = 0;
d3.select(el.parentNode).append('path').attr({
class: el3.attr('class'),
d: arrowHeadStyle.path,
transform: strTranslate(p.x, p.y) + strRotate(rot * 180 / Math.PI) + strScale(arrowScale)
}).style({
fill: Color.rgb(options.arrowcolor),
'stroke-width': 0
});
}
if (doStart) drawhead(startHeadStyle, start, startRot, startScale);
if (doEnd) drawhead(headStyle, end, endRot, scale);
};
/***/ }),
/***/ 79180:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var drawModule = __webpack_require__(23816);
var clickModule = __webpack_require__(42300);
module.exports = {
moduleType: 'component',
name: 'annotations',
layoutAttributes: __webpack_require__(13916),
supplyLayoutDefaults: __webpack_require__(45216),
includeBasePlot: __webpack_require__(36632)('annotations'),
calcAutorange: __webpack_require__(90272),
draw: drawModule.draw,
drawOne: drawModule.drawOne,
drawRaw: drawModule.drawRaw,
hasClickToShow: clickModule.hasClickToShow,
onClick: clickModule.onClick,
convertCoords: __webpack_require__(26828)
};
/***/ }),
/***/ 45899:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var annAttrs = __webpack_require__(13916);
var overrideAll = (__webpack_require__(67824).overrideAll);
var templatedArray = (__webpack_require__(31780).templatedArray);
module.exports = overrideAll(templatedArray('annotation', {
visible: annAttrs.visible,
x: {
valType: 'any'
},
y: {
valType: 'any'
},
z: {
valType: 'any'
},
ax: {
valType: 'number'
},
ay: {
valType: 'number'
},
xanchor: annAttrs.xanchor,
xshift: annAttrs.xshift,
yanchor: annAttrs.yanchor,
yshift: annAttrs.yshift,
text: annAttrs.text,
textangle: annAttrs.textangle,
font: annAttrs.font,
width: annAttrs.width,
height: annAttrs.height,
opacity: annAttrs.opacity,
align: annAttrs.align,
valign: annAttrs.valign,
bgcolor: annAttrs.bgcolor,
bordercolor: annAttrs.bordercolor,
borderpad: annAttrs.borderpad,
borderwidth: annAttrs.borderwidth,
showarrow: annAttrs.showarrow,
arrowcolor: annAttrs.arrowcolor,
arrowhead: annAttrs.arrowhead,
startarrowhead: annAttrs.startarrowhead,
arrowside: annAttrs.arrowside,
arrowsize: annAttrs.arrowsize,
startarrowsize: annAttrs.startarrowsize,
arrowwidth: annAttrs.arrowwidth,
standoff: annAttrs.standoff,
startstandoff: annAttrs.startstandoff,
hovertext: annAttrs.hovertext,
hoverlabel: annAttrs.hoverlabel,
captureevents: annAttrs.captureevents
// maybes later?
// clicktoshow: annAttrs.clicktoshow,
// xclick: annAttrs.xclick,
// yclick: annAttrs.yclick,
// not needed!
// axref: 'pixel'
// ayref: 'pixel'
// xref: 'x'
// yref: 'y
// zref: 'z'
}), 'calc', 'from-root');
/***/ }),
/***/ 42456:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
module.exports = function convert(scene) {
var fullSceneLayout = scene.fullSceneLayout;
var anns = fullSceneLayout.annotations;
for (var i = 0; i < anns.length; i++) {
mockAnnAxes(anns[i], scene);
}
scene.fullLayout._infolayer.selectAll('.annotation-' + scene.id).remove();
};
function mockAnnAxes(ann, scene) {
var fullSceneLayout = scene.fullSceneLayout;
var domain = fullSceneLayout.domain;
var size = scene.fullLayout._size;
var base = {
// this gets fill in on render
pdata: null,
// to get setConvert to not execute cleanly
type: 'linear',
// don't try to update them on `editable: true`
autorange: false,
// set infinite range so that annotation draw routine
// does not try to remove 'outside-range' annotations,
// this case is handled in the render loop
range: [-Infinity, Infinity]
};
ann._xa = {};
Lib.extendFlat(ann._xa, base);
Axes.setConvert(ann._xa);
ann._xa._offset = size.l + domain.x[0] * size.w;
ann._xa.l2p = function () {
return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]);
};
ann._ya = {};
Lib.extendFlat(ann._ya, base);
Axes.setConvert(ann._ya);
ann._ya._offset = size.t + (1 - domain.y[1]) * size.h;
ann._ya.l2p = function () {
return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]);
};
}
/***/ }),
/***/ 52808:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var handleArrayContainerDefaults = __webpack_require__(51272);
var handleAnnotationCommonDefaults = __webpack_require__(87192);
var attributes = __webpack_require__(45899);
module.exports = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) {
handleArrayContainerDefaults(sceneLayoutIn, sceneLayoutOut, {
name: 'annotations',
handleItemDefaults: handleAnnotationDefaults,
fullLayout: opts.fullLayout
});
};
function handleAnnotationDefaults(annIn, annOut, sceneLayout, opts) {
function coerce(attr, dflt) {
return Lib.coerce(annIn, annOut, attributes, attr, dflt);
}
function coercePosition(axLetter) {
var axName = axLetter + 'axis';
// mock in such way that getFromId grabs correct 3D axis
var gdMock = {
_fullLayout: {}
};
gdMock._fullLayout[axName] = sceneLayout[axName];
return Axes.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5);
}
var visible = coerce('visible');
if (!visible) return;
handleAnnotationCommonDefaults(annIn, annOut, opts.fullLayout, coerce);
coercePosition('x');
coercePosition('y');
coercePosition('z');
// if you have one coordinate you should all three
Lib.noneOrAll(annIn, annOut, ['x', 'y', 'z']);
// hard-set here for completeness
annOut.xref = 'x';
annOut.yref = 'y';
annOut.zref = 'z';
coerce('xanchor');
coerce('yanchor');
coerce('xshift');
coerce('yshift');
if (annOut.showarrow) {
annOut.axref = 'pixel';
annOut.ayref = 'pixel';
// TODO maybe default values should be bigger than the 2D case?
coerce('ax', -10);
coerce('ay', -30);
// if you have one part of arrow length you should have both
Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
}
}
/***/ }),
/***/ 71836:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var drawRaw = (__webpack_require__(23816).drawRaw);
var project = __webpack_require__(94424);
var axLetters = ['x', 'y', 'z'];
module.exports = function draw(scene) {
var fullSceneLayout = scene.fullSceneLayout;
var dataScale = scene.dataScale;
var anns = fullSceneLayout.annotations;
for (var i = 0; i < anns.length; i++) {
var ann = anns[i];
var annotationIsOffscreen = false;
for (var j = 0; j < 3; j++) {
var axLetter = axLetters[j];
var pos = ann[axLetter];
var ax = fullSceneLayout[axLetter + 'axis'];
var posFraction = ax.r2fraction(pos);
if (posFraction < 0 || posFraction > 1) {
annotationIsOffscreen = true;
break;
}
}
if (annotationIsOffscreen) {
scene.fullLayout._infolayer.select('.annotation-' + scene.id + '[data-index="' + i + '"]').remove();
} else {
ann._pdata = project(scene.glplot.cameraParams, [fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2]]);
drawRaw(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya);
}
}
};
/***/ }),
/***/ 56864:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
module.exports = {
moduleType: 'component',
name: 'annotations3d',
schema: {
subplots: {
scene: {
annotations: __webpack_require__(45899)
}
}
},
layoutAttributes: __webpack_require__(45899),
handleDefaults: __webpack_require__(52808),
includeBasePlot: includeGL3D,
convert: __webpack_require__(42456),
draw: __webpack_require__(71836)
};
function includeGL3D(layoutIn, layoutOut) {
var GL3D = Registry.subplotsRegistry.gl3d;
if (!GL3D) return;
var attrRegex = GL3D.attrRegex;
var keys = Object.keys(layoutIn);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (attrRegex.test(k) && (layoutIn[k].annotations || []).length) {
Lib.pushUnique(layoutOut._basePlotModules, GL3D);
Lib.pushUnique(layoutOut._subplots.gl3d, k);
}
}
}
/***/ }),
/***/ 54976:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// a trimmed down version of:
// https://github.com/alexcjohnson/world-calendars/blob/master/dist/index.js
module.exports = __webpack_require__(38700);
__webpack_require__(15168);
__webpack_require__(67020);
__webpack_require__(89792);
__webpack_require__(55668);
__webpack_require__(65168);
__webpack_require__(2084);
__webpack_require__(26368);
__webpack_require__(24747);
__webpack_require__(65616);
__webpack_require__(30632);
__webpack_require__(73040);
__webpack_require__(1104);
__webpack_require__(51456);
__webpack_require__(4592);
__webpack_require__(45348);
/***/ }),
/***/ 97776:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var calendars = __webpack_require__(54976);
var Lib = __webpack_require__(3400);
var constants = __webpack_require__(39032);
var EPOCHJD = constants.EPOCHJD;
var ONEDAY = constants.ONEDAY;
var attributes = {
valType: 'enumerated',
values: Lib.sortObjectKeys(calendars.calendars),
editType: 'calc',
dflt: 'gregorian'
};
var handleDefaults = function (contIn, contOut, attr, dflt) {
var attrs = {};
attrs[attr] = attributes;
return Lib.coerce(contIn, contOut, attrs, attr, dflt);
};
var handleTraceDefaults = function (traceIn, traceOut, coords, layout) {
for (var i = 0; i < coords.length; i++) {
handleDefaults(traceIn, traceOut, coords[i] + 'calendar', layout.calendar);
}
};
// each calendar needs its own default canonical tick. I would love to use
// 2000-01-01 (or even 0000-01-01) for them all but they don't necessarily
// all support either of those dates. Instead I'll use the most significant
// number they *do* support, biased toward the present day.
var CANONICAL_TICK = {
chinese: '2000-01-01',
coptic: '2000-01-01',
discworld: '2000-01-01',
ethiopian: '2000-01-01',
hebrew: '5000-01-01',
islamic: '1000-01-01',
julian: '2000-01-01',
mayan: '5000-01-01',
nanakshahi: '1000-01-01',
nepali: '2000-01-01',
persian: '1000-01-01',
jalali: '1000-01-01',
taiwan: '1000-01-01',
thai: '2000-01-01',
ummalqura: '1400-01-01'
};
// Start on a Sunday - for week ticks
// Discworld and Mayan calendars don't have 7-day weeks but we're going to give them
// 7-day week ticks so start on our Sundays.
// If anyone really cares we can customize the auto tick spacings for these calendars.
var CANONICAL_SUNDAY = {
chinese: '2000-01-02',
coptic: '2000-01-03',
discworld: '2000-01-03',
ethiopian: '2000-01-05',
hebrew: '5000-01-01',
islamic: '1000-01-02',
julian: '2000-01-03',
mayan: '5000-01-01',
nanakshahi: '1000-01-05',
nepali: '2000-01-05',
persian: '1000-01-01',
jalali: '1000-01-01',
taiwan: '1000-01-04',
thai: '2000-01-04',
ummalqura: '1400-01-06'
};
var DFLTRANGE = {
chinese: ['2000-01-01', '2001-01-01'],
coptic: ['1700-01-01', '1701-01-01'],
discworld: ['1800-01-01', '1801-01-01'],
ethiopian: ['2000-01-01', '2001-01-01'],
hebrew: ['5700-01-01', '5701-01-01'],
islamic: ['1400-01-01', '1401-01-01'],
julian: ['2000-01-01', '2001-01-01'],
mayan: ['5200-01-01', '5201-01-01'],
nanakshahi: ['0500-01-01', '0501-01-01'],
nepali: ['2000-01-01', '2001-01-01'],
persian: ['1400-01-01', '1401-01-01'],
jalali: ['1400-01-01', '1401-01-01'],
taiwan: ['0100-01-01', '0101-01-01'],
thai: ['2500-01-01', '2501-01-01'],
ummalqura: ['1400-01-01', '1401-01-01']
};
/*
* convert d3 templates to world-calendars templates, so our users only need
* to know d3's specifiers. Map space padding to no padding, and unknown fields
* to an ugly placeholder
*/
var UNKNOWN = '##';
var d3ToWorldCalendars = {
d: {
0: 'dd',
'-': 'd'
},
// 2-digit or unpadded day of month
e: {
0: 'd',
'-': 'd'
},
// alternate, always unpadded day of month
a: {
0: 'D',
'-': 'D'
},
// short weekday name
A: {
0: 'DD',
'-': 'DD'
},
// full weekday name
j: {
0: 'oo',
'-': 'o'
},
// 3-digit or unpadded day of the year
W: {
0: 'ww',
'-': 'w'
},
// 2-digit or unpadded week of the year (Monday first)
m: {
0: 'mm',
'-': 'm'
},
// 2-digit or unpadded month number
b: {
0: 'M',
'-': 'M'
},
// short month name
B: {
0: 'MM',
'-': 'MM'
},
// full month name
y: {
0: 'yy',
'-': 'yy'
},
// 2-digit year (map unpadded to zero-padded)
Y: {
0: 'yyyy',
'-': 'yyyy'
},
// 4-digit year (map unpadded to zero-padded)
U: UNKNOWN,
// Sunday-first week of the year
w: UNKNOWN,
// day of the week [0(sunday),6]
// combined format, we replace the date part with the world-calendar version
// and the %X stays there for d3 to handle with time parts
c: {
0: 'D M d %X yyyy',
'-': 'D M d %X yyyy'
},
x: {
0: 'mm/dd/yyyy',
'-': 'mm/dd/yyyy'
}
};
function worldCalFmt(fmt, x, calendar) {
var dateJD = Math.floor((x + 0.05) / ONEDAY) + EPOCHJD;
var cDate = getCal(calendar).fromJD(dateJD);
var i = 0;
var modifier, directive, directiveLen, directiveObj, replacementPart;
while ((i = fmt.indexOf('%', i)) !== -1) {
modifier = fmt.charAt(i + 1);
if (modifier === '0' || modifier === '-' || modifier === '_') {
directiveLen = 3;
directive = fmt.charAt(i + 2);
if (modifier === '_') modifier = '-';
} else {
directive = modifier;
modifier = '0';
directiveLen = 2;
}
directiveObj = d3ToWorldCalendars[directive];
if (!directiveObj) {
i += directiveLen;
} else {
// code is recognized as a date part but world-calendars doesn't support it
if (directiveObj === UNKNOWN) replacementPart = UNKNOWN;
// format the cDate according to the translated directive
else replacementPart = cDate.formatDate(directiveObj[modifier]);
fmt = fmt.substr(0, i) + replacementPart + fmt.substr(i + directiveLen);
i += replacementPart.length;
}
}
return fmt;
}
// cache world calendars, so we don't have to reinstantiate
// during each date-time conversion
var allCals = {};
function getCal(calendar) {
var calendarObj = allCals[calendar];
if (calendarObj) return calendarObj;
calendarObj = allCals[calendar] = calendars.instance(calendar);
return calendarObj;
}
function makeAttrs(description) {
return Lib.extendFlat({}, attributes, {
description: description
});
}
function makeTraceAttrsDescription(coord) {
return 'Sets the calendar system to use with `' + coord + '` date data.';
}
var xAttrs = {
xcalendar: makeAttrs(makeTraceAttrsDescription('x'))
};
var xyAttrs = Lib.extendFlat({}, xAttrs, {
ycalendar: makeAttrs(makeTraceAttrsDescription('y'))
});
var xyzAttrs = Lib.extendFlat({}, xyAttrs, {
zcalendar: makeAttrs(makeTraceAttrsDescription('z'))
});
var axisAttrs = makeAttrs(['Sets the calendar system to use for `range` and `tick0`', 'if this is a date axis. This does not set the calendar for', 'interpreting data on this axis, that\'s specified in the trace', 'or via the global `layout.calendar`'].join(' '));
module.exports = {
moduleType: 'component',
name: 'calendars',
schema: {
traces: {
scatter: xyAttrs,
bar: xyAttrs,
box: xyAttrs,
heatmap: xyAttrs,
contour: xyAttrs,
histogram: xyAttrs,
histogram2d: xyAttrs,
histogram2dcontour: xyAttrs,
scatter3d: xyzAttrs,
surface: xyzAttrs,
mesh3d: xyzAttrs,
scattergl: xyAttrs,
ohlc: xAttrs,
candlestick: xAttrs
},
layout: {
calendar: makeAttrs(['Sets the default calendar system to use for interpreting and', 'displaying dates throughout the plot.'].join(' '))
},
subplots: {
xaxis: {
calendar: axisAttrs
},
yaxis: {
calendar: axisAttrs
},
scene: {
xaxis: {
calendar: axisAttrs
},
// TODO: it's actually redundant to include yaxis and zaxis here
// because in the scene attributes these are the same object so merging
// into one merges into them all. However, I left them in for parity with
// cartesian, where yaxis is unused until we Plotschema.get() when we
// use its presence or absence to determine whether to delete attributes
// from yaxis if they only apply to x (rangeselector/rangeslider)
yaxis: {
calendar: axisAttrs
},
zaxis: {
calendar: axisAttrs
}
},
polar: {
radialaxis: {
calendar: axisAttrs
}
}
},
transforms: {
filter: {
valuecalendar: makeAttrs(['WARNING: All transforms are deprecated and may be removed from the API in next major version.', 'Sets the calendar system to use for `value`, if it is a date.'].join(' ')),
targetcalendar: makeAttrs(['WARNING: All transforms are deprecated and may be removed from the API in next major version.', 'Sets the calendar system to use for `target`, if it is an', 'array of dates. If `target` is a string (eg *x*) we use the', 'corresponding trace attribute (eg `xcalendar`) if it exists,', 'even if `targetcalendar` is provided.'].join(' '))
}
}
},
layoutAttributes: attributes,
handleDefaults: handleDefaults,
handleTraceDefaults: handleTraceDefaults,
CANONICAL_SUNDAY: CANONICAL_SUNDAY,
CANONICAL_TICK: CANONICAL_TICK,
DFLTRANGE: DFLTRANGE,
getCal: getCal,
worldCalFmt: worldCalFmt
};
/***/ }),
/***/ 22548:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
// IMPORTANT - default colors should be in hex for compatibility
exports.defaults = ['#1f77b4',
// muted blue
'#ff7f0e',
// safety orange
'#2ca02c',
// cooked asparagus green
'#d62728',
// brick red
'#9467bd',
// muted purple
'#8c564b',
// chestnut brown
'#e377c2',
// raspberry yogurt pink
'#7f7f7f',
// middle gray
'#bcbd22',
// curry yellow-green
'#17becf' // blue-teal
];
exports.defaultLine = '#444';
exports.lightLine = '#eee';
exports.background = '#fff';
exports.borderLine = '#BEC8D9';
// with axis.color and Color.interp we aren't using lightLine
// itself anymore, instead interpolating between axis.color
// and the background color using tinycolor.mix. lightFraction
// gives back exactly lightLine if the other colors are defaults.
exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4);
/***/ }),
/***/ 76308:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var tinycolor = __webpack_require__(49760);
var isNumeric = __webpack_require__(38248);
var isTypedArray = (__webpack_require__(38116).isTypedArray);
var color = module.exports = {};
var colorAttrs = __webpack_require__(22548);
color.defaults = colorAttrs.defaults;
var defaultLine = color.defaultLine = colorAttrs.defaultLine;
color.lightLine = colorAttrs.lightLine;
var background = color.background = colorAttrs.background;
/*
* tinyRGB: turn a tinycolor into an rgb string, but
* unlike the built-in tinycolor.toRgbString this never includes alpha
*/
color.tinyRGB = function (tc) {
var c = tc.toRgb();
return 'rgb(' + Math.round(c.r) + ', ' + Math.round(c.g) + ', ' + Math.round(c.b) + ')';
};
color.rgb = function (cstr) {
return color.tinyRGB(tinycolor(cstr));
};
color.opacity = function (cstr) {
return cstr ? tinycolor(cstr).getAlpha() : 0;
};
color.addOpacity = function (cstr, op) {
var c = tinycolor(cstr).toRgb();
return 'rgba(' + Math.round(c.r) + ', ' + Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')';
};
// combine two colors into one apparent color
// if back has transparency or is missing,
// color.background is assumed behind it
color.combine = function (front, back) {
var fc = tinycolor(front).toRgb();
if (fc.a === 1) return tinycolor(front).toRgbString();
var bc = tinycolor(back || background).toRgb();
var bcflat = bc.a === 1 ? bc : {
r: 255 * (1 - bc.a) + bc.r * bc.a,
g: 255 * (1 - bc.a) + bc.g * bc.a,
b: 255 * (1 - bc.a) + bc.b * bc.a
};
var fcflat = {
r: bcflat.r * (1 - fc.a) + fc.r * fc.a,
g: bcflat.g * (1 - fc.a) + fc.g * fc.a,
b: bcflat.b * (1 - fc.a) + fc.b * fc.a
};
return tinycolor(fcflat).toRgbString();
};
/*
* Linearly interpolate between two colors at a normalized interpolation position (0 to 1).
*
* Ignores alpha channel values.
* The resulting color is computed as: factor * first + (1 - factor) * second.
*/
color.interpolate = function (first, second, factor) {
var fc = tinycolor(first).toRgb();
var sc = tinycolor(second).toRgb();
var ic = {
r: factor * fc.r + (1 - factor) * sc.r,
g: factor * fc.g + (1 - factor) * sc.g,
b: factor * fc.b + (1 - factor) * sc.b
};
return tinycolor(ic).toRgbString();
};
/*
* Create a color that contrasts with cstr.
*
* If cstr is a dark color, we lighten it; if it's light, we darken.
*
* If lightAmount / darkAmount are used, we adjust by these percentages,
* otherwise we go all the way to white or black.
*/
color.contrast = function (cstr, lightAmount, darkAmount) {
var tc = tinycolor(cstr);
if (tc.getAlpha() !== 1) tc = tinycolor(color.combine(cstr, background));
var newColor = tc.isDark() ? lightAmount ? tc.lighten(lightAmount) : background : darkAmount ? tc.darken(darkAmount) : defaultLine;
return newColor.toString();
};
color.stroke = function (s, c) {
var tc = tinycolor(c);
s.style({
stroke: color.tinyRGB(tc),
'stroke-opacity': tc.getAlpha()
});
};
color.fill = function (s, c) {
var tc = tinycolor(c);
s.style({
fill: color.tinyRGB(tc),
'fill-opacity': tc.getAlpha()
});
};
// search container for colors with the deprecated rgb(fractions) format
// and convert them to rgb(0-255 values)
color.clean = function (container) {
if (!container || typeof container !== 'object') return;
var keys = Object.keys(container);
var i, j, key, val;
for (i = 0; i < keys.length; i++) {
key = keys[i];
val = container[key];
if (key.substr(key.length - 5) === 'color') {
// only sanitize keys that end in "color" or "colorscale"
if (Array.isArray(val)) {
for (j = 0; j < val.length; j++) val[j] = cleanOne(val[j]);
} else container[key] = cleanOne(val);
} else if (key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) {
// colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]]
for (j = 0; j < val.length; j++) {
if (Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]);
}
} else if (Array.isArray(val)) {
// recurse into arrays of objects, and plain objects
var el0 = val[0];
if (!Array.isArray(el0) && el0 && typeof el0 === 'object') {
for (j = 0; j < val.length; j++) color.clean(val[j]);
}
} else if (val && typeof val === 'object' && !isTypedArray(val)) color.clean(val);
}
};
function cleanOne(val) {
if (isNumeric(val) || typeof val !== 'string') return val;
var valTrim = val.trim();
if (valTrim.substr(0, 3) !== 'rgb') return val;
var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/);
if (!match) return val;
var parts = match[1].trim().split(/\s*[\s,]\s*/);
var rgba = valTrim.charAt(3) === 'a' && parts.length === 4;
if (!rgba && parts.length !== 3) return val;
for (var i = 0; i < parts.length; i++) {
if (!parts[i].length) return val;
parts[i] = Number(parts[i]);
if (!(parts[i] >= 0)) {
// all parts must be non-negative numbers
return val;
}
if (i === 3) {
// alpha>1 gets clipped to 1
if (parts[i] > 1) parts[i] = 1;
} else if (parts[i] >= 1) {
// r, g, b must be < 1 (ie 1 itself is not allowed)
return val;
}
}
var rgbStr = Math.round(parts[0] * 255) + ', ' + Math.round(parts[1] * 255) + ', ' + Math.round(parts[2] * 255);
if (rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')';
return 'rgb(' + rgbStr + ')';
}
/***/ }),
/***/ 42996:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var axesAttrs = __webpack_require__(94724);
var fontAttrs = __webpack_require__(25376);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
module.exports = overrideAll({
orientation: {
valType: 'enumerated',
values: ['h', 'v'],
dflt: 'v'
},
thicknessmode: {
valType: 'enumerated',
values: ['fraction', 'pixels'],
dflt: 'pixels'
},
thickness: {
valType: 'number',
min: 0,
dflt: 30
},
lenmode: {
valType: 'enumerated',
values: ['fraction', 'pixels'],
dflt: 'fraction'
},
len: {
valType: 'number',
min: 0,
dflt: 1
},
x: {
valType: 'number'
},
xref: {
valType: 'enumerated',
dflt: 'paper',
values: ['container', 'paper'],
editType: 'layoutstyle'
},
xanchor: {
valType: 'enumerated',
values: ['left', 'center', 'right']
},
xpad: {
valType: 'number',
min: 0,
dflt: 10
},
y: {
valType: 'number'
},
yref: {
valType: 'enumerated',
dflt: 'paper',
values: ['container', 'paper'],
editType: 'layoutstyle'
},
yanchor: {
valType: 'enumerated',
values: ['top', 'middle', 'bottom']
},
ypad: {
valType: 'number',
min: 0,
dflt: 10
},
// a possible line around the bar itself
outlinecolor: axesAttrs.linecolor,
outlinewidth: axesAttrs.linewidth,
// Should outlinewidth have {dflt: 0} ?
// another possible line outside the padding and tick labels
bordercolor: axesAttrs.linecolor,
borderwidth: {
valType: 'number',
min: 0,
dflt: 0
},
bgcolor: {
valType: 'color',
dflt: 'rgba(0,0,0,0)'
},
// tick and title properties named and function exactly as in axes
tickmode: axesAttrs.minor.tickmode,
nticks: axesAttrs.nticks,
tick0: axesAttrs.tick0,
dtick: axesAttrs.dtick,
tickvals: axesAttrs.tickvals,
ticktext: axesAttrs.ticktext,
ticks: extendFlat({}, axesAttrs.ticks, {
dflt: ''
}),
ticklabeloverflow: extendFlat({}, axesAttrs.ticklabeloverflow, {}),
// ticklabelposition: not used directly, as values depend on orientation
// left/right options are for x axes, and top/bottom options are for y axes
ticklabelposition: {
valType: 'enumerated',
values: ['outside', 'inside', 'outside top', 'inside top', 'outside left', 'inside left', 'outside right', 'inside right', 'outside bottom', 'inside bottom'],
dflt: 'outside'
},
ticklen: axesAttrs.ticklen,
tickwidth: axesAttrs.tickwidth,
tickcolor: axesAttrs.tickcolor,
ticklabelstep: axesAttrs.ticklabelstep,
showticklabels: axesAttrs.showticklabels,
labelalias: axesAttrs.labelalias,
tickfont: fontAttrs({}),
tickangle: axesAttrs.tickangle,
tickformat: axesAttrs.tickformat,
tickformatstops: axesAttrs.tickformatstops,
tickprefix: axesAttrs.tickprefix,
showtickprefix: axesAttrs.showtickprefix,
ticksuffix: axesAttrs.ticksuffix,
showticksuffix: axesAttrs.showticksuffix,
separatethousands: axesAttrs.separatethousands,
exponentformat: axesAttrs.exponentformat,
minexponent: axesAttrs.minexponent,
showexponent: axesAttrs.showexponent,
title: {
text: {
valType: 'string'
},
font: fontAttrs({}),
side: {
valType: 'enumerated',
values: ['right', 'top', 'bottom']
}
},
_deprecated: {
title: {
valType: 'string'
},
titlefont: fontAttrs({}),
titleside: {
valType: 'enumerated',
values: ['right', 'top', 'bottom'],
dflt: 'top'
}
}
}, 'colorbars', 'from-root');
/***/ }),
/***/ 63964:
/***/ (function(module) {
"use strict";
module.exports = {
cn: {
colorbar: 'colorbar',
cbbg: 'cbbg',
cbfill: 'cbfill',
cbfills: 'cbfills',
cbline: 'cbline',
cblines: 'cblines',
cbaxis: 'cbaxis',
cbtitleunshift: 'cbtitleunshift',
cbtitle: 'cbtitle',
cboutline: 'cboutline',
crisp: 'crisp',
jsPlaceholder: 'js-placeholder'
}
};
/***/ }),
/***/ 64013:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
var handleTickValueDefaults = __webpack_require__(26332);
var handleTickMarkDefaults = __webpack_require__(25404);
var handleTickLabelDefaults = __webpack_require__(95936);
var handlePrefixSuffixDefaults = __webpack_require__(42568);
var attributes = __webpack_require__(42996);
module.exports = function colorbarDefaults(containerIn, containerOut, layout) {
var colorbarOut = Template.newContainer(containerOut, 'colorbar');
var colorbarIn = containerIn.colorbar || {};
function coerce(attr, dflt) {
return Lib.coerce(colorbarIn, colorbarOut, attributes, attr, dflt);
}
var margin = layout.margin || {
t: 0,
b: 0,
l: 0,
r: 0
};
var w = layout.width - margin.l - margin.r;
var h = layout.height - margin.t - margin.b;
var orientation = coerce('orientation');
var isVertical = orientation === 'v';
var thicknessmode = coerce('thicknessmode');
coerce('thickness', thicknessmode === 'fraction' ? 30 / (isVertical ? w : h) : 30);
var lenmode = coerce('lenmode');
coerce('len', lenmode === 'fraction' ? 1 : isVertical ? h : w);
var yref = coerce('yref');
var xref = coerce('xref');
var isPaperY = yref === 'paper';
var isPaperX = xref === 'paper';
var defaultX, defaultY, defaultYAnchor;
var defaultXAnchor = 'left';
if (isVertical) {
defaultYAnchor = 'middle';
defaultXAnchor = isPaperX ? 'left' : 'right';
defaultX = isPaperX ? 1.02 : 1;
defaultY = 0.5;
} else {
defaultYAnchor = isPaperY ? 'bottom' : 'top';
defaultXAnchor = 'center';
defaultX = 0.5;
defaultY = isPaperY ? 1.02 : 1;
}
Lib.coerce(colorbarIn, colorbarOut, {
x: {
valType: 'number',
min: isPaperX ? -2 : 0,
max: isPaperX ? 3 : 1,
dflt: defaultX
}
}, 'x');
Lib.coerce(colorbarIn, colorbarOut, {
y: {
valType: 'number',
min: isPaperY ? -2 : 0,
max: isPaperY ? 3 : 1,
dflt: defaultY
}
}, 'y');
coerce('xanchor', defaultXAnchor);
coerce('xpad');
coerce('yanchor', defaultYAnchor);
coerce('ypad');
Lib.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']);
coerce('outlinecolor');
coerce('outlinewidth');
coerce('bordercolor');
coerce('borderwidth');
coerce('bgcolor');
var ticklabelposition = Lib.coerce(colorbarIn, colorbarOut, {
ticklabelposition: {
valType: 'enumerated',
dflt: 'outside',
values: isVertical ? ['outside', 'inside', 'outside top', 'inside top', 'outside bottom', 'inside bottom'] : ['outside', 'inside', 'outside left', 'inside left', 'outside right', 'inside right']
}
}, 'ticklabelposition');
coerce('ticklabeloverflow', ticklabelposition.indexOf('inside') !== -1 ? 'hide past domain' : 'hide past div');
handleTickValueDefaults(colorbarIn, colorbarOut, coerce, 'linear');
var font = layout.font;
var opts = {
noAutotickangles: true,
noTicklabelshift: true,
noTicklabelstandoff: true,
outerTicks: false,
font: font
};
if (ticklabelposition.indexOf('inside') !== -1) {
opts.bgColor = 'black'; // could we instead use the average of colors in the scale?
}
handlePrefixSuffixDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);
handleTickLabelDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);
handleTickMarkDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);
coerce('title.text', layout._dfltTitle.colorbar);
var tickFont = colorbarOut.showticklabels ? colorbarOut.tickfont : font;
var dfltTitleFont = Lib.extendFlat({}, font, {
family: tickFont.family,
size: Lib.bigFont(tickFont.size)
});
Lib.coerceFont(coerce, 'title.font', dfltTitleFont);
coerce('title.side', isVertical ? 'top' : 'right');
};
/***/ }),
/***/ 37848:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var tinycolor = __webpack_require__(49760);
var Plots = __webpack_require__(7316);
var Registry = __webpack_require__(24040);
var Axes = __webpack_require__(54460);
var dragElement = __webpack_require__(86476);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var extendFlat = (__webpack_require__(92880).extendFlat);
var setCursor = __webpack_require__(93972);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var Titles = __webpack_require__(81668);
var svgTextUtils = __webpack_require__(72736);
var flipScale = (__webpack_require__(94288).flipScale);
var handleAxisDefaults = __webpack_require__(28336);
var handleAxisPositionDefaults = __webpack_require__(37668);
var axisLayoutAttrs = __webpack_require__(94724);
var alignmentConstants = __webpack_require__(84284);
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;
var cn = (__webpack_require__(63964).cn);
function draw(gd) {
var fullLayout = gd._fullLayout;
var colorBars = fullLayout._infolayer.selectAll('g.' + cn.colorbar).data(makeColorBarData(gd), function (opts) {
return opts._id;
});
colorBars.enter().append('g').attr('class', function (opts) {
return opts._id;
}).classed(cn.colorbar, true);
colorBars.each(function (opts) {
var g = d3.select(this);
Lib.ensureSingle(g, 'rect', cn.cbbg);
Lib.ensureSingle(g, 'g', cn.cbfills);
Lib.ensureSingle(g, 'g', cn.cblines);
Lib.ensureSingle(g, 'g', cn.cbaxis, function (s) {
s.classed(cn.crisp, true);
});
Lib.ensureSingle(g, 'g', cn.cbtitleunshift, function (s) {
s.append('g').classed(cn.cbtitle, true);
});
Lib.ensureSingle(g, 'rect', cn.cboutline);
var done = drawColorBar(g, opts, gd);
if (done && done.then) (gd._promises || []).push(done);
if (gd._context.edits.colorbarPosition) {
makeEditable(g, opts, gd);
}
});
colorBars.exit().each(function (opts) {
Plots.autoMargin(gd, opts._id);
}).remove();
colorBars.order();
}
function makeColorBarData(gd) {
var fullLayout = gd._fullLayout;
var calcdata = gd.calcdata;
var out = [];
// single out item
var opts;
// colorbar attr parent container
var cont;
// trace attr container
var trace;
// colorbar options
var cbOpt;
function initOpts(opts) {
return extendFlat(opts, {
// fillcolor can be a d3 scale, domain is z values, range is colors
// or leave it out for no fill,
// or set to a string constant for single-color fill
_fillcolor: null,
// line.color has the same options as fillcolor
_line: {
color: null,
width: null,
dash: null
},
// levels of lines to draw.
// note that this DOES NOT determine the extent of the bar
// that's given by the domain of fillcolor
// (or line.color if no fillcolor domain)
_levels: {
start: null,
end: null,
size: null
},
// separate fill levels (for example, heatmap coloring of a
// contour map) if this is omitted, fillcolors will be
// evaluated halfway between levels
_filllevels: null,
// for continuous colorscales: fill with a gradient instead of explicit levels
// value should be the colorscale [[0, c0], [v1, c1], ..., [1, cEnd]]
_fillgradient: null,
// when using a gradient, we need the data range specified separately
_zrange: null
});
}
function calcOpts() {
if (typeof cbOpt.calc === 'function') {
cbOpt.calc(gd, trace, opts);
} else {
opts._fillgradient = cont.reversescale ? flipScale(cont.colorscale) : cont.colorscale;
opts._zrange = [cont[cbOpt.min], cont[cbOpt.max]];
}
}
for (var i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
trace = cd[0].trace;
if (!trace._module) continue;
var moduleOpts = trace._module.colorbar;
if (trace.visible === true && moduleOpts) {
var allowsMultiplotCbs = Array.isArray(moduleOpts);
var cbOpts = allowsMultiplotCbs ? moduleOpts : [moduleOpts];
for (var j = 0; j < cbOpts.length; j++) {
cbOpt = cbOpts[j];
var contName = cbOpt.container;
cont = contName ? trace[contName] : trace;
if (cont && cont.showscale) {
opts = initOpts(cont.colorbar);
opts._id = 'cb' + trace.uid + (allowsMultiplotCbs && contName ? '-' + contName : '');
opts._traceIndex = trace.index;
opts._propPrefix = (contName ? contName + '.' : '') + 'colorbar.';
opts._meta = trace._meta;
calcOpts();
out.push(opts);
}
}
}
}
for (var k in fullLayout._colorAxes) {
cont = fullLayout[k];
if (cont.showscale) {
var colorAxOpts = fullLayout._colorAxes[k];
opts = initOpts(cont.colorbar);
opts._id = 'cb' + k;
opts._propPrefix = k + '.colorbar.';
opts._meta = fullLayout._meta;
cbOpt = {
min: 'cmin',
max: 'cmax'
};
if (colorAxOpts[0] !== 'heatmap') {
trace = colorAxOpts[1];
cbOpt.calc = trace._module.colorbar.calc;
}
calcOpts();
out.push(opts);
}
}
return out;
}
function drawColorBar(g, opts, gd) {
var isVertical = opts.orientation === 'v';
var len = opts.len;
var lenmode = opts.lenmode;
var thickness = opts.thickness;
var thicknessmode = opts.thicknessmode;
var outlinewidth = opts.outlinewidth;
var borderwidth = opts.borderwidth;
var bgcolor = opts.bgcolor;
var xanchor = opts.xanchor;
var yanchor = opts.yanchor;
var xpad = opts.xpad;
var ypad = opts.ypad;
var optsX = opts.x;
var optsY = isVertical ? opts.y : 1 - opts.y;
var isPaperY = opts.yref === 'paper';
var isPaperX = opts.xref === 'paper';
var fullLayout = gd._fullLayout;
var gs = fullLayout._size;
var fillColor = opts._fillcolor;
var line = opts._line;
var title = opts.title;
var titleSide = title.side;
var zrange = opts._zrange || d3.extent((typeof fillColor === 'function' ? fillColor : line.color).domain());
var lineColormap = typeof line.color === 'function' ? line.color : function () {
return line.color;
};
var fillColormap = typeof fillColor === 'function' ? fillColor : function () {
return fillColor;
};
var levelsIn = opts._levels;
var levelsOut = calcLevels(gd, opts, zrange);
var fillLevels = levelsOut.fill;
var lineLevels = levelsOut.line;
// we calculate pixel sizes based on the specified graph size,
// not the actual (in case something pushed the margins around)
// which is a little odd but avoids an odd iterative effect
// when the colorbar itself is pushing the margins.
// but then the fractional size is calculated based on the
// actual graph size, so that the axes will size correctly.
var thickPx = Math.round(thickness * (thicknessmode === 'fraction' ? isVertical ? gs.w : gs.h : 1));
var thickFrac = thickPx / (isVertical ? gs.w : gs.h);
var lenPx = Math.round(len * (lenmode === 'fraction' ? isVertical ? gs.h : gs.w : 1));
var lenFrac = lenPx / (isVertical ? gs.h : gs.w);
var posW = isPaperX ? gs.w : gd._fullLayout.width;
var posH = isPaperY ? gs.h : gd._fullLayout.height;
// x positioning: do it initially just for left anchor,
// then fix at the end (since we don't know the width yet)
var uPx = Math.round(isVertical ? optsX * posW + xpad : optsY * posH + ypad);
var xRatio = {
center: 0.5,
right: 1
}[xanchor] || 0;
var yRatio = {
top: 1,
middle: 0.5
}[yanchor] || 0;
// for dragging... this is getting a little muddled...
var uFrac = isVertical ? optsX - xRatio * thickFrac : optsY - yRatio * thickFrac;
// y/x positioning (for v/h) we can do correctly from the start
var vFrac = isVertical ? optsY - yRatio * lenFrac : optsX - xRatio * lenFrac;
var vPx = Math.round(isVertical ? posH * (1 - vFrac) : posW * vFrac);
// stash a few things for makeEditable
opts._lenFrac = lenFrac;
opts._thickFrac = thickFrac;
opts._uFrac = uFrac;
opts._vFrac = vFrac;
// stash mocked axis for contour label formatting
var ax = opts._axis = mockColorBarAxis(gd, opts, zrange);
// position can't go in through supplyDefaults
// because that restricts it to [0,1]
ax.position = thickFrac + (isVertical ? optsX + xpad / gs.w : optsY + ypad / gs.h);
var topOrBottom = ['top', 'bottom'].indexOf(titleSide) !== -1;
if (isVertical && topOrBottom) {
ax.title.side = titleSide;
ax.titlex = optsX + xpad / gs.w;
ax.titley = vFrac + (title.side === 'top' ? lenFrac - ypad / gs.h : ypad / gs.h);
}
if (!isVertical && !topOrBottom) {
ax.title.side = titleSide;
ax.titley = optsY + ypad / gs.h;
ax.titlex = vFrac + xpad / gs.w; // right side
}
if (line.color && opts.tickmode === 'auto') {
ax.tickmode = 'linear';
ax.tick0 = levelsIn.start;
var dtick = levelsIn.size;
// expand if too many contours, so we don't get too many ticks
var autoNtick = Lib.constrain(lenPx / 50, 4, 15) + 1;
var dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick);
if (dtFactor > 1) {
var dtexp = Math.pow(10, Math.floor(Math.log(dtFactor) / Math.LN10));
dtick *= dtexp * Lib.roundUp(dtFactor / dtexp, [2, 5, 10]);
// if the contours are at round multiples, reset tick0
// so they're still at round multiples. Otherwise,
// keep the first label on the first contour level
if ((Math.abs(levelsIn.start) / levelsIn.size + 1e-6) % 1 < 2e-6) {
ax.tick0 = 0;
}
}
ax.dtick = dtick;
}
// set domain after init, because we may want to
// allow it outside [0,1]
ax.domain = isVertical ? [vFrac + ypad / gs.h, vFrac + lenFrac - ypad / gs.h] : [vFrac + xpad / gs.w, vFrac + lenFrac - xpad / gs.w];
ax.setScale();
g.attr('transform', strTranslate(Math.round(gs.l), Math.round(gs.t)));
var titleCont = g.select('.' + cn.cbtitleunshift).attr('transform', strTranslate(-Math.round(gs.l), -Math.round(gs.t)));
var ticklabelposition = ax.ticklabelposition;
var titleFontSize = ax.title.font.size;
var axLayer = g.select('.' + cn.cbaxis);
var titleEl;
var titleHeight = 0;
var titleWidth = 0;
function drawTitle(titleClass, titleOpts) {
var dfltTitleOpts = {
propContainer: ax,
propName: opts._propPrefix + 'title',
traceIndex: opts._traceIndex,
_meta: opts._meta,
placeholder: fullLayout._dfltTitle.colorbar,
containerGroup: g.select('.' + cn.cbtitle)
};
// this class-to-rotate thing with convertToTspans is
// getting hackier and hackier... delete groups with the
// wrong class (in case earlier the colorbar was drawn on
// a different side, I think?)
var otherClass = titleClass.charAt(0) === 'h' ? titleClass.substr(1) : 'h' + titleClass;
g.selectAll('.' + otherClass + ',.' + otherClass + '-math-group').remove();
Titles.draw(gd, titleClass, extendFlat(dfltTitleOpts, titleOpts || {}));
}
function drawDummyTitle() {
// draw the title so we know how much room it needs
// when we squish the axis.
// On vertical colorbars this only applies to top or bottom titles, not right side.
// On horizontal colorbars this only applies to right, etc.
if (isVertical && topOrBottom || !isVertical && !topOrBottom) {
var x, y;
if (titleSide === 'top') {
x = xpad + gs.l + posW * optsX;
y = ypad + gs.t + posH * (1 - vFrac - lenFrac) + 3 + titleFontSize * 0.75;
}
if (titleSide === 'bottom') {
x = xpad + gs.l + posW * optsX;
y = ypad + gs.t + posH * (1 - vFrac) - 3 - titleFontSize * 0.25;
}
if (titleSide === 'right') {
y = ypad + gs.t + posH * optsY + 3 + titleFontSize * 0.75;
x = xpad + gs.l + posW * vFrac;
}
drawTitle(ax._id + 'title', {
attributes: {
x: x,
y: y,
'text-anchor': isVertical ? 'start' : 'middle'
}
});
}
}
function drawCbTitle() {
if (isVertical && !topOrBottom || !isVertical && topOrBottom) {
var pos = ax.position || 0;
var mid = ax._offset + ax._length / 2;
var x, y;
if (titleSide === 'right') {
y = mid;
x = gs.l + posW * pos + 10 + titleFontSize * (ax.showticklabels ? 1 : 0.5);
} else {
x = mid;
if (titleSide === 'bottom') {
y = gs.t + posH * pos + 10 + (ticklabelposition.indexOf('inside') === -1 ? ax.tickfont.size : 0) + (ax.ticks !== 'intside' ? opts.ticklen || 0 : 0);
}
if (titleSide === 'top') {
var nlines = title.text.split(' ').length;
y = gs.t + posH * pos + 10 - thickPx - LINE_SPACING * titleFontSize * nlines;
}
}
drawTitle((isVertical ?
// the 'h' + is a hack to get around the fact that
// convertToTspans rotates any 'y...' class by 90 degrees.
// TODO: find a better way to control this.
'h' : 'v') + ax._id + 'title', {
avoid: {
selection: d3.select(gd).selectAll('g.' + ax._id + 'tick'),
side: titleSide,
offsetTop: isVertical ? 0 : gs.t,
offsetLeft: isVertical ? gs.l : 0,
maxShift: isVertical ? fullLayout.width : fullLayout.height
},
attributes: {
x: x,
y: y,
'text-anchor': 'middle'
},
transform: {
rotate: isVertical ? -90 : 0,
offset: 0
}
});
}
}
function drawAxis() {
if (!isVertical && !topOrBottom || isVertical && topOrBottom) {
// squish the axis top to make room for the title
var titleGroup = g.select('.' + cn.cbtitle);
var titleText = titleGroup.select('text');
var titleTrans = [-outlinewidth / 2, outlinewidth / 2];
var mathJaxNode = titleGroup.select('.h' + ax._id + 'title-math-group').node();
var lineSize = 15.6;
if (titleText.node()) {
lineSize = parseInt(titleText.node().style.fontSize, 10) * LINE_SPACING;
}
var bb;
if (mathJaxNode) {
bb = Drawing.bBox(mathJaxNode);
titleWidth = bb.width;
titleHeight = bb.height;
if (titleHeight > lineSize) {
// not entirely sure how mathjax is doing
// vertical alignment, but this seems to work.
titleTrans[1] -= (titleHeight - lineSize) / 2;
}
} else if (titleText.node() && !titleText.classed(cn.jsPlaceholder)) {
bb = Drawing.bBox(titleText.node());
titleWidth = bb.width;
titleHeight = bb.height;
}
if (isVertical) {
if (titleHeight) {
// buffer btwn colorbar and title
// TODO: configurable
titleHeight += 5;
if (titleSide === 'top') {
ax.domain[1] -= titleHeight / gs.h;
titleTrans[1] *= -1;
} else {
ax.domain[0] += titleHeight / gs.h;
var nlines = svgTextUtils.lineCount(titleText);
titleTrans[1] += (1 - nlines) * lineSize;
}
titleGroup.attr('transform', strTranslate(titleTrans[0], titleTrans[1]));
ax.setScale();
}
} else {
// horizontal colorbars
if (titleWidth) {
if (titleSide === 'right') {
ax.domain[0] += (titleWidth + titleFontSize / 2) / gs.w;
}
titleGroup.attr('transform', strTranslate(titleTrans[0], titleTrans[1]));
ax.setScale();
}
}
}
g.selectAll('.' + cn.cbfills + ',.' + cn.cblines).attr('transform', isVertical ? strTranslate(0, Math.round(gs.h * (1 - ax.domain[1]))) : strTranslate(Math.round(gs.w * ax.domain[0]), 0));
axLayer.attr('transform', isVertical ? strTranslate(0, Math.round(-gs.t)) : strTranslate(Math.round(-gs.l), 0));
var fills = g.select('.' + cn.cbfills).selectAll('rect.' + cn.cbfill).attr('style', '').data(fillLevels);
fills.enter().append('rect').classed(cn.cbfill, true).attr('style', '');
fills.exit().remove();
var zBounds = zrange.map(ax.c2p).map(Math.round).sort(function (a, b) {
return a - b;
});
fills.each(function (d, i) {
var z = [i === 0 ? zrange[0] : (fillLevels[i] + fillLevels[i - 1]) / 2, i === fillLevels.length - 1 ? zrange[1] : (fillLevels[i] + fillLevels[i + 1]) / 2].map(ax.c2p).map(Math.round);
// offset the side adjoining the next rectangle so they
// overlap, to prevent antialiasing gaps
if (isVertical) {
z[1] = Lib.constrain(z[1] + (z[1] > z[0]) ? 1 : -1, zBounds[0], zBounds[1]);
} /* else {
// TODO: horizontal case
} */
// Colorbar cannot currently support opacities so we
// use an opaque fill even when alpha channels present
var fillEl = d3.select(this).attr(isVertical ? 'x' : 'y', uPx).attr(isVertical ? 'y' : 'x', d3.min(z)).attr(isVertical ? 'width' : 'height', Math.max(thickPx, 2)).attr(isVertical ? 'height' : 'width', Math.max(d3.max(z) - d3.min(z), 2));
if (opts._fillgradient) {
Drawing.gradient(fillEl, gd, opts._id, isVertical ? 'vertical' : 'horizontalreversed', opts._fillgradient, 'fill');
} else {
// tinycolor can't handle exponents and
// at this scale, removing it makes no difference.
var colorString = fillColormap(d).replace('e-', '');
fillEl.attr('fill', tinycolor(colorString).toHexString());
}
});
var lines = g.select('.' + cn.cblines).selectAll('path.' + cn.cbline).data(line.color && line.width ? lineLevels : []);
lines.enter().append('path').classed(cn.cbline, true);
lines.exit().remove();
lines.each(function (d) {
var a = uPx;
var b = Math.round(ax.c2p(d)) + line.width / 2 % 1;
d3.select(this).attr('d', 'M' + (isVertical ? a + ',' + b : b + ',' + a) + (isVertical ? 'h' : 'v') + thickPx).call(Drawing.lineGroupStyle, line.width, lineColormap(d), line.dash);
});
// force full redraw of labels and ticks
axLayer.selectAll('g.' + ax._id + 'tick,path').remove();
var shift = uPx + thickPx + (outlinewidth || 0) / 2 - (opts.ticks === 'outside' ? 1 : 0);
var vals = Axes.calcTicks(ax);
var tickSign = Axes.getTickSigns(ax)[2];
Axes.drawTicks(gd, ax, {
vals: ax.ticks === 'inside' ? Axes.clipEnds(ax, vals) : vals,
layer: axLayer,
path: Axes.makeTickPath(ax, shift, tickSign),
transFn: Axes.makeTransTickFn(ax)
});
return Axes.drawLabels(gd, ax, {
vals: vals,
layer: axLayer,
transFn: Axes.makeTransTickLabelFn(ax),
labelFns: Axes.makeLabelFns(ax, shift)
});
}
// wait for the axis & title to finish rendering before
// continuing positioning
// TODO: why are we redrawing multiple times now with this?
// I guess autoMargin doesn't like being post-promise?
function positionCB() {
var bb;
var innerThickness = thickPx + outlinewidth / 2;
if (ticklabelposition.indexOf('inside') === -1) {
bb = Drawing.bBox(axLayer.node());
innerThickness += isVertical ? bb.width : bb.height;
}
titleEl = titleCont.select('text');
var titleWidth = 0;
var topSideVertical = isVertical && titleSide === 'top';
var rightSideHorizontal = !isVertical && titleSide === 'right';
var moveY = 0;
if (titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) {
var _titleHeight;
var mathJaxNode = titleCont.select('.h' + ax._id + 'title-math-group').node();
if (mathJaxNode && (isVertical && topOrBottom || !isVertical && !topOrBottom)) {
bb = Drawing.bBox(mathJaxNode);
titleWidth = bb.width;
_titleHeight = bb.height;
} else {
// note: the formula below works for all title sides,
// (except for top/bottom mathjax, above)
// but the weird gs.l is because the titleunshift
// transform gets removed by Drawing.bBox
bb = Drawing.bBox(titleCont.node());
titleWidth = bb.right - gs.l - (isVertical ? uPx : vPx);
_titleHeight = bb.bottom - gs.t - (isVertical ? vPx : uPx);
if (!isVertical && titleSide === 'top') {
innerThickness += bb.height;
moveY = bb.height;
}
}
if (rightSideHorizontal) {
titleEl.attr('transform', strTranslate(titleWidth / 2 + titleFontSize / 2, 0));
titleWidth *= 2;
}
innerThickness = Math.max(innerThickness, isVertical ? titleWidth : _titleHeight);
}
var outerThickness = (isVertical ? xpad : ypad) * 2 + innerThickness + borderwidth + outlinewidth / 2;
var hColorbarMoveTitle = 0;
if (!isVertical && title.text && yanchor === 'bottom' && optsY <= 0) {
hColorbarMoveTitle = outerThickness / 2;
outerThickness += hColorbarMoveTitle;
moveY += hColorbarMoveTitle;
}
fullLayout._hColorbarMoveTitle = hColorbarMoveTitle;
fullLayout._hColorbarMoveCBTitle = moveY;
var extraW = borderwidth + outlinewidth;
// TODO - are these the correct positions?
var lx = (isVertical ? uPx : vPx) - extraW / 2 - (isVertical ? xpad : 0);
var ly = (isVertical ? vPx : uPx) - (isVertical ? lenPx : ypad + moveY - hColorbarMoveTitle);
g.select('.' + cn.cbbg).attr('x', lx).attr('y', ly).attr(isVertical ? 'width' : 'height', Math.max(outerThickness - hColorbarMoveTitle, 2)).attr(isVertical ? 'height' : 'width', Math.max(lenPx + extraW, 2)).call(Color.fill, bgcolor).call(Color.stroke, opts.bordercolor).style('stroke-width', borderwidth);
var moveX = rightSideHorizontal ? Math.max(titleWidth - 10, 0) : 0;
g.selectAll('.' + cn.cboutline).attr('x', (isVertical ? uPx : vPx + xpad) + moveX).attr('y', (isVertical ? vPx + ypad - lenPx : uPx) + (topSideVertical ? titleHeight : 0)).attr(isVertical ? 'width' : 'height', Math.max(thickPx, 2)).attr(isVertical ? 'height' : 'width', Math.max(lenPx - (isVertical ? 2 * ypad + titleHeight : 2 * xpad + moveX), 2)).call(Color.stroke, opts.outlinecolor).style({
fill: 'none',
'stroke-width': outlinewidth
});
var xShift = isVertical ? xRatio * outerThickness : 0;
var yShift = isVertical ? 0 : (1 - yRatio) * outerThickness - moveY;
xShift = isPaperX ? gs.l - xShift : -xShift;
yShift = isPaperY ? gs.t - yShift : -yShift;
g.attr('transform', strTranslate(xShift, yShift));
if (!isVertical && (borderwidth || tinycolor(bgcolor).getAlpha() && !tinycolor.equals(fullLayout.paper_bgcolor, bgcolor))) {
// for horizontal colorbars when there is a border line or having different background color
// hide/adjust x positioning for the first/last tick labels if they go outside the border
var tickLabels = axLayer.selectAll('text');
var numTicks = tickLabels[0].length;
var border = g.select('.' + cn.cbbg).node();
var oBb = Drawing.bBox(border);
var oTr = Drawing.getTranslate(g);
var TEXTPAD = 2;
tickLabels.each(function (d, i) {
var first = 0;
var last = numTicks - 1;
if (i === first || i === last) {
var iBb = Drawing.bBox(this);
var iTr = Drawing.getTranslate(this);
var deltaX;
if (i === last) {
var iRight = iBb.right + iTr.x;
var oRight = oBb.right + oTr.x + vPx - borderwidth - TEXTPAD + optsX;
deltaX = oRight - iRight;
if (deltaX > 0) deltaX = 0;
} else if (i === first) {
var iLeft = iBb.left + iTr.x;
var oLeft = oBb.left + oTr.x + vPx + borderwidth + TEXTPAD;
deltaX = oLeft - iLeft;
if (deltaX < 0) deltaX = 0;
}
if (deltaX) {
if (numTicks < 3) {
// adjust position
this.setAttribute('transform', 'translate(' + deltaX + ',0) ' + this.getAttribute('transform'));
} else {
// hide
this.setAttribute('visibility', 'hidden');
}
}
}
});
}
// auto margin adjustment
var marginOpts = {};
var lFrac = FROM_TL[xanchor];
var rFrac = FROM_BR[xanchor];
var tFrac = FROM_TL[yanchor];
var bFrac = FROM_BR[yanchor];
var extraThickness = outerThickness - thickPx;
if (isVertical) {
if (lenmode === 'pixels') {
marginOpts.y = optsY;
marginOpts.t = lenPx * tFrac;
marginOpts.b = lenPx * bFrac;
} else {
marginOpts.t = marginOpts.b = 0;
marginOpts.yt = optsY + len * tFrac;
marginOpts.yb = optsY - len * bFrac;
}
if (thicknessmode === 'pixels') {
marginOpts.x = optsX;
marginOpts.l = outerThickness * lFrac;
marginOpts.r = outerThickness * rFrac;
} else {
marginOpts.l = extraThickness * lFrac;
marginOpts.r = extraThickness * rFrac;
marginOpts.xl = optsX - thickness * lFrac;
marginOpts.xr = optsX + thickness * rFrac;
}
} else {
// horizontal colorbars
if (lenmode === 'pixels') {
marginOpts.x = optsX;
marginOpts.l = lenPx * lFrac;
marginOpts.r = lenPx * rFrac;
} else {
marginOpts.l = marginOpts.r = 0;
marginOpts.xl = optsX + len * lFrac;
marginOpts.xr = optsX - len * rFrac;
}
if (thicknessmode === 'pixels') {
marginOpts.y = 1 - optsY;
marginOpts.t = outerThickness * tFrac;
marginOpts.b = outerThickness * bFrac;
} else {
marginOpts.t = extraThickness * tFrac;
marginOpts.b = extraThickness * bFrac;
marginOpts.yt = optsY - thickness * tFrac;
marginOpts.yb = optsY + thickness * bFrac;
}
}
var sideY = opts.y < 0.5 ? 'b' : 't';
var sideX = opts.x < 0.5 ? 'l' : 'r';
gd._fullLayout._reservedMargin[opts._id] = {};
var possibleReservedMargins = {
r: fullLayout.width - lx - xShift,
l: lx + marginOpts.r,
b: fullLayout.height - ly - yShift,
t: ly + marginOpts.b
};
if (isPaperX && isPaperY) {
Plots.autoMargin(gd, opts._id, marginOpts);
} else if (isPaperX) {
gd._fullLayout._reservedMargin[opts._id][sideY] = possibleReservedMargins[sideY];
} else if (isPaperY) {
gd._fullLayout._reservedMargin[opts._id][sideX] = possibleReservedMargins[sideX];
} else {
if (isVertical) {
gd._fullLayout._reservedMargin[opts._id][sideX] = possibleReservedMargins[sideX];
} else {
gd._fullLayout._reservedMargin[opts._id][sideY] = possibleReservedMargins[sideY];
}
}
}
return Lib.syncOrAsync([Plots.previousPromises, drawDummyTitle, drawAxis, drawCbTitle, Plots.previousPromises, positionCB], gd);
}
function makeEditable(g, opts, gd) {
var isVertical = opts.orientation === 'v';
var fullLayout = gd._fullLayout;
var gs = fullLayout._size;
var t0, xf, yf;
dragElement.init({
element: g.node(),
gd: gd,
prepFn: function () {
t0 = g.attr('transform');
setCursor(g);
},
moveFn: function (dx, dy) {
g.attr('transform', t0 + strTranslate(dx, dy));
xf = dragElement.align((isVertical ? opts._uFrac : opts._vFrac) + dx / gs.w, isVertical ? opts._thickFrac : opts._lenFrac, 0, 1, opts.xanchor);
yf = dragElement.align((isVertical ? opts._vFrac : 1 - opts._uFrac) - dy / gs.h, isVertical ? opts._lenFrac : opts._thickFrac, 0, 1, opts.yanchor);
var csr = dragElement.getCursor(xf, yf, opts.xanchor, opts.yanchor);
setCursor(g, csr);
},
doneFn: function () {
setCursor(g);
if (xf !== undefined && yf !== undefined) {
var update = {};
update[opts._propPrefix + 'x'] = xf;
update[opts._propPrefix + 'y'] = yf;
if (opts._traceIndex !== undefined) {
Registry.call('_guiRestyle', gd, update, opts._traceIndex);
} else {
Registry.call('_guiRelayout', gd, update);
}
}
}
});
}
function calcLevels(gd, opts, zrange) {
var levelsIn = opts._levels;
var lineLevels = [];
var fillLevels = [];
var l;
var i;
var l0 = levelsIn.end + levelsIn.size / 100;
var ls = levelsIn.size;
var zr0 = 1.001 * zrange[0] - 0.001 * zrange[1];
var zr1 = 1.001 * zrange[1] - 0.001 * zrange[0];
for (i = 0; i < 1e5; i++) {
l = levelsIn.start + i * ls;
if (ls > 0 ? l >= l0 : l <= l0) break;
if (l > zr0 && l < zr1) lineLevels.push(l);
}
if (opts._fillgradient) {
fillLevels = [0];
} else if (typeof opts._fillcolor === 'function') {
var fillLevelsIn = opts._filllevels;
if (fillLevelsIn) {
l0 = fillLevelsIn.end + fillLevelsIn.size / 100;
ls = fillLevelsIn.size;
for (i = 0; i < 1e5; i++) {
l = fillLevelsIn.start + i * ls;
if (ls > 0 ? l >= l0 : l <= l0) break;
if (l > zrange[0] && l < zrange[1]) fillLevels.push(l);
}
} else {
fillLevels = lineLevels.map(function (v) {
return v - levelsIn.size / 2;
});
fillLevels.push(fillLevels[fillLevels.length - 1] + levelsIn.size);
}
} else if (opts._fillcolor && typeof opts._fillcolor === 'string') {
// doesn't matter what this value is, with a single value
// we'll make a single fill rect covering the whole bar
fillLevels = [0];
}
if (levelsIn.size < 0) {
lineLevels.reverse();
fillLevels.reverse();
}
return {
line: lineLevels,
fill: fillLevels
};
}
function mockColorBarAxis(gd, opts, zrange) {
var fullLayout = gd._fullLayout;
var isVertical = opts.orientation === 'v';
var cbAxisIn = {
type: 'linear',
range: zrange,
tickmode: opts.tickmode,
nticks: opts.nticks,
tick0: opts.tick0,
dtick: opts.dtick,
tickvals: opts.tickvals,
ticktext: opts.ticktext,
ticks: opts.ticks,
ticklen: opts.ticklen,
tickwidth: opts.tickwidth,
tickcolor: opts.tickcolor,
showticklabels: opts.showticklabels,
labelalias: opts.labelalias,
ticklabelposition: opts.ticklabelposition,
ticklabeloverflow: opts.ticklabeloverflow,
ticklabelstep: opts.ticklabelstep,
tickfont: opts.tickfont,
tickangle: opts.tickangle,
tickformat: opts.tickformat,
exponentformat: opts.exponentformat,
minexponent: opts.minexponent,
separatethousands: opts.separatethousands,
showexponent: opts.showexponent,
showtickprefix: opts.showtickprefix,
tickprefix: opts.tickprefix,
showticksuffix: opts.showticksuffix,
ticksuffix: opts.ticksuffix,
title: opts.title,
showline: true,
anchor: 'free',
side: isVertical ? 'right' : 'bottom',
position: 1
};
var letter = isVertical ? 'y' : 'x';
var cbAxisOut = {
type: 'linear',
_id: letter + opts._id
};
var axisOptions = {
letter: letter,
font: fullLayout.font,
noAutotickangles: letter === 'y',
noHover: true,
noTickson: true,
noTicklabelmode: true,
noInsideRange: true,
calendar: fullLayout.calendar // not really necessary (yet?)
};
function coerce(attr, dflt) {
return Lib.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt);
}
handleAxisDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout);
handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions);
return cbAxisOut;
}
module.exports = {
draw: draw
};
/***/ }),
/***/ 90553:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
module.exports = function hasColorbar(container) {
return Lib.isPlainObject(container.colorbar);
};
/***/ }),
/***/ 55080:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'component',
name: 'colorbar',
attributes: __webpack_require__(42996),
supplyDefaults: __webpack_require__(64013),
draw: (__webpack_require__(37848).draw),
hasColorbar: __webpack_require__(90553)
};
/***/ }),
/***/ 49084:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorbarAttrs = __webpack_require__(42996);
var counterRegex = (__webpack_require__(53756).counter);
var sortObjectKeys = __webpack_require__(95376);
var palettes = (__webpack_require__(88304).scales);
var paletteStr = sortObjectKeys(palettes);
function code(s) {
return '`' + s + '`';
}
/**
* Make colorscale attribute declarations for
*
* - colorscale,
* - (c|z)auto, (c|z)min, (c|z)max,
* - autocolorscale, reversescale,
* - showscale (optionally)
* - color (optionally)
*
* @param {string} context (dflt: '', i.e. from trace root):
* the container this is in ('', *marker*, *marker.line* etc)
*
* @param {object} opts:
* - cLetter {string} (dflt: 'c'):
* leading letter for 'min', 'max and 'auto' attribute (either 'z' or 'c')
*
* - colorAttr {string} (dflt: 'z' if `cLetter: 'z'`, 'color' if `cLetter: 'c'`):
* (for descriptions) sets the name of the color attribute that maps to the colorscale.
*
* N.B. if `colorAttr: 'color'`, we include the `color` declaration here.
*
* - onlyIfNumerical {string} (dflt: false' if `cLetter: 'z'`, true if `cLetter: 'c'`):
* (for descriptions) set to true if colorscale attribute only
*
* - colorscaleDflt {string}:
* overrides the colorscale dflt
*
* - autoColorDflt {boolean} (dflt true):
* normally autocolorscale.dflt is `true`, but pass `false` to override
*
* - noScale {boolean} (dflt: true if `context: 'marker.line'`, false otherwise):
* set to `false` to not include showscale attribute (e.g. for 'marker.line')
*
* - showScaleDflt {boolean} (dflt: true if `cLetter: 'z'`, false otherwise)
*
* - editTypeOverride {boolean} (dflt: ''):
* most of these attributes already require a recalc, but the ones that do not
* have editType *style* or *plot* unless you override (presumably with *calc*)
*
* - anim {boolean) (dflt: undefined): is 'color' animatable?
*
* @return {object}
*/
module.exports = function colorScaleAttrs(context, opts) {
context = context || '';
opts = opts || {};
var cLetter = opts.cLetter || 'c';
var onlyIfNumerical = 'onlyIfNumerical' in opts ? opts.onlyIfNumerical : Boolean(context);
var noScale = 'noScale' in opts ? opts.noScale : context === 'marker.line';
var showScaleDflt = 'showScaleDflt' in opts ? opts.showScaleDflt : cLetter === 'z';
var colorscaleDflt = typeof opts.colorscaleDflt === 'string' ? palettes[opts.colorscaleDflt] : null;
var editTypeOverride = opts.editTypeOverride || '';
var contextHead = context ? context + '.' : '';
var colorAttr, colorAttrFull;
if ('colorAttr' in opts) {
colorAttr = opts.colorAttr;
colorAttrFull = opts.colorAttr;
} else {
colorAttr = {
z: 'z',
c: 'color'
}[cLetter];
colorAttrFull = 'in ' + code(contextHead + colorAttr);
}
var effectDesc = onlyIfNumerical ? ' Has an effect only if ' + colorAttrFull + ' is set to a numerical array.' : '';
var auto = cLetter + 'auto';
var min = cLetter + 'min';
var max = cLetter + 'max';
var mid = cLetter + 'mid';
var autoFull = code(contextHead + auto);
var minFull = code(contextHead + min);
var maxFull = code(contextHead + max);
var minmaxFull = minFull + ' and ' + maxFull;
var autoImpliedEdits = {};
autoImpliedEdits[min] = autoImpliedEdits[max] = undefined;
var minmaxImpliedEdits = {};
minmaxImpliedEdits[auto] = false;
var attrs = {};
if (colorAttr === 'color') {
attrs.color = {
valType: 'color',
arrayOk: true,
editType: editTypeOverride || 'style'
};
if (opts.anim) {
attrs.color.anim = true;
}
}
attrs[auto] = {
valType: 'boolean',
dflt: true,
editType: 'calc',
impliedEdits: autoImpliedEdits
};
attrs[min] = {
valType: 'number',
dflt: null,
editType: editTypeOverride || 'plot',
impliedEdits: minmaxImpliedEdits
};
attrs[max] = {
valType: 'number',
dflt: null,
editType: editTypeOverride || 'plot',
impliedEdits: minmaxImpliedEdits
};
attrs[mid] = {
valType: 'number',
dflt: null,
editType: 'calc',
impliedEdits: autoImpliedEdits
};
attrs.colorscale = {
valType: 'colorscale',
editType: 'calc',
dflt: colorscaleDflt,
impliedEdits: {
autocolorscale: false
}
};
attrs.autocolorscale = {
valType: 'boolean',
// gets overrode in 'heatmap' & 'surface' for backwards comp.
dflt: opts.autoColorDflt === false ? false : true,
editType: 'calc',
impliedEdits: {
colorscale: undefined
}
};
attrs.reversescale = {
valType: 'boolean',
dflt: false,
editType: 'plot'
};
if (!noScale) {
attrs.showscale = {
valType: 'boolean',
dflt: showScaleDflt,
editType: 'calc'
};
attrs.colorbar = colorbarAttrs;
}
if (!opts.noColorAxis) {
attrs.coloraxis = {
valType: 'subplotid',
regex: counterRegex('coloraxis'),
dflt: null,
editType: 'calc'
};
}
return attrs;
};
/***/ }),
/***/ 47128:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var extractOpts = (__webpack_require__(94288).extractOpts);
module.exports = function calc(gd, trace, opts) {
var fullLayout = gd._fullLayout;
var vals = opts.vals;
var containerStr = opts.containerStr;
var container = containerStr ? Lib.nestedProperty(trace, containerStr).get() : trace;
var cOpts = extractOpts(container);
var auto = cOpts.auto !== false;
var min = cOpts.min;
var max = cOpts.max;
var mid = cOpts.mid;
var minVal = function () {
return Lib.aggNums(Math.min, null, vals);
};
var maxVal = function () {
return Lib.aggNums(Math.max, null, vals);
};
if (min === undefined) {
min = minVal();
} else if (auto) {
if (container._colorAx && isNumeric(min)) {
min = Math.min(min, minVal());
} else {
min = minVal();
}
}
if (max === undefined) {
max = maxVal();
} else if (auto) {
if (container._colorAx && isNumeric(max)) {
max = Math.max(max, maxVal());
} else {
max = maxVal();
}
}
if (auto && mid !== undefined) {
if (max - mid > mid - min) {
min = mid - (max - mid);
} else if (max - mid < mid - min) {
max = mid + (mid - min);
}
}
if (min === max) {
min -= 0.5;
max += 0.5;
}
cOpts._sync('min', min);
cOpts._sync('max', max);
if (cOpts.autocolorscale) {
var scl;
if (min * max < 0) scl = fullLayout.colorscale.diverging;else if (min >= 0) scl = fullLayout.colorscale.sequential;else scl = fullLayout.colorscale.sequentialminus;
cOpts._sync('colorscale', scl);
}
};
/***/ }),
/***/ 95504:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var extractOpts = (__webpack_require__(94288).extractOpts);
module.exports = function crossTraceDefaults(fullData, fullLayout) {
function replace(cont, k) {
var val = cont['_' + k];
if (val !== undefined) {
cont[k] = val;
}
}
function relinkColorAttrs(outerCont, cbOpt) {
var cont = cbOpt.container ? Lib.nestedProperty(outerCont, cbOpt.container).get() : outerCont;
if (cont) {
if (cont.coloraxis) {
// stash ref to color axis
cont._colorAx = fullLayout[cont.coloraxis];
} else {
var cOpts = extractOpts(cont);
var isAuto = cOpts.auto;
if (isAuto || cOpts.min === undefined) {
replace(cont, cbOpt.min);
}
if (isAuto || cOpts.max === undefined) {
replace(cont, cbOpt.max);
}
if (cOpts.autocolorscale) {
replace(cont, 'colorscale');
}
}
}
}
for (var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
var cbOpts = trace._module.colorbar;
if (cbOpts) {
if (Array.isArray(cbOpts)) {
for (var j = 0; j < cbOpts.length; j++) {
relinkColorAttrs(trace, cbOpts[j]);
}
} else {
relinkColorAttrs(trace, cbOpts);
}
}
if (hasColorscale(trace, 'marker.line')) {
relinkColorAttrs(trace, {
container: 'marker.line',
min: 'cmin',
max: 'cmax'
});
}
}
for (var k in fullLayout._colorAxes) {
relinkColorAttrs(fullLayout[k], {
min: 'cmin',
max: 'cmax'
});
}
};
/***/ }),
/***/ 27260:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var hasColorbar = __webpack_require__(90553);
var colorbarDefaults = __webpack_require__(64013);
var isValidScale = (__webpack_require__(88304).isValid);
var traceIs = (__webpack_require__(24040).traceIs);
function npMaybe(parentCont, prefix) {
var containerStr = prefix.slice(0, prefix.length - 1);
return prefix ? Lib.nestedProperty(parentCont, containerStr).get() || {} : parentCont;
}
/**
* Colorscale / colorbar default handler
*
* @param {object} parentContIn : user (input) parent container (e.g. trace or layout coloraxis object)
* @param {object} parentContOut : full parent container
* @param {object} layout : (full) layout object
* @param {fn} coerce : Lib.coerce wrapper
* @param {object} opts :
* - prefix {string} : attr string prefix to colorscale container from parent root
* - cLetter {string} : 'c or 'z' color letter
*/
module.exports = function colorScaleDefaults(parentContIn, parentContOut, layout, coerce, opts) {
var prefix = opts.prefix;
var cLetter = opts.cLetter;
var inTrace = ('_module' in parentContOut);
var containerIn = npMaybe(parentContIn, prefix);
var containerOut = npMaybe(parentContOut, prefix);
var template = npMaybe(parentContOut._template || {}, prefix) || {};
// colorScaleDefaults wrapper called if-ever we need to reset the colorscale
// attributes for containers that were linked to invalid color axes
var thisFn = function () {
delete parentContIn.coloraxis;
delete parentContOut.coloraxis;
return colorScaleDefaults(parentContIn, parentContOut, layout, coerce, opts);
};
if (inTrace) {
var colorAxes = layout._colorAxes || {};
var colorAx = coerce(prefix + 'coloraxis');
if (colorAx) {
var colorbarVisuals = traceIs(parentContOut, 'contour') && Lib.nestedProperty(parentContOut, 'contours.coloring').get() || 'heatmap';
var stash = colorAxes[colorAx];
if (stash) {
stash[2].push(thisFn);
if (stash[0] !== colorbarVisuals) {
stash[0] = false;
Lib.warn(['Ignoring coloraxis:', colorAx, 'setting', 'as it is linked to incompatible colorscales.'].join(' '));
}
} else {
// stash:
// - colorbar visual 'type'
// - colorbar options to help in Colorbar.draw
// - list of colorScaleDefaults wrapper functions
colorAxes[colorAx] = [colorbarVisuals, parentContOut, [thisFn]];
}
return;
}
}
var minIn = containerIn[cLetter + 'min'];
var maxIn = containerIn[cLetter + 'max'];
var validMinMax = isNumeric(minIn) && isNumeric(maxIn) && minIn < maxIn;
var auto = coerce(prefix + cLetter + 'auto', !validMinMax);
if (auto) {
coerce(prefix + cLetter + 'mid');
} else {
coerce(prefix + cLetter + 'min');
coerce(prefix + cLetter + 'max');
}
// handles both the trace case (autocolorscale is false by default) and
// the marker and marker.line case (autocolorscale is true by default)
var sclIn = containerIn.colorscale;
var sclTemplate = template.colorscale;
var autoColorscaleDflt;
if (sclIn !== undefined) autoColorscaleDflt = !isValidScale(sclIn);
if (sclTemplate !== undefined) autoColorscaleDflt = !isValidScale(sclTemplate);
coerce(prefix + 'autocolorscale', autoColorscaleDflt);
coerce(prefix + 'colorscale');
coerce(prefix + 'reversescale');
if (prefix !== 'marker.line.') {
// handles both the trace case where the dflt is listed in attributes and
// the marker case where the dflt is determined by hasColorbar
var showScaleDflt;
if (prefix && inTrace) showScaleDflt = hasColorbar(containerIn);
var showScale = coerce(prefix + 'showscale', showScaleDflt);
if (showScale) {
if (prefix && template) containerOut._template = template;
colorbarDefaults(containerIn, containerOut, layout);
}
}
};
/***/ }),
/***/ 94288:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var tinycolor = __webpack_require__(49760);
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var isValidScale = (__webpack_require__(88304).isValid);
function hasColorscale(trace, containerStr, colorKey) {
var container = containerStr ? Lib.nestedProperty(trace, containerStr).get() || {} : trace;
var color = container[colorKey || 'color'];
if (color && color._inputArray) color = color._inputArray;
var isArrayWithOneNumber = false;
if (Lib.isArrayOrTypedArray(color)) {
for (var i = 0; i < color.length; i++) {
if (isNumeric(color[i])) {
isArrayWithOneNumber = true;
break;
}
}
}
return Lib.isPlainObject(container) && (isArrayWithOneNumber || container.showscale === true || isNumeric(container.cmin) && isNumeric(container.cmax) || isValidScale(container.colorscale) || Lib.isPlainObject(container.colorbar));
}
var constantAttrs = ['showscale', 'autocolorscale', 'colorscale', 'reversescale', 'colorbar'];
var letterAttrs = ['min', 'max', 'mid', 'auto'];
/**
* Extract 'c' / 'z', trace / color axis colorscale options
*
* Note that it would be nice to replace all z* with c* equivalents in v3
*
* @param {object} cont : attribute container
* @return {object}:
* - min: cmin or zmin
* - max: cmax or zmax
* - mid: cmid or zmid
* - auto: cauto or zauto
* - *scale: *scale attrs
* - colorbar: colorbar
* - _sync: function syncing attr and underscore dual (useful when calc'ing min/max)
*/
function extractOpts(cont) {
var colorAx = cont._colorAx;
var cont2 = colorAx ? colorAx : cont;
var out = {};
var cLetter;
var i, k;
for (i = 0; i < constantAttrs.length; i++) {
k = constantAttrs[i];
out[k] = cont2[k];
}
if (colorAx) {
cLetter = 'c';
for (i = 0; i < letterAttrs.length; i++) {
k = letterAttrs[i];
out[k] = cont2['c' + k];
}
} else {
var k2;
for (i = 0; i < letterAttrs.length; i++) {
k = letterAttrs[i];
k2 = 'c' + k;
if (k2 in cont2) {
out[k] = cont2[k2];
continue;
}
k2 = 'z' + k;
if (k2 in cont2) {
out[k] = cont2[k2];
}
}
cLetter = k2.charAt(0);
}
out._sync = function (k, v) {
var k2 = letterAttrs.indexOf(k) !== -1 ? cLetter + k : k;
cont2[k2] = cont2['_' + k2] = v;
};
return out;
}
/**
* Extract colorscale into numeric domain and color range.
*
* @param {object} cont colorscale container (e.g. trace, marker)
* - colorscale {array of arrays}
* - cmin/zmin {number}
* - cmax/zmax {number}
* - reversescale {boolean}
*
* @return {object}
* - domain {array}
* - range {array}
*/
function extractScale(cont) {
var cOpts = extractOpts(cont);
var cmin = cOpts.min;
var cmax = cOpts.max;
var scl = cOpts.reversescale ? flipScale(cOpts.colorscale) : cOpts.colorscale;
var N = scl.length;
var domain = new Array(N);
var range = new Array(N);
for (var i = 0; i < N; i++) {
var si = scl[i];
domain[i] = cmin + si[0] * (cmax - cmin);
range[i] = si[1];
}
return {
domain: domain,
range: range
};
}
function flipScale(scl) {
var N = scl.length;
var sclNew = new Array(N);
for (var i = N - 1, j = 0; i >= 0; i--, j++) {
var si = scl[i];
sclNew[j] = [1 - si[0], si[1]];
}
return sclNew;
}
/**
* General colorscale function generator.
*
* @param {object} specs output of Colorscale.extractScale or precomputed domain, range.
* - domain {array}
* - range {array}
*
* @param {object} opts
* - noNumericCheck {boolean} if true, scale func bypasses numeric checks
* - returnArray {boolean} if true, scale func return 4-item array instead of color strings
*
* @return {function}
*/
function makeColorScaleFunc(specs, opts) {
opts = opts || {};
var domain = specs.domain;
var range = specs.range;
var N = range.length;
var _range = new Array(N);
for (var i = 0; i < N; i++) {
var rgba = tinycolor(range[i]).toRgb();
_range[i] = [rgba.r, rgba.g, rgba.b, rgba.a];
}
var _sclFunc = d3.scale.linear().domain(domain).range(_range).clamp(true);
var noNumericCheck = opts.noNumericCheck;
var returnArray = opts.returnArray;
var sclFunc;
if (noNumericCheck && returnArray) {
sclFunc = _sclFunc;
} else if (noNumericCheck) {
sclFunc = function (v) {
return colorArray2rbga(_sclFunc(v));
};
} else if (returnArray) {
sclFunc = function (v) {
if (isNumeric(v)) return _sclFunc(v);else if (tinycolor(v).isValid()) return v;else return Color.defaultLine;
};
} else {
sclFunc = function (v) {
if (isNumeric(v)) return colorArray2rbga(_sclFunc(v));else if (tinycolor(v).isValid()) return v;else return Color.defaultLine;
};
}
// colorbar draw looks into the d3 scale closure for domain and range
sclFunc.domain = _sclFunc.domain;
sclFunc.range = function () {
return range;
};
return sclFunc;
}
function makeColorScaleFuncFromTrace(trace, opts) {
return makeColorScaleFunc(extractScale(trace), opts);
}
function colorArray2rbga(colorArray) {
var colorObj = {
r: colorArray[0],
g: colorArray[1],
b: colorArray[2],
a: colorArray[3]
};
return tinycolor(colorObj).toRgbString();
}
module.exports = {
hasColorscale: hasColorscale,
extractOpts: extractOpts,
extractScale: extractScale,
flipScale: flipScale,
makeColorScaleFunc: makeColorScaleFunc,
makeColorScaleFuncFromTrace: makeColorScaleFuncFromTrace
};
/***/ }),
/***/ 8932:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scales = __webpack_require__(88304);
var helpers = __webpack_require__(94288);
module.exports = {
moduleType: 'component',
name: 'colorscale',
attributes: __webpack_require__(49084),
layoutAttributes: __webpack_require__(92332),
supplyLayoutDefaults: __webpack_require__(51608),
handleDefaults: __webpack_require__(27260),
crossTraceDefaults: __webpack_require__(95504),
calc: __webpack_require__(47128),
// ./scales.js is required in lib/coerce.js ;
// it needs to be a separate module to avoid a circular dependency
scales: scales.scales,
defaultScale: scales.defaultScale,
getScale: scales.get,
isValidScale: scales.isValid,
hasColorscale: helpers.hasColorscale,
extractOpts: helpers.extractOpts,
extractScale: helpers.extractScale,
flipScale: helpers.flipScale,
makeColorScaleFunc: helpers.makeColorScaleFunc,
makeColorScaleFuncFromTrace: helpers.makeColorScaleFuncFromTrace
};
/***/ }),
/***/ 92332:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var extendFlat = (__webpack_require__(92880).extendFlat);
var colorScaleAttrs = __webpack_require__(49084);
var scales = (__webpack_require__(88304).scales);
var msg = 'Note that `autocolorscale` must be true for this attribute to work.';
module.exports = {
editType: 'calc',
colorscale: {
editType: 'calc',
sequential: {
valType: 'colorscale',
dflt: scales.Reds,
editType: 'calc'
},
sequentialminus: {
valType: 'colorscale',
dflt: scales.Blues,
editType: 'calc'
},
diverging: {
valType: 'colorscale',
dflt: scales.RdBu,
editType: 'calc'
}
},
coloraxis: extendFlat({
// not really a 'subplot' attribute container,
// but this is the flag we use to denote attributes that
// support yaxis, yaxis2, yaxis3, ... counters
_isSubplotObj: true,
editType: 'calc'
}, colorScaleAttrs('', {
colorAttr: 'corresponding trace color array(s)',
noColorAxis: true,
showScaleDflt: true
}))
};
/***/ }),
/***/ 51608:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
var colorScaleAttrs = __webpack_require__(92332);
var colorScaleDefaults = __webpack_require__(27260);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, colorScaleAttrs, attr, dflt);
}
coerce('colorscale.sequential');
coerce('colorscale.sequentialminus');
coerce('colorscale.diverging');
var colorAxes = layoutOut._colorAxes;
var colorAxIn, colorAxOut;
function coerceAx(attr, dflt) {
return Lib.coerce(colorAxIn, colorAxOut, colorScaleAttrs.coloraxis, attr, dflt);
}
for (var k in colorAxes) {
var stash = colorAxes[k];
if (stash[0]) {
colorAxIn = layoutIn[k] || {};
colorAxOut = Template.newContainer(layoutOut, k, 'coloraxis');
colorAxOut._name = k;
colorScaleDefaults(colorAxIn, colorAxOut, layoutOut, coerceAx, {
prefix: '',
cLetter: 'c'
});
} else {
// re-coerce colorscale attributes w/o coloraxis
for (var i = 0; i < stash[2].length; i++) {
stash[2][i]();
}
delete layoutOut._colorAxes[k];
}
}
};
/***/ }),
/***/ 88304:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var tinycolor = __webpack_require__(49760);
var scales = {
Greys: [[0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']],
YlGnBu: [[0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'], [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'], [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'], [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'], [1, 'rgb(255,255,217)']],
Greens: [[0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'], [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'], [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'], [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'], [1, 'rgb(247,252,245)']],
YlOrRd: [[0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'], [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'], [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'], [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'], [1, 'rgb(255,255,204)']],
Bluered: [[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']],
// modified RdBu based on
// http://www.kennethmoreland.com/color-maps/
RdBu: [[0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'], [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'], [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']],
// Scale for non-negative numeric values
Reds: [[0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'], [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']],
// Scale for non-positive numeric values
Blues: [[0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'], [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'], [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']],
Picnic: [[0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'], [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'], [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'], [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'], [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'], [1, 'rgb(255,0,0)']],
Rainbow: [[0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'], [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'], [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'], [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'], [1, 'rgb(255,0,0)']],
Portland: [[0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'], [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'], [1, 'rgb(217,30,30)']],
Jet: [[0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'], [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'], [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']],
Hot: [[0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'], [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']],
Blackbody: [[0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'], [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'], [1, 'rgb(160,200,255)']],
Earth: [[0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'], [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'], [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']],
Electric: [[0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'], [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'], [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']],
Viridis: [[0, '#440154'], [0.06274509803921569, '#48186a'], [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'], [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'], [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'], [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'], [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'], [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'], [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'], [1, '#fde725']],
Cividis: [[0.000000, 'rgb(0,32,76)'], [0.058824, 'rgb(0,42,102)'], [0.117647, 'rgb(0,52,110)'], [0.176471, 'rgb(39,63,108)'], [0.235294, 'rgb(60,74,107)'], [0.294118, 'rgb(76,85,107)'], [0.352941, 'rgb(91,95,109)'], [0.411765, 'rgb(104,106,112)'], [0.470588, 'rgb(117,117,117)'], [0.529412, 'rgb(131,129,120)'], [0.588235, 'rgb(146,140,120)'], [0.647059, 'rgb(161,152,118)'], [0.705882, 'rgb(176,165,114)'], [0.764706, 'rgb(192,177,109)'], [0.823529, 'rgb(209,191,102)'], [0.882353, 'rgb(225,204,92)'], [0.941176, 'rgb(243,219,79)'], [1.000000, 'rgb(255,233,69)']]
};
var defaultScale = scales.RdBu;
function getScale(scl, dflt) {
if (!dflt) dflt = defaultScale;
if (!scl) return dflt;
function parseScale() {
try {
scl = scales[scl] || JSON.parse(scl);
} catch (e) {
scl = dflt;
}
}
if (typeof scl === 'string') {
parseScale();
// occasionally scl is double-JSON encoded...
if (typeof scl === 'string') parseScale();
}
if (!isValidScaleArray(scl)) return dflt;
return scl;
}
function isValidScaleArray(scl) {
var highestVal = 0;
if (!Array.isArray(scl) || scl.length < 2) return false;
if (!scl[0] || !scl[scl.length - 1]) return false;
if (+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;
for (var i = 0; i < scl.length; i++) {
var si = scl[i];
if (si.length !== 2 || +si[0] < highestVal || !tinycolor(si[1]).isValid()) {
return false;
}
highestVal = +si[0];
}
return true;
}
function isValidScale(scl) {
if (scales[scl] !== undefined) return true;else return isValidScaleArray(scl);
}
module.exports = {
scales: scales,
defaultScale: defaultScale,
get: getScale,
isValid: isValidScale
};
/***/ }),
/***/ 78316:
/***/ (function(module) {
"use strict";
// for automatic alignment on dragging, <1/3 means left align,
// >2/3 means right, and between is center. Pick the right fraction
// based on where you are, and return the fraction corresponding to
// that position on the object
module.exports = function align(v, dv, v0, v1, anchor) {
var vmin = (v - v0) / (v1 - v0);
var vmax = vmin + dv / (v1 - v0);
var vc = (vmin + vmax) / 2;
// explicitly specified anchor
if (anchor === 'left' || anchor === 'bottom') return vmin;
if (anchor === 'center' || anchor === 'middle') return vc;
if (anchor === 'right' || anchor === 'top') return vmax;
// automatic based on position
if (vmin < 2 / 3 - vc) return vmin;
if (vmax > 4 / 3 - vc) return vmax;
return vc;
};
/***/ }),
/***/ 67416:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
// set cursors pointing toward the closest corner/side,
// to indicate alignment
// x and y are 0-1, fractions of the plot area
var cursorset = [['sw-resize', 's-resize', 'se-resize'], ['w-resize', 'move', 'e-resize'], ['nw-resize', 'n-resize', 'ne-resize']];
module.exports = function getCursor(x, y, xanchor, yanchor) {
if (xanchor === 'left') x = 0;else if (xanchor === 'center') x = 1;else if (xanchor === 'right') x = 2;else x = Lib.constrain(Math.floor(x * 3), 0, 2);
if (yanchor === 'bottom') y = 0;else if (yanchor === 'middle') y = 1;else if (yanchor === 'top') y = 2;else y = Lib.constrain(Math.floor(y * 3), 0, 2);
return cursorset[y][x];
};
/***/ }),
/***/ 72760:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
exports.selectMode = function (dragmode) {
return dragmode === 'lasso' || dragmode === 'select';
};
exports.drawMode = function (dragmode) {
return dragmode === 'drawclosedpath' || dragmode === 'drawopenpath' || dragmode === 'drawline' || dragmode === 'drawrect' || dragmode === 'drawcircle';
};
exports.openMode = function (dragmode) {
return dragmode === 'drawline' || dragmode === 'drawopenpath';
};
exports.rectMode = function (dragmode) {
return dragmode === 'select' || dragmode === 'drawline' || dragmode === 'drawrect' || dragmode === 'drawcircle';
};
exports.freeMode = function (dragmode) {
return dragmode === 'lasso' || dragmode === 'drawclosedpath' || dragmode === 'drawopenpath';
};
exports.selectingOrDrawing = function (dragmode) {
return exports.freeMode(dragmode) || exports.rectMode(dragmode);
};
/***/ }),
/***/ 86476:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var mouseOffset = __webpack_require__(29128);
var hasHover = __webpack_require__(52264);
var supportsPassive = __webpack_require__(89184);
var removeElement = (__webpack_require__(3400).removeElement);
var constants = __webpack_require__(33816);
var dragElement = module.exports = {};
dragElement.align = __webpack_require__(78316);
dragElement.getCursor = __webpack_require__(67416);
var unhover = __webpack_require__(2616);
dragElement.unhover = unhover.wrapped;
dragElement.unhoverRaw = unhover.raw;
/**
* Abstracts click & drag interactions
*
* During the interaction, a "coverSlip" element - a transparent
* div covering the whole page - is created, which has two key effects:
* - Lets you drag beyond the boundaries of the plot itself without
* dropping (but if you drag all the way out of the browser window the
* interaction will end)
* - Freezes the cursor: whatever mouse cursor the drag element had when the
* interaction started gets copied to the coverSlip for use until mouseup
*
* If the user executes a drag bigger than MINDRAG, callbacks will fire as:
* prepFn, moveFn (1 or more times), doneFn
* If the user does not drag enough, prepFn and clickFn will fire.
*
* Note: If you cancel contextmenu, clickFn will fire even with a right click
* (unlike native events) so you'll get a `plotly_click` event. Cancel context eg:
* gd.addEventListener('contextmenu', function(e) { e.preventDefault(); });
* TODO: we should probably turn this into a `config` parameter, so we can fix it
* such that if you *don't* cancel contextmenu, we can prevent partial drags, which
* put you in a weird state.
*
* If the user clicks multiple times quickly, clickFn will fire each time
* but numClicks will increase to help you recognize doubleclicks.
*
* @param {object} options with keys:
* element (required) the DOM element to drag
* prepFn (optional) function(event, startX, startY)
* executed on mousedown
* startX and startY are the clientX and clientY pixel position
* of the mousedown event
* moveFn (optional) function(dx, dy)
* executed on move, ONLY after we've exceeded MINDRAG
* (we keep executing moveFn if you move back to where you started)
* dx and dy are the net pixel offset of the drag,
* dragged is true/false, has the mouse moved enough to
* constitute a drag
* doneFn (optional) function(e)
* executed on mouseup, ONLY if we exceeded MINDRAG (so you can be
* sure that moveFn has been called at least once)
* numClicks is how many clicks we've registered within
* a doubleclick time
* e is the original mouseup event
* clickFn (optional) function(numClicks, e)
* executed on mouseup if we have NOT exceeded MINDRAG (ie moveFn
* has not been called at all)
* numClicks is how many clicks we've registered within
* a doubleclick time
* e is the original mousedown event
* clampFn (optional, function(dx, dy) return [dx2, dy2])
* Provide custom clamping function for small displacements.
* By default, clamping is done using `minDrag` to x and y displacements
* independently.
*/
dragElement.init = function init(options) {
var gd = options.gd;
var numClicks = 1;
var doubleClickDelay = gd._context.doubleClickDelay;
var element = options.element;
var startX, startY, newMouseDownTime, cursor, dragCover, initialEvent, initialTarget, rightClick;
if (!gd._mouseDownTime) gd._mouseDownTime = 0;
element.style.pointerEvents = 'all';
element.onmousedown = onStart;
if (!supportsPassive) {
element.ontouchstart = onStart;
} else {
if (element._ontouchstart) {
element.removeEventListener('touchstart', element._ontouchstart);
}
element._ontouchstart = onStart;
element.addEventListener('touchstart', onStart, {
passive: false
});
}
function _clampFn(dx, dy, minDrag) {
if (Math.abs(dx) < minDrag) dx = 0;
if (Math.abs(dy) < minDrag) dy = 0;
return [dx, dy];
}
var clampFn = options.clampFn || _clampFn;
function onStart(e) {
// make dragging and dragged into properties of gd
// so that others can look at and modify them
gd._dragged = false;
gd._dragging = true;
var offset = pointerOffset(e);
startX = offset[0];
startY = offset[1];
initialTarget = e.target;
initialEvent = e;
rightClick = e.buttons === 2 || e.ctrlKey;
// fix Fx.hover for touch events
if (typeof e.clientX === 'undefined' && typeof e.clientY === 'undefined') {
e.clientX = startX;
e.clientY = startY;
}
newMouseDownTime = new Date().getTime();
if (newMouseDownTime - gd._mouseDownTime < doubleClickDelay) {
// in a click train
numClicks += 1;
} else {
// new click train
numClicks = 1;
gd._mouseDownTime = newMouseDownTime;
}
if (options.prepFn) options.prepFn(e, startX, startY);
if (hasHover && !rightClick) {
dragCover = coverSlip();
dragCover.style.cursor = window.getComputedStyle(element).cursor;
} else if (!hasHover) {
// document acts as a dragcover for mobile, bc we can't create dragcover dynamically
dragCover = document;
cursor = window.getComputedStyle(document.documentElement).cursor;
document.documentElement.style.cursor = window.getComputedStyle(element).cursor;
}
document.addEventListener('mouseup', onDone);
document.addEventListener('touchend', onDone);
if (options.dragmode !== false) {
e.preventDefault();
document.addEventListener('mousemove', onMove);
document.addEventListener('touchmove', onMove, {
passive: false
});
}
return;
}
function onMove(e) {
e.preventDefault();
var offset = pointerOffset(e);
var minDrag = options.minDrag || constants.MINDRAG;
var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag);
var dx = dxdy[0];
var dy = dxdy[1];
if (dx || dy) {
gd._dragged = true;
dragElement.unhover(gd, e);
}
if (gd._dragged && options.moveFn && !rightClick) {
gd._dragdata = {
element: element,
dx: dx,
dy: dy
};
options.moveFn(dx, dy);
}
return;
}
function onDone(e) {
delete gd._dragdata;
if (options.dragmode !== false) {
e.preventDefault();
document.removeEventListener('mousemove', onMove);
document.removeEventListener('touchmove', onMove);
}
document.removeEventListener('mouseup', onDone);
document.removeEventListener('touchend', onDone);
if (hasHover) {
removeElement(dragCover);
} else if (cursor) {
dragCover.documentElement.style.cursor = cursor;
cursor = null;
}
if (!gd._dragging) {
gd._dragged = false;
return;
}
gd._dragging = false;
// don't count as a dblClick unless the mouseUp is also within
// the dblclick delay
if (new Date().getTime() - gd._mouseDownTime > doubleClickDelay) {
numClicks = Math.max(numClicks - 1, 1);
}
if (gd._dragged) {
if (options.doneFn) options.doneFn();
} else {
if (options.clickFn) options.clickFn(numClicks, initialEvent);
// If we haven't dragged, this should be a click. But because of the
// coverSlip changing the element, the natural system might not generate one,
// so we need to make our own. But right clicks don't normally generate
// click events, only contextmenu events, which happen on mousedown.
if (!rightClick) {
var e2;
try {
e2 = new MouseEvent('click', e);
} catch (err) {
var offset = pointerOffset(e);
e2 = document.createEvent('MouseEvents');
e2.initMouseEvent('click', e.bubbles, e.cancelable, e.view, e.detail, e.screenX, e.screenY, offset[0], offset[1], e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
}
initialTarget.dispatchEvent(e2);
}
}
gd._dragging = false;
gd._dragged = false;
return;
}
};
function coverSlip() {
var cover = document.createElement('div');
cover.className = 'dragcover';
var cStyle = cover.style;
cStyle.position = 'fixed';
cStyle.left = 0;
cStyle.right = 0;
cStyle.top = 0;
cStyle.bottom = 0;
cStyle.zIndex = 999999999;
cStyle.background = 'none';
document.body.appendChild(cover);
return cover;
}
dragElement.coverSlip = coverSlip;
function pointerOffset(e) {
return mouseOffset(e.changedTouches ? e.changedTouches[0] : e, document.body);
}
/***/ }),
/***/ 2616:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Events = __webpack_require__(95924);
var throttle = __webpack_require__(91200);
var getGraphDiv = (__webpack_require__(52200).getGraphDiv);
var hoverConstants = __webpack_require__(92456);
var unhover = module.exports = {};
unhover.wrapped = function (gd, evt, subplot) {
gd = getGraphDiv(gd);
// Important, clear any queued hovers
if (gd._fullLayout) {
throttle.clear(gd._fullLayout._uid + hoverConstants.HOVERID);
}
unhover.raw(gd, evt, subplot);
};
// remove hover effects on mouse out, and emit unhover event
unhover.raw = function raw(gd, evt) {
var fullLayout = gd._fullLayout;
var oldhoverdata = gd._hoverdata;
if (!evt) evt = {};
if (evt.target && !gd._dragged && Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
return;
}
fullLayout._hoverlayer.selectAll('g').remove();
fullLayout._hoverlayer.selectAll('line').remove();
fullLayout._hoverlayer.selectAll('circle').remove();
gd._hoverdata = undefined;
if (evt.target && oldhoverdata) {
gd.emit('plotly_unhover', {
event: evt,
points: oldhoverdata
});
}
};
/***/ }),
/***/ 98192:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
exports.u = {
valType: 'string',
// string type usually doesn't take values... this one should really be
// a special type or at least a special coercion function, from the GUI
// you only get these values but elsewhere the user can supply a list of
// dash lengths in px, and it will be honored
values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'],
dflt: 'solid',
editType: 'style'
};
exports.c = {
shape: {
valType: 'enumerated',
values: ['', '/', '\\', 'x', '-', '|', '+', '.'],
dflt: '',
arrayOk: true,
editType: 'style'
},
fillmode: {
valType: 'enumerated',
values: ['replace', 'overlay'],
dflt: 'replace',
editType: 'style'
},
bgcolor: {
valType: 'color',
arrayOk: true,
editType: 'style'
},
fgcolor: {
valType: 'color',
arrayOk: true,
editType: 'style'
},
fgopacity: {
valType: 'number',
editType: 'style',
min: 0,
max: 1
},
size: {
valType: 'number',
min: 0,
dflt: 8,
arrayOk: true,
editType: 'style'
},
solidity: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.3,
arrayOk: true,
editType: 'style'
},
editType: 'style'
};
/***/ }),
/***/ 43616:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var numberFormat = Lib.numberFormat;
var isNumeric = __webpack_require__(38248);
var tinycolor = __webpack_require__(49760);
var Registry = __webpack_require__(24040);
var Color = __webpack_require__(76308);
var Colorscale = __webpack_require__(8932);
var strTranslate = Lib.strTranslate;
var svgTextUtils = __webpack_require__(72736);
var xmlnsNamespaces = __webpack_require__(9616);
var alignment = __webpack_require__(84284);
var LINE_SPACING = alignment.LINE_SPACING;
var DESELECTDIM = (__webpack_require__(13448).DESELECTDIM);
var subTypes = __webpack_require__(43028);
var makeBubbleSizeFn = __webpack_require__(7152);
var appendArrayPointValue = (__webpack_require__(10624).appendArrayPointValue);
var drawing = module.exports = {};
// -----------------------------------------------------
// styling functions for plot elements
// -----------------------------------------------------
drawing.font = function (s, font) {
var variant = font.variant;
var style = font.style;
var weight = font.weight;
var color = font.color;
var size = font.size;
var family = font.family;
var shadow = font.shadow;
var lineposition = font.lineposition;
var textcase = font.textcase;
if (family) s.style('font-family', family);
if (size + 1) s.style('font-size', size + 'px');
if (color) s.call(Color.fill, color);
if (weight) s.style('font-weight', weight);
if (style) s.style('font-style', style);
if (variant) s.style('font-variant', variant);
if (textcase) s.style('text-transform', dropNone(textcase2transform(textcase)));
if (shadow) s.style('text-shadow', shadow === 'auto' ? svgTextUtils.makeTextShadow(Color.contrast(color)) : dropNone(shadow));
if (lineposition) s.style('text-decoration-line', dropNone(lineposition2decorationLine(lineposition)));
};
function dropNone(a) {
return a === 'none' ? undefined : a;
}
var textcase2transformOptions = {
normal: 'none',
lower: 'lowercase',
upper: 'uppercase',
'word caps': 'capitalize'
};
function textcase2transform(textcase) {
return textcase2transformOptions[textcase];
}
function lineposition2decorationLine(lineposition) {
return lineposition.replace('under', 'underline').replace('over', 'overline').replace('through', 'line-through').split('+').join(' ');
}
/*
* Positioning helpers
* Note: do not use `setPosition` with nodes modified by
* `svgTextUtils.convertToTspans`. Use `svgTextUtils.positionText`
* instead, so that elements get updated to match.
*/
drawing.setPosition = function (s, x, y) {
s.attr('x', x).attr('y', y);
};
drawing.setSize = function (s, w, h) {
s.attr('width', w).attr('height', h);
};
drawing.setRect = function (s, x, y, w, h) {
s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h);
};
/** Translate node
*
* @param {object} d : calcdata point item
* @param {sel} sel : d3 selction of node to translate
* @param {object} xa : corresponding full xaxis object
* @param {object} ya : corresponding full yaxis object
*
* @return {boolean} :
* true if selection got translated
* false if selection could not get translated
*/
drawing.translatePoint = function (d, sel, xa, ya) {
var x = xa.c2p(d.x);
var y = ya.c2p(d.y);
if (isNumeric(x) && isNumeric(y) && sel.node()) {
// for multiline text this works better
if (sel.node().nodeName === 'text') {
sel.attr('x', x).attr('y', y);
} else {
sel.attr('transform', strTranslate(x, y));
}
} else {
return false;
}
return true;
};
drawing.translatePoints = function (s, xa, ya) {
s.each(function (d) {
var sel = d3.select(this);
drawing.translatePoint(d, sel, xa, ya);
});
};
drawing.hideOutsideRangePoint = function (d, sel, xa, ya, xcalendar, ycalendar) {
sel.attr('display', xa.isPtWithinRange(d, xcalendar) && ya.isPtWithinRange(d, ycalendar) ? null : 'none');
};
drawing.hideOutsideRangePoints = function (traceGroups, subplot) {
if (!subplot._hasClipOnAxisFalse) return;
var xa = subplot.xaxis;
var ya = subplot.yaxis;
traceGroups.each(function (d) {
var trace = d[0].trace;
var xcalendar = trace.xcalendar;
var ycalendar = trace.ycalendar;
var selector = Registry.traceIs(trace, 'bar-like') ? '.bartext' : '.point,.textpoint';
traceGroups.selectAll(selector).each(function (d) {
drawing.hideOutsideRangePoint(d, d3.select(this), xa, ya, xcalendar, ycalendar);
});
});
};
drawing.crispRound = function (gd, lineWidth, dflt) {
// for lines that disable antialiasing we want to
// make sure the width is an integer, and at least 1 if it's nonzero
if (!lineWidth || !isNumeric(lineWidth)) return dflt || 0;
// but not for static plots - these don't get antialiased anyway.
if (gd._context.staticPlot) return lineWidth;
if (lineWidth < 1) return 1;
return Math.round(lineWidth);
};
drawing.singleLineStyle = function (d, s, lw, lc, ld) {
s.style('fill', 'none');
var line = (((d || [])[0] || {}).trace || {}).line || {};
var lw1 = lw || line.width || 0;
var dash = ld || line.dash || '';
Color.stroke(s, lc || line.color);
drawing.dashLine(s, dash, lw1);
};
drawing.lineGroupStyle = function (s, lw, lc, ld) {
s.style('fill', 'none').each(function (d) {
var line = (((d || [])[0] || {}).trace || {}).line || {};
var lw1 = lw || line.width || 0;
var dash = ld || line.dash || '';
d3.select(this).call(Color.stroke, lc || line.color).call(drawing.dashLine, dash, lw1);
});
};
drawing.dashLine = function (s, dash, lineWidth) {
lineWidth = +lineWidth || 0;
dash = drawing.dashStyle(dash, lineWidth);
s.style({
'stroke-dasharray': dash,
'stroke-width': lineWidth + 'px'
});
};
drawing.dashStyle = function (dash, lineWidth) {
lineWidth = +lineWidth || 1;
var dlw = Math.max(lineWidth, 3);
if (dash === 'solid') dash = '';else if (dash === 'dot') dash = dlw + 'px,' + dlw + 'px';else if (dash === 'dash') dash = 3 * dlw + 'px,' + 3 * dlw + 'px';else if (dash === 'longdash') dash = 5 * dlw + 'px,' + 5 * dlw + 'px';else if (dash === 'dashdot') {
dash = 3 * dlw + 'px,' + dlw + 'px,' + dlw + 'px,' + dlw + 'px';
} else if (dash === 'longdashdot') {
dash = 5 * dlw + 'px,' + 2 * dlw + 'px,' + dlw + 'px,' + 2 * dlw + 'px';
}
// otherwise user wrote the dasharray themselves - leave it be
return dash;
};
function setFillStyle(sel, trace, gd, forLegend) {
var markerPattern = trace.fillpattern;
var fillgradient = trace.fillgradient;
var patternShape = markerPattern && drawing.getPatternAttr(markerPattern.shape, 0, '');
if (patternShape) {
var patternBGColor = drawing.getPatternAttr(markerPattern.bgcolor, 0, null);
var patternFGColor = drawing.getPatternAttr(markerPattern.fgcolor, 0, null);
var patternFGOpacity = markerPattern.fgopacity;
var patternSize = drawing.getPatternAttr(markerPattern.size, 0, 8);
var patternSolidity = drawing.getPatternAttr(markerPattern.solidity, 0, 0.3);
var patternID = trace.uid;
drawing.pattern(sel, 'point', gd, patternID, patternShape, patternSize, patternSolidity, undefined, markerPattern.fillmode, patternBGColor, patternFGColor, patternFGOpacity);
} else if (fillgradient && fillgradient.type !== 'none') {
var direction = fillgradient.type;
var gradientID = 'scatterfill-' + trace.uid;
if (forLegend) {
gradientID = 'legendfill-' + trace.uid;
}
if (!forLegend && (fillgradient.start !== undefined || fillgradient.stop !== undefined)) {
var start, stop;
if (direction === 'horizontal') {
start = {
x: fillgradient.start,
y: 0
};
stop = {
x: fillgradient.stop,
y: 0
};
} else if (direction === 'vertical') {
start = {
x: 0,
y: fillgradient.start
};
stop = {
x: 0,
y: fillgradient.stop
};
}
start.x = trace._xA.c2p(start.x === undefined ? trace._extremes.x.min[0].val : start.x, true);
start.y = trace._yA.c2p(start.y === undefined ? trace._extremes.y.min[0].val : start.y, true);
stop.x = trace._xA.c2p(stop.x === undefined ? trace._extremes.x.max[0].val : stop.x, true);
stop.y = trace._yA.c2p(stop.y === undefined ? trace._extremes.y.max[0].val : stop.y, true);
sel.call(gradientWithBounds, gd, gradientID, 'linear', fillgradient.colorscale, 'fill', start, stop, true, false);
} else {
if (direction === 'horizontal') {
direction = direction + 'reversed';
}
sel.call(drawing.gradient, gd, gradientID, direction, fillgradient.colorscale, 'fill');
}
} else if (trace.fillcolor) {
sel.call(Color.fill, trace.fillcolor);
}
}
// Same as fillGroupStyle, except in this case the selection may be a transition
drawing.singleFillStyle = function (sel, gd) {
var node = d3.select(sel.node());
var data = node.data();
var trace = ((data[0] || [])[0] || {}).trace || {};
setFillStyle(sel, trace, gd, false);
};
drawing.fillGroupStyle = function (s, gd, forLegend) {
s.style('stroke-width', 0).each(function (d) {
var shape = d3.select(this);
// N.B. 'd' won't be a calcdata item when
// fill !== 'none' on a segment-less and marker-less trace
if (d[0].trace) {
setFillStyle(shape, d[0].trace, gd, forLegend);
}
});
};
var SYMBOLDEFS = __webpack_require__(71984);
drawing.symbolNames = [];
drawing.symbolFuncs = [];
drawing.symbolBackOffs = [];
drawing.symbolNeedLines = {};
drawing.symbolNoDot = {};
drawing.symbolNoFill = {};
drawing.symbolList = [];
Object.keys(SYMBOLDEFS).forEach(function (k) {
var symDef = SYMBOLDEFS[k];
var n = symDef.n;
drawing.symbolList.push(n, String(n), k, n + 100, String(n + 100), k + '-open');
drawing.symbolNames[n] = k;
drawing.symbolFuncs[n] = symDef.f;
drawing.symbolBackOffs[n] = symDef.backoff || 0;
if (symDef.needLine) {
drawing.symbolNeedLines[n] = true;
}
if (symDef.noDot) {
drawing.symbolNoDot[n] = true;
} else {
drawing.symbolList.push(n + 200, String(n + 200), k + '-dot', n + 300, String(n + 300), k + '-open-dot');
}
if (symDef.noFill) {
drawing.symbolNoFill[n] = true;
}
});
var MAXSYMBOL = drawing.symbolNames.length;
// add a dot in the middle of the symbol
var DOTPATH = 'M0,0.5L0.5,0L0,-0.5L-0.5,0Z';
drawing.symbolNumber = function (v) {
if (isNumeric(v)) {
v = +v;
} else if (typeof v === 'string') {
var vbase = 0;
if (v.indexOf('-open') > 0) {
vbase = 100;
v = v.replace('-open', '');
}
if (v.indexOf('-dot') > 0) {
vbase += 200;
v = v.replace('-dot', '');
}
v = drawing.symbolNames.indexOf(v);
if (v >= 0) {
v += vbase;
}
}
return v % 100 >= MAXSYMBOL || v >= 400 ? 0 : Math.floor(Math.max(v, 0));
};
function makePointPath(symbolNumber, r, t, s) {
var base = symbolNumber % 100;
return drawing.symbolFuncs[base](r, t, s) + (symbolNumber >= 200 ? DOTPATH : '');
}
var stopFormatter = numberFormat('~f');
var gradientInfo = {
radial: {
type: 'radial'
},
radialreversed: {
type: 'radial',
reversed: true
},
horizontal: {
type: 'linear',
start: {
x: 1,
y: 0
},
stop: {
x: 0,
y: 0
}
},
horizontalreversed: {
type: 'linear',
start: {
x: 1,
y: 0
},
stop: {
x: 0,
y: 0
},
reversed: true
},
vertical: {
type: 'linear',
start: {
x: 0,
y: 1
},
stop: {
x: 0,
y: 0
}
},
verticalreversed: {
type: 'linear',
start: {
x: 0,
y: 1
},
stop: {
x: 0,
y: 0
},
reversed: true
}
};
/**
* gradient: create and apply a gradient fill
*
* @param {object} sel: d3 selection to apply this gradient to
* You can use `selection.call(Drawing.gradient, ...)`
* @param {DOM element} gd: the graph div `sel` is part of
* @param {string} gradientID: a unique (within this plot) identifier
* for this gradient, so that we don't create unnecessary definitions
* @param {string} type: 'radial', 'horizontal', or 'vertical', optionally with
* 'reversed' at the end. Normally radial goes center to edge,
* horizontal goes right to left, and vertical goes bottom to top
* @param {array} colorscale: as in attribute values, [[fraction, color], ...]
* @param {string} prop: the property to apply to, 'fill' or 'stroke'
*/
drawing.gradient = function (sel, gd, gradientID, type, colorscale, prop) {
var info = gradientInfo[type];
return gradientWithBounds(sel, gd, gradientID, info.type, colorscale, prop, info.start, info.stop, false, info.reversed);
};
/**
* gradient_with_bounds: create and apply a gradient fill for defined start and stop positions
*
* @param {object} sel: d3 selection to apply this gradient to
* You can use `selection.call(Drawing.gradient, ...)`
* @param {DOM element} gd: the graph div `sel` is part of
* @param {string} gradientID: a unique (within this plot) identifier
* for this gradient, so that we don't create unnecessary definitions
* @param {string} type: 'radial' or 'linear'. Radial goes center to edge,
* horizontal goes as defined by start and stop
* @param {array} colorscale: as in attribute values, [[fraction, color], ...]
* @param {string} prop: the property to apply to, 'fill' or 'stroke'
* @param {object} start: start point for linear gradients, { x: number, y: number }.
* Ignored if type is 'radial'.
* @param {object} stop: stop point for linear gradients, { x: number, y: number }.
* Ignored if type is 'radial'.
* @param {boolean} inUserSpace: If true, start and stop give absolute values in the plot.
* If false, start and stop are fractions of the traces extent along each axis.
* @param {boolean} reversed: If true, the gradient is reversed between normal start and stop,
* i.e., the colorscale is applied in order from stop to start for linear, from edge
* to center for radial gradients.
*/
function gradientWithBounds(sel, gd, gradientID, type, colorscale, prop, start, stop, inUserSpace, reversed) {
var len = colorscale.length;
var info;
if (type === 'linear') {
info = {
node: 'linearGradient',
attrs: {
x1: start.x,
y1: start.y,
x2: stop.x,
y2: stop.y,
gradientUnits: inUserSpace ? 'userSpaceOnUse' : 'objectBoundingBox'
},
reversed: reversed
};
} else if (type === 'radial') {
info = {
node: 'radialGradient',
reversed: reversed
};
}
var colorStops = new Array(len);
for (var i = 0; i < len; i++) {
if (info.reversed) {
colorStops[len - 1 - i] = [stopFormatter((1 - colorscale[i][0]) * 100), colorscale[i][1]];
} else {
colorStops[i] = [stopFormatter(colorscale[i][0] * 100), colorscale[i][1]];
}
}
var fullLayout = gd._fullLayout;
var fullID = 'g' + fullLayout._uid + '-' + gradientID;
var gradient = fullLayout._defs.select('.gradients').selectAll('#' + fullID).data([type + colorStops.join(';')], Lib.identity);
gradient.exit().remove();
gradient.enter().append(info.node).each(function () {
var el = d3.select(this);
if (info.attrs) el.attr(info.attrs);
el.attr('id', fullID);
var stops = el.selectAll('stop').data(colorStops);
stops.exit().remove();
stops.enter().append('stop');
stops.each(function (d) {
var tc = tinycolor(d[1]);
d3.select(this).attr({
offset: d[0] + '%',
'stop-color': Color.tinyRGB(tc),
'stop-opacity': tc.getAlpha()
});
});
});
sel.style(prop, getFullUrl(fullID, gd)).style(prop + '-opacity', null);
sel.classed('gradient_filled', true);
}
/**
* pattern: create and apply a pattern fill
*
* @param {object} sel: d3 selection to apply this pattern to
* You can use `selection.call(Drawing.pattern, ...)`
* @param {string} calledBy: option to know the caller component
* @param {DOM element} gd: the graph div `sel` is part of
* @param {string} patternID: a unique (within this plot) identifier
* for this pattern, so that we don't create unnecessary definitions
* @param {number} size: size of unit squares for repetition of this pattern
* @param {number} solidity: how solid lines of this pattern are
* @param {string} mcc: color when painted with colorscale
* @param {string} fillmode: fillmode for this pattern
* @param {string} bgcolor: background color for this pattern
* @param {string} fgcolor: foreground color for this pattern
* @param {number} fgopacity: foreground opacity for this pattern
*/
drawing.pattern = function (sel, calledBy, gd, patternID, shape, size, solidity, mcc, fillmode, bgcolor, fgcolor, fgopacity) {
var isLegend = calledBy === 'legend';
if (mcc) {
if (fillmode === 'overlay') {
bgcolor = mcc;
fgcolor = Color.contrast(bgcolor);
} else {
bgcolor = undefined;
fgcolor = mcc;
}
}
var fullLayout = gd._fullLayout;
var fullID = 'p' + fullLayout._uid + '-' + patternID;
var width, height;
// linear interpolation
var linearFn = function (x, x0, x1, y0, y1) {
return y0 + (y1 - y0) * (x - x0) / (x1 - x0);
};
var path, linewidth, radius;
var patternTag;
var patternAttrs = {};
var fgC = tinycolor(fgcolor);
var fgRGB = Color.tinyRGB(fgC);
var fgAlpha = fgC.getAlpha();
var opacity = fgopacity * fgAlpha;
switch (shape) {
case '/':
width = size * Math.sqrt(2);
height = size * Math.sqrt(2);
path = 'M-' + width / 4 + ',' + height / 4 + 'l' + width / 2 + ',-' + height / 2 + 'M0,' + height + 'L' + width + ',0' + 'M' + width / 4 * 3 + ',' + height / 4 * 5 + 'l' + width / 2 + ',-' + height / 2;
linewidth = solidity * size;
patternTag = 'path';
patternAttrs = {
d: path,
opacity: opacity,
stroke: fgRGB,
'stroke-width': linewidth + 'px'
};
break;
case '\\':
width = size * Math.sqrt(2);
height = size * Math.sqrt(2);
path = 'M' + width / 4 * 3 + ',-' + height / 4 + 'l' + width / 2 + ',' + height / 2 + 'M0,0L' + width + ',' + height + 'M-' + width / 4 + ',' + height / 4 * 3 + 'l' + width / 2 + ',' + height / 2;
linewidth = solidity * size;
patternTag = 'path';
patternAttrs = {
d: path,
opacity: opacity,
stroke: fgRGB,
'stroke-width': linewidth + 'px'
};
break;
case 'x':
width = size * Math.sqrt(2);
height = size * Math.sqrt(2);
path = 'M-' + width / 4 + ',' + height / 4 + 'l' + width / 2 + ',-' + height / 2 + 'M0,' + height + 'L' + width + ',0' + 'M' + width / 4 * 3 + ',' + height / 4 * 5 + 'l' + width / 2 + ',-' + height / 2 + 'M' + width / 4 * 3 + ',-' + height / 4 + 'l' + width / 2 + ',' + height / 2 + 'M0,0L' + width + ',' + height + 'M-' + width / 4 + ',' + height / 4 * 3 + 'l' + width / 2 + ',' + height / 2;
linewidth = size - size * Math.sqrt(1.0 - solidity);
patternTag = 'path';
patternAttrs = {
d: path,
opacity: opacity,
stroke: fgRGB,
'stroke-width': linewidth + 'px'
};
break;
case '|':
width = size;
height = size;
patternTag = 'path';
path = 'M' + width / 2 + ',0L' + width / 2 + ',' + height;
linewidth = solidity * size;
patternTag = 'path';
patternAttrs = {
d: path,
opacity: opacity,
stroke: fgRGB,
'stroke-width': linewidth + 'px'
};
break;
case '-':
width = size;
height = size;
patternTag = 'path';
path = 'M0,' + height / 2 + 'L' + width + ',' + height / 2;
linewidth = solidity * size;
patternTag = 'path';
patternAttrs = {
d: path,
opacity: opacity,
stroke: fgRGB,
'stroke-width': linewidth + 'px'
};
break;
case '+':
width = size;
height = size;
patternTag = 'path';
path = 'M' + width / 2 + ',0L' + width / 2 + ',' + height + 'M0,' + height / 2 + 'L' + width + ',' + height / 2;
linewidth = size - size * Math.sqrt(1.0 - solidity);
patternTag = 'path';
patternAttrs = {
d: path,
opacity: opacity,
stroke: fgRGB,
'stroke-width': linewidth + 'px'
};
break;
case '.':
width = size;
height = size;
if (solidity < Math.PI / 4) {
radius = Math.sqrt(solidity * size * size / Math.PI);
} else {
radius = linearFn(solidity, Math.PI / 4, 1.0, size / 2, size / Math.sqrt(2));
}
patternTag = 'circle';
patternAttrs = {
cx: width / 2,
cy: height / 2,
r: radius,
opacity: opacity,
fill: fgRGB
};
break;
}
var str = [shape || 'noSh', bgcolor || 'noBg', fgcolor || 'noFg', size, solidity].join(';');
var pattern = fullLayout._defs.select('.patterns').selectAll('#' + fullID).data([str], Lib.identity);
pattern.exit().remove();
pattern.enter().append('pattern').each(function () {
var el = d3.select(this);
el.attr({
id: fullID,
width: width + 'px',
height: height + 'px',
patternUnits: 'userSpaceOnUse',
// for legends scale down patterns just a bit so that default size (i.e 8) nicely fit in small icons
patternTransform: isLegend ? 'scale(0.8)' : ''
});
if (bgcolor) {
var bgC = tinycolor(bgcolor);
var bgRGB = Color.tinyRGB(bgC);
var bgAlpha = bgC.getAlpha();
var rects = el.selectAll('rect').data([0]);
rects.exit().remove();
rects.enter().append('rect').attr({
width: width + 'px',
height: height + 'px',
fill: bgRGB,
'fill-opacity': bgAlpha
});
}
var patterns = el.selectAll(patternTag).data([0]);
patterns.exit().remove();
patterns.enter().append(patternTag).attr(patternAttrs);
});
sel.style('fill', getFullUrl(fullID, gd)).style('fill-opacity', null);
sel.classed('pattern_filled', true);
};
/*
* Make the gradients container and clear out any previous gradients.
* We never collect all the gradients we need in one place,
* so we can't ever remove gradients that have stopped being useful,
* except all at once before a full redraw.
* The upside of this is arbitrary points can share gradient defs
*/
drawing.initGradients = function (gd) {
var fullLayout = gd._fullLayout;
var gradientsGroup = Lib.ensureSingle(fullLayout._defs, 'g', 'gradients');
gradientsGroup.selectAll('linearGradient,radialGradient').remove();
d3.select(gd).selectAll('.gradient_filled').classed('gradient_filled', false);
};
drawing.initPatterns = function (gd) {
var fullLayout = gd._fullLayout;
var patternsGroup = Lib.ensureSingle(fullLayout._defs, 'g', 'patterns');
patternsGroup.selectAll('pattern').remove();
d3.select(gd).selectAll('.pattern_filled').classed('pattern_filled', false);
};
drawing.getPatternAttr = function (mp, i, dflt) {
if (mp && Lib.isArrayOrTypedArray(mp)) {
return i < mp.length ? mp[i] : dflt;
}
return mp;
};
drawing.pointStyle = function (s, trace, gd, pt) {
if (!s.size()) return;
var fns = drawing.makePointStyleFns(trace);
s.each(function (d) {
drawing.singlePointStyle(d, d3.select(this), trace, fns, gd, pt);
});
};
drawing.singlePointStyle = function (d, sel, trace, fns, gd, pt) {
var marker = trace.marker;
var markerLine = marker.line;
if (pt && pt.i >= 0 && d.i === undefined) d.i = pt.i;
sel.style('opacity', fns.selectedOpacityFn ? fns.selectedOpacityFn(d) : d.mo === undefined ? marker.opacity : d.mo);
if (fns.ms2mrc) {
var r;
// handle multi-trace graph edit case
if (d.ms === 'various' || marker.size === 'various') {
r = 3;
} else {
r = fns.ms2mrc(d.ms);
}
// store the calculated size so hover can use it
d.mrc = r;
if (fns.selectedSizeFn) {
r = d.mrc = fns.selectedSizeFn(d);
}
// turn the symbol into a sanitized number
var x = drawing.symbolNumber(d.mx || marker.symbol) || 0;
// save if this marker is open
// because that impacts how to handle colors
d.om = x % 200 >= 100;
var angle = getMarkerAngle(d, trace);
var standoff = getMarkerStandoff(d, trace);
sel.attr('d', makePointPath(x, r, angle, standoff));
}
var perPointGradient = false;
var fillColor, lineColor, lineWidth;
// 'so' is suspected outliers, for box plots
if (d.so) {
lineWidth = markerLine.outlierwidth;
lineColor = markerLine.outliercolor;
fillColor = marker.outliercolor;
} else {
var markerLineWidth = (markerLine || {}).width;
lineWidth = (d.mlw + 1 || markerLineWidth + 1 ||
// TODO: we need the latter for legends... can we get rid of it?
(d.trace ? (d.trace.marker.line || {}).width : 0) + 1) - 1 || 0;
if ('mlc' in d) lineColor = d.mlcc = fns.lineScale(d.mlc);
// weird case: array wasn't long enough to apply to every point
else if (Lib.isArrayOrTypedArray(markerLine.color)) lineColor = Color.defaultLine;else lineColor = markerLine.color;
if (Lib.isArrayOrTypedArray(marker.color)) {
fillColor = Color.defaultLine;
perPointGradient = true;
}
if ('mc' in d) {
fillColor = d.mcc = fns.markerScale(d.mc);
} else {
fillColor = marker.color || marker.colors || 'rgba(0,0,0,0)';
}
if (fns.selectedColorFn) {
fillColor = fns.selectedColorFn(d);
}
}
if (d.om) {
// open markers can't have zero linewidth, default to 1px,
// and use fill color as stroke color
sel.call(Color.stroke, fillColor).style({
'stroke-width': (lineWidth || 1) + 'px',
fill: 'none'
});
} else {
sel.style('stroke-width', (d.isBlank ? 0 : lineWidth) + 'px');
var markerGradient = marker.gradient;
var gradientType = d.mgt;
if (gradientType) perPointGradient = true;else gradientType = markerGradient && markerGradient.type;
// for legend - arrays will propagate through here, but we don't need
// to treat it as per-point.
if (Lib.isArrayOrTypedArray(gradientType)) {
gradientType = gradientType[0];
if (!gradientInfo[gradientType]) gradientType = 0;
}
var markerPattern = marker.pattern;
var patternShape = markerPattern && drawing.getPatternAttr(markerPattern.shape, d.i, '');
if (gradientType && gradientType !== 'none') {
var gradientColor = d.mgc;
if (gradientColor) perPointGradient = true;else gradientColor = markerGradient.color;
var gradientID = trace.uid;
if (perPointGradient) gradientID += '-' + d.i;
drawing.gradient(sel, gd, gradientID, gradientType, [[0, gradientColor], [1, fillColor]], 'fill');
} else if (patternShape) {
var perPointPattern = false;
var fgcolor = markerPattern.fgcolor;
if (!fgcolor && pt && pt.color) {
fgcolor = pt.color;
perPointPattern = true;
}
var patternFGColor = drawing.getPatternAttr(fgcolor, d.i, pt && pt.color || null);
var patternBGColor = drawing.getPatternAttr(markerPattern.bgcolor, d.i, null);
var patternFGOpacity = markerPattern.fgopacity;
var patternSize = drawing.getPatternAttr(markerPattern.size, d.i, 8);
var patternSolidity = drawing.getPatternAttr(markerPattern.solidity, d.i, 0.3);
perPointPattern = perPointPattern || d.mcc || Lib.isArrayOrTypedArray(markerPattern.shape) || Lib.isArrayOrTypedArray(markerPattern.bgcolor) || Lib.isArrayOrTypedArray(markerPattern.fgcolor) || Lib.isArrayOrTypedArray(markerPattern.size) || Lib.isArrayOrTypedArray(markerPattern.solidity);
var patternID = trace.uid;
if (perPointPattern) patternID += '-' + d.i;
drawing.pattern(sel, 'point', gd, patternID, patternShape, patternSize, patternSolidity, d.mcc, markerPattern.fillmode, patternBGColor, patternFGColor, patternFGOpacity);
} else {
Lib.isArrayOrTypedArray(fillColor) ? Color.fill(sel, fillColor[d.i]) : Color.fill(sel, fillColor);
}
if (lineWidth) {
Color.stroke(sel, lineColor);
}
}
};
drawing.makePointStyleFns = function (trace) {
var out = {};
var marker = trace.marker;
// allow array marker and marker line colors to be
// scaled by given max and min to colorscales
out.markerScale = drawing.tryColorscale(marker, '');
out.lineScale = drawing.tryColorscale(marker, 'line');
if (Registry.traceIs(trace, 'symbols')) {
out.ms2mrc = subTypes.isBubble(trace) ? makeBubbleSizeFn(trace) : function () {
return (marker.size || 6) / 2;
};
}
if (trace.selectedpoints) {
Lib.extendFlat(out, drawing.makeSelectedPointStyleFns(trace));
}
return out;
};
drawing.makeSelectedPointStyleFns = function (trace) {
var out = {};
var selectedAttrs = trace.selected || {};
var unselectedAttrs = trace.unselected || {};
var marker = trace.marker || {};
var selectedMarker = selectedAttrs.marker || {};
var unselectedMarker = unselectedAttrs.marker || {};
var mo = marker.opacity;
var smo = selectedMarker.opacity;
var usmo = unselectedMarker.opacity;
var smoIsDefined = smo !== undefined;
var usmoIsDefined = usmo !== undefined;
if (Lib.isArrayOrTypedArray(mo) || smoIsDefined || usmoIsDefined) {
out.selectedOpacityFn = function (d) {
var base = d.mo === undefined ? marker.opacity : d.mo;
if (d.selected) {
return smoIsDefined ? smo : base;
} else {
return usmoIsDefined ? usmo : DESELECTDIM * base;
}
};
}
var mc = marker.color;
var smc = selectedMarker.color;
var usmc = unselectedMarker.color;
if (smc || usmc) {
out.selectedColorFn = function (d) {
var base = d.mcc || mc;
if (d.selected) {
return smc || base;
} else {
return usmc || base;
}
};
}
var ms = marker.size;
var sms = selectedMarker.size;
var usms = unselectedMarker.size;
var smsIsDefined = sms !== undefined;
var usmsIsDefined = usms !== undefined;
if (Registry.traceIs(trace, 'symbols') && (smsIsDefined || usmsIsDefined)) {
out.selectedSizeFn = function (d) {
var base = d.mrc || ms / 2;
if (d.selected) {
return smsIsDefined ? sms / 2 : base;
} else {
return usmsIsDefined ? usms / 2 : base;
}
};
}
return out;
};
drawing.makeSelectedTextStyleFns = function (trace) {
var out = {};
var selectedAttrs = trace.selected || {};
var unselectedAttrs = trace.unselected || {};
var textFont = trace.textfont || {};
var selectedTextFont = selectedAttrs.textfont || {};
var unselectedTextFont = unselectedAttrs.textfont || {};
var tc = textFont.color;
var stc = selectedTextFont.color;
var utc = unselectedTextFont.color;
out.selectedTextColorFn = function (d) {
var base = d.tc || tc;
if (d.selected) {
return stc || base;
} else {
if (utc) return utc;else return stc ? base : Color.addOpacity(base, DESELECTDIM);
}
};
return out;
};
drawing.selectedPointStyle = function (s, trace) {
if (!s.size() || !trace.selectedpoints) return;
var fns = drawing.makeSelectedPointStyleFns(trace);
var marker = trace.marker || {};
var seq = [];
if (fns.selectedOpacityFn) {
seq.push(function (pt, d) {
pt.style('opacity', fns.selectedOpacityFn(d));
});
}
if (fns.selectedColorFn) {
seq.push(function (pt, d) {
Color.fill(pt, fns.selectedColorFn(d));
});
}
if (fns.selectedSizeFn) {
seq.push(function (pt, d) {
var mx = d.mx || marker.symbol || 0;
var mrc2 = fns.selectedSizeFn(d);
pt.attr('d', makePointPath(drawing.symbolNumber(mx), mrc2, getMarkerAngle(d, trace), getMarkerStandoff(d, trace)));
// save for Drawing.selectedTextStyle
d.mrc2 = mrc2;
});
}
if (seq.length) {
s.each(function (d) {
var pt = d3.select(this);
for (var i = 0; i < seq.length; i++) {
seq[i](pt, d);
}
});
}
};
drawing.tryColorscale = function (marker, prefix) {
var cont = prefix ? Lib.nestedProperty(marker, prefix).get() : marker;
if (cont) {
var colorArray = cont.color;
if ((cont.colorscale || cont._colorAx) && Lib.isArrayOrTypedArray(colorArray)) {
return Colorscale.makeColorScaleFuncFromTrace(cont);
}
}
return Lib.identity;
};
var TEXTOFFSETSIGN = {
start: 1,
end: -1,
middle: 0,
bottom: 1,
top: -1
};
function textPointPosition(s, textPosition, fontSize, markerRadius, dontTouchParent) {
var group = d3.select(s.node().parentNode);
var v = textPosition.indexOf('top') !== -1 ? 'top' : textPosition.indexOf('bottom') !== -1 ? 'bottom' : 'middle';
var h = textPosition.indexOf('left') !== -1 ? 'end' : textPosition.indexOf('right') !== -1 ? 'start' : 'middle';
// if markers are shown, offset a little more than
// the nominal marker size
// ie 2/1.6 * nominal, bcs some markers are a bit bigger
var r = markerRadius ? markerRadius / 0.8 + 1 : 0;
var numLines = (svgTextUtils.lineCount(s) - 1) * LINE_SPACING + 1;
var dx = TEXTOFFSETSIGN[h] * r;
var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2;
// fix the overall text group position
s.attr('text-anchor', h);
if (!dontTouchParent) {
group.attr('transform', strTranslate(dx, dy));
}
}
function extracTextFontSize(d, trace) {
var fontSize = d.ts || trace.textfont.size;
return isNumeric(fontSize) && fontSize > 0 ? fontSize : 0;
}
// draw text at points
drawing.textPointStyle = function (s, trace, gd) {
if (!s.size()) return;
var selectedTextColorFn;
if (trace.selectedpoints) {
var fns = drawing.makeSelectedTextStyleFns(trace);
selectedTextColorFn = fns.selectedTextColorFn;
}
var texttemplate = trace.texttemplate;
var fullLayout = gd._fullLayout;
s.each(function (d) {
var p = d3.select(this);
var text = texttemplate ? Lib.extractOption(d, trace, 'txt', 'texttemplate') : Lib.extractOption(d, trace, 'tx', 'text');
if (!text && text !== 0) {
p.remove();
return;
}
if (texttemplate) {
var fn = trace._module.formatLabels;
var labels = fn ? fn(d, trace, fullLayout) : {};
var pointValues = {};
appendArrayPointValue(pointValues, trace, d.i);
var meta = trace._meta || {};
text = Lib.texttemplateString(text, labels, fullLayout._d3locale, pointValues, d, meta);
}
var pos = d.tp || trace.textposition;
var fontSize = extracTextFontSize(d, trace);
var fontColor = selectedTextColorFn ? selectedTextColorFn(d) : d.tc || trace.textfont.color;
p.call(drawing.font, {
family: d.tf || trace.textfont.family,
weight: d.tw || trace.textfont.weight,
style: d.ty || trace.textfont.style,
variant: d.tv || trace.textfont.variant,
textcase: d.tC || trace.textfont.textcase,
lineposition: d.tE || trace.textfont.lineposition,
shadow: d.tS || trace.textfont.shadow,
size: fontSize,
color: fontColor
}).text(text).call(svgTextUtils.convertToTspans, gd).call(textPointPosition, pos, fontSize, d.mrc);
});
};
drawing.selectedTextStyle = function (s, trace) {
if (!s.size() || !trace.selectedpoints) return;
var fns = drawing.makeSelectedTextStyleFns(trace);
s.each(function (d) {
var tx = d3.select(this);
var tc = fns.selectedTextColorFn(d);
var tp = d.tp || trace.textposition;
var fontSize = extracTextFontSize(d, trace);
Color.fill(tx, tc);
var dontTouchParent = Registry.traceIs(trace, 'bar-like');
textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc, dontTouchParent);
});
};
// generalized Catmull-Rom splines, per
// http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
var CatmullRomExp = 0.5;
drawing.smoothopen = function (pts, smoothness) {
if (pts.length < 3) {
return 'M' + pts.join('L');
}
var path = 'M' + pts[0];
var tangents = [];
var i;
for (i = 1; i < pts.length - 1; i++) {
tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
}
path += 'Q' + tangents[0][0] + ' ' + pts[1];
for (i = 2; i < pts.length - 1; i++) {
path += 'C' + tangents[i - 2][1] + ' ' + tangents[i - 1][0] + ' ' + pts[i];
}
path += 'Q' + tangents[pts.length - 3][1] + ' ' + pts[pts.length - 1];
return path;
};
drawing.smoothclosed = function (pts, smoothness) {
if (pts.length < 3) {
return 'M' + pts.join('L') + 'Z';
}
var path = 'M' + pts[0];
var pLast = pts.length - 1;
var tangents = [makeTangent(pts[pLast], pts[0], pts[1], smoothness)];
var i;
for (i = 1; i < pLast; i++) {
tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
}
tangents.push(makeTangent(pts[pLast - 1], pts[pLast], pts[0], smoothness));
for (i = 1; i <= pLast; i++) {
path += 'C' + tangents[i - 1][1] + ' ' + tangents[i][0] + ' ' + pts[i];
}
path += 'C' + tangents[pLast][1] + ' ' + tangents[0][0] + ' ' + pts[0] + 'Z';
return path;
};
var lastDrawnX, lastDrawnY;
function roundEnd(pt, isY, isLastPoint) {
if (isLastPoint) pt = applyBackoff(pt);
return isY ? roundY(pt[1]) : roundX(pt[0]);
}
function roundX(p) {
var v = d3.round(p, 2);
lastDrawnX = v;
return v;
}
function roundY(p) {
var v = d3.round(p, 2);
lastDrawnY = v;
return v;
}
function makeTangent(prevpt, thispt, nextpt, smoothness) {
var d1x = prevpt[0] - thispt[0];
var d1y = prevpt[1] - thispt[1];
var d2x = nextpt[0] - thispt[0];
var d2y = nextpt[1] - thispt[1];
var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
var denom1 = 3 * d2a * (d1a + d2a);
var denom2 = 3 * d1a * (d1a + d2a);
return [[roundX(thispt[0] + (denom1 && numx / denom1)), roundY(thispt[1] + (denom1 && numy / denom1))], [roundX(thispt[0] - (denom2 && numx / denom2)), roundY(thispt[1] - (denom2 && numy / denom2))]];
}
// step paths - returns a generator function for paths
// with the given step shape
var STEPPATH = {
hv: function (p0, p1, isLastPoint) {
return 'H' + roundX(p1[0]) + 'V' + roundEnd(p1, 1, isLastPoint);
},
vh: function (p0, p1, isLastPoint) {
return 'V' + roundY(p1[1]) + 'H' + roundEnd(p1, 0, isLastPoint);
},
hvh: function (p0, p1, isLastPoint) {
return 'H' + roundX((p0[0] + p1[0]) / 2) + 'V' + roundY(p1[1]) + 'H' + roundEnd(p1, 0, isLastPoint);
},
vhv: function (p0, p1, isLastPoint) {
return 'V' + roundY((p0[1] + p1[1]) / 2) + 'H' + roundX(p1[0]) + 'V' + roundEnd(p1, 1, isLastPoint);
}
};
var STEPLINEAR = function (p0, p1, isLastPoint) {
return 'L' + roundEnd(p1, 0, isLastPoint) + ',' + roundEnd(p1, 1, isLastPoint);
};
drawing.steps = function (shape) {
var onestep = STEPPATH[shape] || STEPLINEAR;
return function (pts) {
var path = 'M' + roundX(pts[0][0]) + ',' + roundY(pts[0][1]);
var len = pts.length;
for (var i = 1; i < len; i++) {
path += onestep(pts[i - 1], pts[i], i === len - 1);
}
return path;
};
};
function applyBackoff(pt, start) {
var backoff = pt.backoff;
var trace = pt.trace;
var d = pt.d;
var i = pt.i;
if (backoff && trace && trace.marker && trace.marker.angle % 360 === 0 && trace.line && trace.line.shape !== 'spline') {
var arrayBackoff = Lib.isArrayOrTypedArray(backoff);
var end = pt;
var x1 = start ? start[0] : lastDrawnX || 0;
var y1 = start ? start[1] : lastDrawnY || 0;
var x2 = end[0];
var y2 = end[1];
var dx = x2 - x1;
var dy = y2 - y1;
var t = Math.atan2(dy, dx);
var b = arrayBackoff ? backoff[i] : backoff;
if (b === 'auto') {
var endI = end.i;
if (trace.type === 'scatter') endI--; // Why we need this hack?
var endMarker = end.marker;
var endMarkerSymbol = endMarker.symbol;
if (Lib.isArrayOrTypedArray(endMarkerSymbol)) endMarkerSymbol = endMarkerSymbol[endI];
var endMarkerSize = endMarker.size;
if (Lib.isArrayOrTypedArray(endMarkerSize)) endMarkerSize = endMarkerSize[endI];
b = endMarker ? drawing.symbolBackOffs[drawing.symbolNumber(endMarkerSymbol)] * endMarkerSize : 0;
b += drawing.getMarkerStandoff(d[endI], trace) || 0;
}
var x = x2 - b * Math.cos(t);
var y = y2 - b * Math.sin(t);
if ((x <= x2 && x >= x1 || x >= x2 && x <= x1) && (y <= y2 && y >= y1 || y >= y2 && y <= y1)) {
pt = [x, y];
}
}
return pt;
}
drawing.applyBackoff = applyBackoff;
// off-screen svg render testing element, shared by the whole page
// uses the id 'js-plotly-tester' and stores it in drawing.tester
drawing.makeTester = function () {
var tester = Lib.ensureSingleById(d3.select('body'), 'svg', 'js-plotly-tester', function (s) {
s.attr(xmlnsNamespaces.svgAttrs).style({
position: 'absolute',
left: '-10000px',
top: '-10000px',
width: '9000px',
height: '9000px',
'z-index': '1'
});
});
// browsers differ on how they describe the bounding rect of
// the svg if its contents spill over... so make a 1x1px
// reference point we can measure off of.
var testref = Lib.ensureSingle(tester, 'path', 'js-reference-point', function (s) {
s.attr('d', 'M0,0H1V1H0Z').style({
'stroke-width': 0,
fill: 'black'
});
});
drawing.tester = tester;
drawing.testref = testref;
};
/*
* use our offscreen tester to get a clientRect for an element,
* in a reference frame where it isn't translated (or transformed) and
* its anchor point is at (0,0)
* always returns a copy of the bbox, so the caller can modify it safely
*
* @param {SVGElement} node: the element to measure. If possible this should be
* a or MathJax element that's already passed through
* `convertToTspans` because in that case we can cache the results, but it's
* possible to pass in any svg element.
*
* @param {boolean} inTester: is this element already in `drawing.tester`?
* If you are measuring a dummy element, rather than one you really intend
* to use on the plot, making it in `drawing.tester` in the first place
* allows us to test faster because it cuts out cloning and appending it.
*
* @param {string} hash: for internal use only, if we already know the cache key
* for this element beforehand.
*
* @return {object}: a plain object containing the width, height, left, right,
* top, and bottom of `node`
*/
drawing.savedBBoxes = {};
var savedBBoxesCount = 0;
var maxSavedBBoxes = 10000;
drawing.bBox = function (node, inTester, hash) {
/*
* Cache elements we've already measured so we don't have to
* remeasure the same thing many times
* We have a few bBox callers though who pass a node larger than
* a or a MathJax , such as an axis group containing many labels.
* These will not generate a hash (unless we figure out an appropriate
* hash key for them) and thus we will not hash them.
*/
if (!hash) hash = nodeHash(node);
var out;
if (hash) {
out = drawing.savedBBoxes[hash];
if (out) return Lib.extendFlat({}, out);
} else if (node.childNodes.length === 1) {
/*
* If we have only one child element, which is itself hashable, make
* a new hash from this element plus its x,y,transform
* These bounding boxes *include* x,y,transform - mostly for use by
* callers trying to avoid overlaps (ie titles)
*/
var innerNode = node.childNodes[0];
hash = nodeHash(innerNode);
if (hash) {
var x = +innerNode.getAttribute('x') || 0;
var y = +innerNode.getAttribute('y') || 0;
var transform = innerNode.getAttribute('transform');
if (!transform) {
// in this case, just varying x and y, don't bother caching
// the final bBox because the alteration is quick.
var innerBB = drawing.bBox(innerNode, false, hash);
if (x) {
innerBB.left += x;
innerBB.right += x;
}
if (y) {
innerBB.top += y;
innerBB.bottom += y;
}
return innerBB;
}
/*
* else we have a transform - rather than make a complicated
* (and error-prone and probably slow) transform parser/calculator,
* just continue on calculating the boundingClientRect of the group
* and use the new composite hash to cache it.
* That said, `innerNode.transform.baseVal` is an array of
* `SVGTransform` objects, that *do* seem to have a nice matrix
* multiplication interface that we could use to avoid making
* another getBoundingClientRect call...
*/
hash += '~' + x + '~' + y + '~' + transform;
out = drawing.savedBBoxes[hash];
if (out) return Lib.extendFlat({}, out);
}
}
var testNode, tester;
if (inTester) {
testNode = node;
} else {
tester = drawing.tester.node();
// copy the node to test into the tester
testNode = node.cloneNode(true);
tester.appendChild(testNode);
}
// standardize its position (and newline tspans if any)
d3.select(testNode).attr('transform', null).call(svgTextUtils.positionText, 0, 0);
var testRect = testNode.getBoundingClientRect();
var refRect = drawing.testref.node().getBoundingClientRect();
if (!inTester) tester.removeChild(testNode);
var bb = {
height: testRect.height,
width: testRect.width,
left: testRect.left - refRect.left,
top: testRect.top - refRect.top,
right: testRect.right - refRect.left,
bottom: testRect.bottom - refRect.top
};
// make sure we don't have too many saved boxes,
// or a long session could overload on memory
// by saving boxes for long-gone elements
if (savedBBoxesCount >= maxSavedBBoxes) {
drawing.savedBBoxes = {};
savedBBoxesCount = 0;
}
// cache this bbox
if (hash) drawing.savedBBoxes[hash] = bb;
savedBBoxesCount++;
return Lib.extendFlat({}, bb);
};
// capture everything about a node (at least in our usage) that
// impacts its bounding box, given that bBox clears x, y, and transform
function nodeHash(node) {
var inputText = node.getAttribute('data-unformatted');
if (inputText === null) return;
return inputText + node.getAttribute('data-math') + node.getAttribute('text-anchor') + node.getAttribute('style');
}
/**
* Set clipPath URL in a way that work for all situations.
*
* In details, graphs on pages with HTML tags need to prepend
* the clip path ids with the page's base url EXCEPT during toImage exports.
*
* @param {d3 selection} s : node to add clip-path attribute
* @param {string} localId : local clip-path (w/o base url) id
* @param {DOM element || object} gd
* - context._baseUrl {string}
* - context._exportedPlot {boolean}
*/
drawing.setClipUrl = function (s, localId, gd) {
s.attr('clip-path', getFullUrl(localId, gd));
};
function getFullUrl(localId, gd) {
if (!localId) return null;
var context = gd._context;
var baseUrl = context._exportedPlot ? '' : context._baseUrl || '';
return baseUrl ? 'url(\'' + baseUrl + '#' + localId + '\')' : 'url(#' + localId + ')';
}
drawing.getTranslate = function (element) {
// Note the separator [^\d] between x and y in this regex
// We generally use ',' but IE will convert it to ' '
var re = /.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/;
var getter = element.attr ? 'attr' : 'getAttribute';
var transform = element[getter]('transform') || '';
var translate = transform.replace(re, function (match, p1, p2) {
return [p1, p2].join(' ');
}).split(' ');
return {
x: +translate[0] || 0,
y: +translate[1] || 0
};
};
drawing.setTranslate = function (element, x, y) {
var re = /(\btranslate\(.*?\);?)/;
var getter = element.attr ? 'attr' : 'getAttribute';
var setter = element.attr ? 'attr' : 'setAttribute';
var transform = element[getter]('transform') || '';
x = x || 0;
y = y || 0;
transform = transform.replace(re, '').trim();
transform += strTranslate(x, y);
transform = transform.trim();
element[setter]('transform', transform);
return transform;
};
drawing.getScale = function (element) {
var re = /.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/;
var getter = element.attr ? 'attr' : 'getAttribute';
var transform = element[getter]('transform') || '';
var translate = transform.replace(re, function (match, p1, p2) {
return [p1, p2].join(' ');
}).split(' ');
return {
x: +translate[0] || 1,
y: +translate[1] || 1
};
};
drawing.setScale = function (element, x, y) {
var re = /(\bscale\(.*?\);?)/;
var getter = element.attr ? 'attr' : 'getAttribute';
var setter = element.attr ? 'attr' : 'setAttribute';
var transform = element[getter]('transform') || '';
x = x || 1;
y = y || 1;
transform = transform.replace(re, '').trim();
transform += 'scale(' + x + ',' + y + ')';
transform = transform.trim();
element[setter]('transform', transform);
return transform;
};
var SCALE_RE = /\s*sc.*/;
drawing.setPointGroupScale = function (selection, xScale, yScale) {
xScale = xScale || 1;
yScale = yScale || 1;
if (!selection) return;
// The same scale transform for every point:
var scale = xScale === 1 && yScale === 1 ? '' : 'scale(' + xScale + ',' + yScale + ')';
selection.each(function () {
var t = (this.getAttribute('transform') || '').replace(SCALE_RE, '');
t += scale;
t = t.trim();
this.setAttribute('transform', t);
});
};
var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/;
drawing.setTextPointsScale = function (selection, xScale, yScale) {
if (!selection) return;
selection.each(function () {
var transforms;
var el = d3.select(this);
var text = el.select('text');
if (!text.node()) return;
var x = parseFloat(text.attr('x') || 0);
var y = parseFloat(text.attr('y') || 0);
var existingTransform = (el.attr('transform') || '').match(TEXT_POINT_LAST_TRANSLATION_RE);
if (xScale === 1 && yScale === 1) {
transforms = [];
} else {
transforms = [strTranslate(x, y), 'scale(' + xScale + ',' + yScale + ')', strTranslate(-x, -y)];
}
if (existingTransform) {
transforms.push(existingTransform);
}
el.attr('transform', transforms.join(''));
});
};
function getMarkerStandoff(d, trace) {
var standoff;
if (d) standoff = d.mf;
if (standoff === undefined) {
standoff = trace.marker ? trace.marker.standoff || 0 : 0;
}
if (!trace._geo && !trace._xA) {
// case of legends
return -standoff;
}
return standoff;
}
drawing.getMarkerStandoff = getMarkerStandoff;
var atan2 = Math.atan2;
var cos = Math.cos;
var sin = Math.sin;
function rotate(t, xy) {
var x = xy[0];
var y = xy[1];
return [x * cos(t) - y * sin(t), x * sin(t) + y * cos(t)];
}
var previousLon;
var previousLat;
var previousX;
var previousY;
var previousI;
var previousTraceUid;
function getMarkerAngle(d, trace) {
var angle = d.ma;
if (angle === undefined) {
angle = trace.marker.angle;
if (!angle || Lib.isArrayOrTypedArray(angle)) {
angle = 0;
}
}
var x, y;
var ref = trace.marker.angleref;
if (ref === 'previous' || ref === 'north') {
if (trace._geo) {
var p = trace._geo.project(d.lonlat);
x = p[0];
y = p[1];
} else {
var xa = trace._xA;
var ya = trace._yA;
if (xa && ya) {
x = xa.c2p(d.x);
y = ya.c2p(d.y);
} else {
// case of legends
return 90;
}
}
if (trace._geo) {
var lon = d.lonlat[0];
var lat = d.lonlat[1];
var north = trace._geo.project([lon, lat + 1e-5 // epsilon
]);
var east = trace._geo.project([lon + 1e-5,
// epsilon
lat]);
var u = atan2(east[1] - y, east[0] - x);
var v = atan2(north[1] - y, north[0] - x);
var t;
if (ref === 'north') {
t = angle / 180 * Math.PI;
// To use counter-clockwise angles i.e.
// East: 90, West: -90
// to facilitate wind visualisations
// in future we should use t = -t here.
} else if (ref === 'previous') {
var lon1 = lon / 180 * Math.PI;
var lat1 = lat / 180 * Math.PI;
var lon2 = previousLon / 180 * Math.PI;
var lat2 = previousLat / 180 * Math.PI;
var dLon = lon2 - lon1;
var deltaY = cos(lat2) * sin(dLon);
var deltaX = sin(lat2) * cos(lat1) - cos(lat2) * sin(lat1) * cos(dLon);
t = -atan2(deltaY, deltaX) - Math.PI;
previousLon = lon;
previousLat = lat;
}
var A = rotate(u, [cos(t), 0]);
var B = rotate(v, [sin(t), 0]);
angle = atan2(A[1] + B[1], A[0] + B[0]) / Math.PI * 180;
if (ref === 'previous' && !(previousTraceUid === trace.uid && d.i === previousI + 1)) {
angle = null;
}
}
if (ref === 'previous' && !trace._geo) {
if (previousTraceUid === trace.uid && d.i === previousI + 1 && isNumeric(x) && isNumeric(y)) {
var dX = x - previousX;
var dY = y - previousY;
var shape = trace.line ? trace.line.shape || '' : '';
var lastShapeChar = shape.slice(shape.length - 1);
if (lastShapeChar === 'h') dY = 0;
if (lastShapeChar === 'v') dX = 0;
angle += atan2(dY, dX) / Math.PI * 180 + 90;
} else {
angle = null;
}
}
}
previousX = x;
previousY = y;
previousI = d.i;
previousTraceUid = trace.uid;
return angle;
}
drawing.getMarkerAngle = getMarkerAngle;
/***/ }),
/***/ 71984:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var parseSvgPath = __webpack_require__(21984);
var round = (__webpack_require__(33428).round);
/** Marker symbol definitions
* users can specify markers either by number or name
* add 100 (or '-open') and you get an open marker
* open markers have no fill and use line color as the stroke color
* add 200 (or '-dot') and you get a dot in the middle
* add both and you get both
*/
var emptyPath = 'M0,0Z';
var sqrt2 = Math.sqrt(2);
var sqrt3 = Math.sqrt(3);
var PI = Math.PI;
var cos = Math.cos;
var sin = Math.sin;
module.exports = {
circle: {
n: 0,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = round(r, 2);
var circle = 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
return standoff ? align(angle, standoff, circle) : circle;
}
},
square: {
n: 1,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = round(r, 2);
return align(angle, standoff, 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z');
}
},
diamond: {
n: 2,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rd = round(r * 1.3, 2);
return align(angle, standoff, 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z');
}
},
cross: {
n: 3,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rc = round(r * 0.4, 2);
var rc2 = round(r * 1.2, 2);
return align(angle, standoff, 'M' + rc2 + ',' + rc + 'H' + rc + 'V' + rc2 + 'H-' + rc + 'V' + rc + 'H-' + rc2 + 'V-' + rc + 'H-' + rc + 'V-' + rc2 + 'H' + rc + 'V-' + rc + 'H' + rc2 + 'Z');
}
},
x: {
n: 4,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r * 0.8 / sqrt2, 2);
var ne = 'l' + rx + ',' + rx;
var se = 'l' + rx + ',-' + rx;
var sw = 'l-' + rx + ',-' + rx;
var nw = 'l-' + rx + ',' + rx;
return align(angle, standoff, 'M0,' + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + 'Z');
}
},
'triangle-up': {
n: 5,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rt = round(r * 2 / sqrt3, 2);
var r2 = round(r / 2, 2);
var rs = round(r, 2);
return align(angle, standoff, 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z');
}
},
'triangle-down': {
n: 6,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rt = round(r * 2 / sqrt3, 2);
var r2 = round(r / 2, 2);
var rs = round(r, 2);
return align(angle, standoff, 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z');
}
},
'triangle-left': {
n: 7,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rt = round(r * 2 / sqrt3, 2);
var r2 = round(r / 2, 2);
var rs = round(r, 2);
return align(angle, standoff, 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z');
}
},
'triangle-right': {
n: 8,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rt = round(r * 2 / sqrt3, 2);
var r2 = round(r / 2, 2);
var rs = round(r, 2);
return align(angle, standoff, 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z');
}
},
'triangle-ne': {
n: 9,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var r1 = round(r * 0.6, 2);
var r2 = round(r * 1.2, 2);
return align(angle, standoff, 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z');
}
},
'triangle-se': {
n: 10,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var r1 = round(r * 0.6, 2);
var r2 = round(r * 1.2, 2);
return align(angle, standoff, 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z');
}
},
'triangle-sw': {
n: 11,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var r1 = round(r * 0.6, 2);
var r2 = round(r * 1.2, 2);
return align(angle, standoff, 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z');
}
},
'triangle-nw': {
n: 12,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var r1 = round(r * 0.6, 2);
var r2 = round(r * 1.2, 2);
return align(angle, standoff, 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z');
}
},
pentagon: {
n: 13,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var x1 = round(r * 0.951, 2);
var x2 = round(r * 0.588, 2);
var y0 = round(-r, 2);
var y1 = round(r * -0.309, 2);
var y2 = round(r * 0.809, 2);
return align(angle, standoff, 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 + 'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z');
}
},
hexagon: {
n: 14,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var y0 = round(r, 2);
var y1 = round(r / 2, 2);
var x = round(r * sqrt3 / 2, 2);
return align(angle, standoff, 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 + 'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z');
}
},
hexagon2: {
n: 15,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var x0 = round(r, 2);
var x1 = round(r / 2, 2);
var y = round(r * sqrt3 / 2, 2);
return align(angle, standoff, 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 + ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z');
}
},
octagon: {
n: 16,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var a = round(r * 0.924, 2);
var b = round(r * 0.383, 2);
return align(angle, standoff, 'M-' + b + ',-' + a + 'H' + b + 'L' + a + ',-' + b + 'V' + b + 'L' + b + ',' + a + 'H-' + b + 'L-' + a + ',' + b + 'V-' + b + 'Z');
}
},
star: {
n: 17,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = r * 1.4;
var x1 = round(rs * 0.225, 2);
var x2 = round(rs * 0.951, 2);
var x3 = round(rs * 0.363, 2);
var x4 = round(rs * 0.588, 2);
var y0 = round(-rs, 2);
var y1 = round(rs * -0.309, 2);
var y3 = round(rs * 0.118, 2);
var y4 = round(rs * 0.809, 2);
var y5 = round(rs * 0.382, 2);
return align(angle, standoff, 'M' + x1 + ',' + y1 + 'H' + x2 + 'L' + x3 + ',' + y3 + 'L' + x4 + ',' + y4 + 'L0,' + y5 + 'L-' + x4 + ',' + y4 + 'L-' + x3 + ',' + y3 + 'L-' + x2 + ',' + y1 + 'H-' + x1 + 'L0,' + y0 + 'Z');
}
},
hexagram: {
n: 18,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var y = round(r * 0.66, 2);
var x1 = round(r * 0.38, 2);
var x2 = round(r * 0.76, 2);
return align(angle, standoff, 'M-' + x2 + ',0l-' + x1 + ',-' + y + 'h' + x2 + 'l' + x1 + ',-' + y + 'l' + x1 + ',' + y + 'h' + x2 + 'l-' + x1 + ',' + y + 'l' + x1 + ',' + y + 'h-' + x2 + 'l-' + x1 + ',' + y + 'l-' + x1 + ',-' + y + 'h-' + x2 + 'Z');
}
},
'star-triangle-up': {
n: 19,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var x = round(r * sqrt3 * 0.8, 2);
var y1 = round(r * 0.8, 2);
var y2 = round(r * 1.6, 2);
var rc = round(r * 4, 2);
var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
return align(angle, standoff, 'M-' + x + ',' + y1 + aPart + x + ',' + y1 + aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z');
}
},
'star-triangle-down': {
n: 20,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var x = round(r * sqrt3 * 0.8, 2);
var y1 = round(r * 0.8, 2);
var y2 = round(r * 1.6, 2);
var rc = round(r * 4, 2);
var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
return align(angle, standoff, 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 + aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z');
}
},
'star-square': {
n: 21,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rp = round(r * 1.1, 2);
var rc = round(r * 2, 2);
var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
return align(angle, standoff, 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp + aPart + rp + ',' + rp + aPart + rp + ',-' + rp + aPart + '-' + rp + ',-' + rp + 'Z');
}
},
'star-diamond': {
n: 22,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rp = round(r * 1.4, 2);
var rc = round(r * 1.9, 2);
var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
return align(angle, standoff, 'M-' + rp + ',0' + aPart + '0,' + rp + aPart + rp + ',0' + aPart + '0,-' + rp + aPart + '-' + rp + ',0' + 'Z');
}
},
'diamond-tall': {
n: 23,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var x = round(r * 0.7, 2);
var y = round(r * 1.4, 2);
return align(angle, standoff, 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z');
}
},
'diamond-wide': {
n: 24,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var x = round(r * 1.4, 2);
var y = round(r * 0.7, 2);
return align(angle, standoff, 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z');
}
},
hourglass: {
n: 25,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = round(r, 2);
return align(angle, standoff, 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z');
},
noDot: true
},
bowtie: {
n: 26,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = round(r, 2);
return align(angle, standoff, 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z');
},
noDot: true
},
'circle-cross': {
n: 27,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = round(r, 2);
return align(angle, standoff, 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs + 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z');
},
needLine: true,
noDot: true
},
'circle-x': {
n: 28,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = round(r, 2);
var rc = round(r / sqrt2, 2);
return align(angle, standoff, 'M' + rc + ',' + rc + 'L-' + rc + ',-' + rc + 'M' + rc + ',-' + rc + 'L-' + rc + ',' + rc + 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z');
},
needLine: true,
noDot: true
},
'square-cross': {
n: 29,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = round(r, 2);
return align(angle, standoff, 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs + 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z');
},
needLine: true,
noDot: true
},
'square-x': {
n: 30,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rs = round(r, 2);
return align(angle, standoff, 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs + 'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs + 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z');
},
needLine: true,
noDot: true
},
'diamond-cross': {
n: 31,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rd = round(r * 1.3, 2);
return align(angle, standoff, 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' + 'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd);
},
needLine: true,
noDot: true
},
'diamond-x': {
n: 32,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rd = round(r * 1.3, 2);
var r2 = round(r * 0.65, 2);
return align(angle, standoff, 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' + 'M-' + r2 + ',-' + r2 + 'L' + r2 + ',' + r2 + 'M-' + r2 + ',' + r2 + 'L' + r2 + ',-' + r2);
},
needLine: true,
noDot: true
},
'cross-thin': {
n: 33,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rc = round(r * 1.4, 2);
return align(angle, standoff, 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc);
},
needLine: true,
noDot: true,
noFill: true
},
'x-thin': {
n: 34,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r, 2);
return align(angle, standoff, 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx + 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx);
},
needLine: true,
noDot: true,
noFill: true
},
asterisk: {
n: 35,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rc = round(r * 1.2, 2);
var rs = round(r * 0.85, 2);
return align(angle, standoff, 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc + 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs + 'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs);
},
needLine: true,
noDot: true,
noFill: true
},
hash: {
n: 36,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var r1 = round(r / 2, 2);
var r2 = round(r, 2);
return align(angle, standoff, 'M' + r1 + ',' + r2 + 'V-' + r2 + 'M' + (r1 - r2) + ',-' + r2 + 'V' + r2 + 'M' + r2 + ',' + r1 + 'H-' + r2 + 'M-' + r2 + ',' + (r1 - r2) + 'H' + r2);
},
needLine: true,
noFill: true
},
'y-up': {
n: 37,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var x = round(r * 1.2, 2);
var y0 = round(r * 1.6, 2);
var y1 = round(r * 0.8, 2);
return align(angle, standoff, 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0');
},
needLine: true,
noDot: true,
noFill: true
},
'y-down': {
n: 38,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var x = round(r * 1.2, 2);
var y0 = round(r * 1.6, 2);
var y1 = round(r * 0.8, 2);
return align(angle, standoff, 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0');
},
needLine: true,
noDot: true,
noFill: true
},
'y-left': {
n: 39,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var y = round(r * 1.2, 2);
var x0 = round(r * 1.6, 2);
var x1 = round(r * 0.8, 2);
return align(angle, standoff, 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0');
},
needLine: true,
noDot: true,
noFill: true
},
'y-right': {
n: 40,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var y = round(r * 1.2, 2);
var x0 = round(r * 1.6, 2);
var x1 = round(r * 0.8, 2);
return align(angle, standoff, 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0');
},
needLine: true,
noDot: true,
noFill: true
},
'line-ew': {
n: 41,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rc = round(r * 1.4, 2);
return align(angle, standoff, 'M' + rc + ',0H-' + rc);
},
needLine: true,
noDot: true,
noFill: true
},
'line-ns': {
n: 42,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rc = round(r * 1.4, 2);
return align(angle, standoff, 'M0,' + rc + 'V-' + rc);
},
needLine: true,
noDot: true,
noFill: true
},
'line-ne': {
n: 43,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r, 2);
return align(angle, standoff, 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx);
},
needLine: true,
noDot: true,
noFill: true
},
'line-nw': {
n: 44,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r, 2);
return align(angle, standoff, 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx);
},
needLine: true,
noDot: true,
noFill: true
},
'arrow-up': {
n: 45,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r, 2);
var ry = round(r * 2, 2);
return align(angle, standoff, 'M0,0L-' + rx + ',' + ry + 'H' + rx + 'Z');
},
backoff: 1,
noDot: true
},
'arrow-down': {
n: 46,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r, 2);
var ry = round(r * 2, 2);
return align(angle, standoff, 'M0,0L-' + rx + ',-' + ry + 'H' + rx + 'Z');
},
noDot: true
},
'arrow-left': {
n: 47,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r * 2, 2);
var ry = round(r, 2);
return align(angle, standoff, 'M0,0L' + rx + ',-' + ry + 'V' + ry + 'Z');
},
noDot: true
},
'arrow-right': {
n: 48,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r * 2, 2);
var ry = round(r, 2);
return align(angle, standoff, 'M0,0L-' + rx + ',-' + ry + 'V' + ry + 'Z');
},
noDot: true
},
'arrow-bar-up': {
n: 49,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r, 2);
var ry = round(r * 2, 2);
return align(angle, standoff, 'M-' + rx + ',0H' + rx + 'M0,0L-' + rx + ',' + ry + 'H' + rx + 'Z');
},
backoff: 1,
needLine: true,
noDot: true
},
'arrow-bar-down': {
n: 50,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r, 2);
var ry = round(r * 2, 2);
return align(angle, standoff, 'M-' + rx + ',0H' + rx + 'M0,0L-' + rx + ',-' + ry + 'H' + rx + 'Z');
},
needLine: true,
noDot: true
},
'arrow-bar-left': {
n: 51,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r * 2, 2);
var ry = round(r, 2);
return align(angle, standoff, 'M0,-' + ry + 'V' + ry + 'M0,0L' + rx + ',-' + ry + 'V' + ry + 'Z');
},
needLine: true,
noDot: true
},
'arrow-bar-right': {
n: 52,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var rx = round(r * 2, 2);
var ry = round(r, 2);
return align(angle, standoff, 'M0,-' + ry + 'V' + ry + 'M0,0L-' + rx + ',-' + ry + 'V' + ry + 'Z');
},
needLine: true,
noDot: true
},
arrow: {
n: 53,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var headAngle = PI / 2.5; // 36 degrees - golden ratio
var x = 2 * r * cos(headAngle);
var y = 2 * r * sin(headAngle);
return align(angle, standoff, 'M0,0' + 'L' + -x + ',' + y + 'L' + x + ',' + y + 'Z');
},
backoff: 0.9,
noDot: true
},
'arrow-wide': {
n: 54,
f: function (r, angle, standoff) {
if (skipAngle(angle)) return emptyPath;
var headAngle = PI / 4; // 90 degrees
var x = 2 * r * cos(headAngle);
var y = 2 * r * sin(headAngle);
return align(angle, standoff, 'M0,0' + 'L' + -x + ',' + y + 'A ' + 2 * r + ',' + 2 * r + ' 0 0 1 ' + x + ',' + y + 'Z');
},
backoff: 0.4,
noDot: true
}
};
function skipAngle(angle) {
return angle === null;
}
var lastPathIn, lastPathOut;
var lastAngle, lastStandoff;
function align(angle, standoff, path) {
if ((!angle || angle % 360 === 0) && !standoff) return path;
if (lastAngle === angle && lastStandoff === standoff && lastPathIn === path) return lastPathOut;
lastAngle = angle;
lastStandoff = standoff;
lastPathIn = path;
function rotate(t, xy) {
var cosT = cos(t);
var sinT = sin(t);
var x = xy[0];
var y = xy[1] + (standoff || 0);
return [x * cosT - y * sinT, x * sinT + y * cosT];
}
var t = angle / 180 * PI;
var x = 0;
var y = 0;
var cmd = parseSvgPath(path);
var str = '';
for (var i = 0; i < cmd.length; i++) {
var cmdI = cmd[i];
var op = cmdI[0];
var x0 = x;
var y0 = y;
if (op === 'M' || op === 'L') {
x = +cmdI[1];
y = +cmdI[2];
} else if (op === 'm' || op === 'l') {
x += +cmdI[1];
y += +cmdI[2];
} else if (op === 'H') {
x = +cmdI[1];
} else if (op === 'h') {
x += +cmdI[1];
} else if (op === 'V') {
y = +cmdI[1];
} else if (op === 'v') {
y += +cmdI[1];
} else if (op === 'A') {
x = +cmdI[1];
y = +cmdI[2];
var E = rotate(t, [+cmdI[6], +cmdI[7]]);
cmdI[6] = E[0];
cmdI[7] = E[1];
cmdI[3] = +cmdI[3] + angle;
}
// change from H, V, h, v to L or l
if (op === 'H' || op === 'V') op = 'L';
if (op === 'h' || op === 'v') op = 'l';
if (op === 'm' || op === 'l') {
x -= x0;
y -= y0;
}
var B = rotate(t, [x, y]);
if (op === 'H' || op === 'V') op = 'L';
if (op === 'M' || op === 'L' || op === 'm' || op === 'l') {
cmdI[1] = B[0];
cmdI[2] = B[1];
}
cmdI[0] = op;
str += cmdI[0] + cmdI.slice(1).join(',');
}
lastPathOut = str;
return str;
}
/***/ }),
/***/ 97644:
/***/ (function(module) {
"use strict";
module.exports = {
visible: {
valType: 'boolean',
editType: 'calc'
},
type: {
valType: 'enumerated',
values: ['percent', 'constant', 'sqrt', 'data'],
editType: 'calc'
},
symmetric: {
valType: 'boolean',
editType: 'calc'
},
array: {
valType: 'data_array',
editType: 'calc'
},
arrayminus: {
valType: 'data_array',
editType: 'calc'
},
value: {
valType: 'number',
min: 0,
dflt: 10,
editType: 'calc'
},
valueminus: {
valType: 'number',
min: 0,
dflt: 10,
editType: 'calc'
},
traceref: {
valType: 'integer',
min: 0,
dflt: 0,
editType: 'style'
},
tracerefminus: {
valType: 'integer',
min: 0,
dflt: 0,
editType: 'style'
},
copy_ystyle: {
valType: 'boolean',
editType: 'plot'
},
copy_zstyle: {
valType: 'boolean',
editType: 'style'
},
color: {
valType: 'color',
editType: 'style'
},
thickness: {
valType: 'number',
min: 0,
dflt: 2,
editType: 'style'
},
width: {
valType: 'number',
min: 0,
editType: 'plot'
},
editType: 'calc',
_deprecated: {
opacity: {
valType: 'number',
editType: 'style'
}
}
};
/***/ }),
/***/ 14880:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Registry = __webpack_require__(24040);
var Axes = __webpack_require__(54460);
var Lib = __webpack_require__(3400);
var makeComputeError = __webpack_require__(93792);
module.exports = function calc(gd) {
var calcdata = gd.calcdata;
for (var i = 0; i < calcdata.length; i++) {
var calcTrace = calcdata[i];
var trace = calcTrace[0].trace;
if (trace.visible === true && Registry.traceIs(trace, 'errorBarsOK')) {
var xa = Axes.getFromId(gd, trace.xaxis);
var ya = Axes.getFromId(gd, trace.yaxis);
calcOneAxis(calcTrace, trace, xa, 'x');
calcOneAxis(calcTrace, trace, ya, 'y');
}
}
};
function calcOneAxis(calcTrace, trace, axis, coord) {
var opts = trace['error_' + coord] || {};
var isVisible = opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1;
var vals = [];
if (!isVisible) return;
var computeError = makeComputeError(opts);
for (var i = 0; i < calcTrace.length; i++) {
var calcPt = calcTrace[i];
var iIn = calcPt.i;
// for types that don't include `i` in each calcdata point
if (iIn === undefined) iIn = i;
// for stacked area inserted points
// TODO: errorbars have been tested cursorily with stacked area,
// but not thoroughly. It's not even really clear what you want to do:
// Should it just be calculated based on that trace's size data?
// Should you add errors from below in quadrature?
// And what about normalization, where in principle the errors shrink
// again when you get up to the top end?
// One option would be to forbid errorbars with stacking until we
// decide how to handle these questions.
else if (iIn === null) continue;
var calcCoord = calcPt[coord];
if (!isNumeric(axis.c2l(calcCoord))) continue;
var errors = computeError(calcCoord, iIn);
if (isNumeric(errors[0]) && isNumeric(errors[1])) {
var shoe = calcPt[coord + 's'] = calcCoord - errors[0];
var hat = calcPt[coord + 'h'] = calcCoord + errors[1];
vals.push(shoe, hat);
}
}
var axId = axis._id;
var baseExtremes = trace._extremes[axId];
var extremes = Axes.findExtremes(axis, vals, Lib.extendFlat({
tozero: baseExtremes.opts.tozero
}, {
padded: true
}));
baseExtremes.min = baseExtremes.min.concat(extremes.min);
baseExtremes.max = baseExtremes.max.concat(extremes.max);
}
/***/ }),
/***/ 93792:
/***/ (function(module) {
"use strict";
/**
* Error bar computing function generator
*
* N.B. The generated function does not clean the dataPt entries. Non-numeric
* entries result in undefined error magnitudes.
*
* @param {object} opts error bar attributes
*
* @return {function} :
* @param {numeric} dataPt data point from where to compute the error magnitude
* @param {number} index index of dataPt in its corresponding data array
* @return {array}
* - error[0] : error magnitude in the negative direction
* - error[1] : " " " " positive "
*/
module.exports = function makeComputeError(opts) {
var type = opts.type;
var symmetric = opts.symmetric;
if (type === 'data') {
var array = opts.array || [];
if (symmetric) {
return function computeError(dataPt, index) {
var val = +array[index];
return [val, val];
};
} else {
var arrayminus = opts.arrayminus || [];
return function computeError(dataPt, index) {
var val = +array[index];
var valMinus = +arrayminus[index];
// in case one is present and the other is missing, fill in 0
// so we still see the present one. Mostly useful during manual
// data entry.
if (!isNaN(val) || !isNaN(valMinus)) {
return [valMinus || 0, val || 0];
}
return [NaN, NaN];
};
}
} else {
var computeErrorValue = makeComputeErrorValue(type, opts.value);
var computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus);
if (symmetric || opts.valueminus === undefined) {
return function computeError(dataPt) {
var val = computeErrorValue(dataPt);
return [val, val];
};
} else {
return function computeError(dataPt) {
return [computeErrorValueMinus(dataPt), computeErrorValue(dataPt)];
};
}
}
};
/**
* Compute error bar magnitude (for all types except data)
*
* @param {string} type error bar type
* @param {numeric} value error bar value
*
* @return {function} :
* @param {numeric} dataPt
*/
function makeComputeErrorValue(type, value) {
if (type === 'percent') {
return function (dataPt) {
return Math.abs(dataPt * value / 100);
};
}
if (type === 'constant') {
return function () {
return Math.abs(value);
};
}
if (type === 'sqrt') {
return function (dataPt) {
return Math.sqrt(Math.abs(dataPt));
};
}
}
/***/ }),
/***/ 65200:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
var attributes = __webpack_require__(97644);
module.exports = function (traceIn, traceOut, defaultColor, opts) {
var objName = 'error_' + opts.axis;
var containerOut = Template.newContainer(traceOut, objName);
var containerIn = traceIn[objName] || {};
function coerce(attr, dflt) {
return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
}
var hasErrorBars = containerIn.array !== undefined || containerIn.value !== undefined || containerIn.type === 'sqrt';
var visible = coerce('visible', hasErrorBars);
if (visible === false) return;
var type = coerce('type', 'array' in containerIn ? 'data' : 'percent');
var symmetric = true;
if (type !== 'sqrt') {
symmetric = coerce('symmetric', !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn));
}
if (type === 'data') {
coerce('array');
coerce('traceref');
if (!symmetric) {
coerce('arrayminus');
coerce('tracerefminus');
}
} else if (type === 'percent' || type === 'constant') {
coerce('value');
if (!symmetric) coerce('valueminus');
}
var copyAttr = 'copy_' + opts.inherit + 'style';
if (opts.inherit) {
var inheritObj = traceOut['error_' + opts.inherit];
if ((inheritObj || {}).visible) {
coerce(copyAttr, !(containerIn.color || isNumeric(containerIn.thickness) || isNumeric(containerIn.width)));
}
}
if (!opts.inherit || !containerOut[copyAttr]) {
coerce('color', defaultColor);
coerce('thickness');
coerce('width', Registry.traceIs(traceOut, 'gl3d') ? 0 : 4);
}
};
/***/ }),
/***/ 64968:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var overrideAll = (__webpack_require__(67824).overrideAll);
var attributes = __webpack_require__(97644);
var xyAttrs = {
error_x: Lib.extendFlat({}, attributes),
error_y: Lib.extendFlat({}, attributes)
};
delete xyAttrs.error_x.copy_zstyle;
delete xyAttrs.error_y.copy_zstyle;
delete xyAttrs.error_y.copy_ystyle;
var xyzAttrs = {
error_x: Lib.extendFlat({}, attributes),
error_y: Lib.extendFlat({}, attributes),
error_z: Lib.extendFlat({}, attributes)
};
delete xyzAttrs.error_x.copy_ystyle;
delete xyzAttrs.error_y.copy_ystyle;
delete xyzAttrs.error_z.copy_ystyle;
delete xyzAttrs.error_z.copy_zstyle;
module.exports = {
moduleType: 'component',
name: 'errorbars',
schema: {
traces: {
scatter: xyAttrs,
bar: xyAttrs,
histogram: xyAttrs,
scatter3d: overrideAll(xyzAttrs, 'calc', 'nested'),
scattergl: overrideAll(xyAttrs, 'calc', 'nested')
}
},
supplyDefaults: __webpack_require__(65200),
calc: __webpack_require__(14880),
makeComputeError: __webpack_require__(93792),
plot: __webpack_require__(78512),
style: __webpack_require__(92036),
hoverInfo: hoverInfo
};
function hoverInfo(calcPoint, trace, hoverPoint) {
if ((trace.error_y || {}).visible) {
hoverPoint.yerr = calcPoint.yh - calcPoint.y;
if (!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys;
}
if ((trace.error_x || {}).visible) {
hoverPoint.xerr = calcPoint.xh - calcPoint.x;
if (!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs;
}
}
/***/ }),
/***/ 78512:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var isNumeric = __webpack_require__(38248);
var Drawing = __webpack_require__(43616);
var subTypes = __webpack_require__(43028);
module.exports = function plot(gd, traces, plotinfo, transitionOpts) {
var isNew;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var hasAnimation = transitionOpts && transitionOpts.duration > 0;
var isStatic = gd._context.staticPlot;
traces.each(function (d) {
var trace = d[0].trace;
// || {} is in case the trace (specifically scatterternary)
// doesn't support error bars at all, but does go through
// the scatter.plot mechanics, which calls ErrorBars.plot
// internally
var xObj = trace.error_x || {};
var yObj = trace.error_y || {};
var keyFunc;
if (trace.ids) {
keyFunc = function (d) {
return d.id;
};
}
var sparse = subTypes.hasMarkers(trace) && trace.marker.maxdisplayed > 0;
if (!yObj.visible && !xObj.visible) d = [];
var errorbars = d3.select(this).selectAll('g.errorbar').data(d, keyFunc);
errorbars.exit().remove();
if (!d.length) return;
if (!xObj.visible) errorbars.selectAll('path.xerror').remove();
if (!yObj.visible) errorbars.selectAll('path.yerror').remove();
errorbars.style('opacity', 1);
var enter = errorbars.enter().append('g').classed('errorbar', true);
if (hasAnimation) {
enter.style('opacity', 0).transition().duration(transitionOpts.duration).style('opacity', 1);
}
Drawing.setClipUrl(errorbars, plotinfo.layerClipId, gd);
errorbars.each(function (d) {
var errorbar = d3.select(this);
var coords = errorCoords(d, xa, ya);
if (sparse && !d.vis) return;
var path;
var yerror = errorbar.select('path.yerror');
if (yObj.visible && isNumeric(coords.x) && isNumeric(coords.yh) && isNumeric(coords.ys)) {
var yw = yObj.width;
path = 'M' + (coords.x - yw) + ',' + coords.yh + 'h' + 2 * yw +
// hat
'm-' + yw + ',0V' + coords.ys; // bar
if (!coords.noYS) path += 'm-' + yw + ',0h' + 2 * yw; // shoe
isNew = !yerror.size();
if (isNew) {
yerror = errorbar.append('path').style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke').classed('yerror', true);
} else if (hasAnimation) {
yerror = yerror.transition().duration(transitionOpts.duration).ease(transitionOpts.easing);
}
yerror.attr('d', path);
} else yerror.remove();
var xerror = errorbar.select('path.xerror');
if (xObj.visible && isNumeric(coords.y) && isNumeric(coords.xh) && isNumeric(coords.xs)) {
var xw = (xObj.copy_ystyle ? yObj : xObj).width;
path = 'M' + coords.xh + ',' + (coords.y - xw) + 'v' + 2 * xw +
// hat
'm0,-' + xw + 'H' + coords.xs; // bar
if (!coords.noXS) path += 'm0,-' + xw + 'v' + 2 * xw; // shoe
isNew = !xerror.size();
if (isNew) {
xerror = errorbar.append('path').style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke').classed('xerror', true);
} else if (hasAnimation) {
xerror = xerror.transition().duration(transitionOpts.duration).ease(transitionOpts.easing);
}
xerror.attr('d', path);
} else xerror.remove();
});
});
};
// compute the coordinates of the error-bar objects
function errorCoords(d, xa, ya) {
var out = {
x: xa.c2p(d.x),
y: ya.c2p(d.y)
};
// calculate the error bar size and hat and shoe locations
if (d.yh !== undefined) {
out.yh = ya.c2p(d.yh);
out.ys = ya.c2p(d.ys);
// if the shoes go off-scale (ie log scale, error bars past zero)
// clip the bar and hide the shoes
if (!isNumeric(out.ys)) {
out.noYS = true;
out.ys = ya.c2p(d.ys, true);
}
}
if (d.xh !== undefined) {
out.xh = xa.c2p(d.xh);
out.xs = xa.c2p(d.xs);
if (!isNumeric(out.xs)) {
out.noXS = true;
out.xs = xa.c2p(d.xs, true);
}
}
return out;
}
/***/ }),
/***/ 92036:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
module.exports = function style(traces) {
traces.each(function (d) {
var trace = d[0].trace;
var yObj = trace.error_y || {};
var xObj = trace.error_x || {};
var s = d3.select(this);
s.selectAll('path.yerror').style('stroke-width', yObj.thickness + 'px').call(Color.stroke, yObj.color);
if (xObj.copy_ystyle) xObj = yObj;
s.selectAll('path.xerror').style('stroke-width', xObj.thickness + 'px').call(Color.stroke, xObj.color);
});
};
/***/ }),
/***/ 55756:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var hoverLabelAttrs = (__webpack_require__(65460).hoverlabel);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = {
hoverlabel: {
bgcolor: extendFlat({}, hoverLabelAttrs.bgcolor, {
arrayOk: true
}),
bordercolor: extendFlat({}, hoverLabelAttrs.bordercolor, {
arrayOk: true
}),
font: fontAttrs({
arrayOk: true,
editType: 'none'
}),
align: extendFlat({}, hoverLabelAttrs.align, {
arrayOk: true
}),
namelength: extendFlat({}, hoverLabelAttrs.namelength, {
arrayOk: true
}),
editType: 'none'
}
};
/***/ }),
/***/ 55056:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
module.exports = function calc(gd) {
var calcdata = gd.calcdata;
var fullLayout = gd._fullLayout;
function makeCoerceHoverInfo(trace) {
return function (val) {
return Lib.coerceHoverinfo({
hoverinfo: val
}, {
_module: trace._module
}, fullLayout);
};
}
for (var i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var trace = cd[0].trace;
// don't include hover calc fields for pie traces
// as calcdata items might be sorted by value and
// won't match the data array order.
if (Registry.traceIs(trace, 'pie-like')) continue;
var fillFn = Registry.traceIs(trace, '2dMap') ? paste : Lib.fillArray;
fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace));
if (trace.hovertemplate) fillFn(trace.hovertemplate, cd, 'ht');
if (!trace.hoverlabel) continue;
fillFn(trace.hoverlabel.bgcolor, cd, 'hbg');
fillFn(trace.hoverlabel.bordercolor, cd, 'hbc');
fillFn(trace.hoverlabel.font.size, cd, 'hts');
fillFn(trace.hoverlabel.font.color, cd, 'htc');
fillFn(trace.hoverlabel.font.family, cd, 'htf');
fillFn(trace.hoverlabel.font.weight, cd, 'htw');
fillFn(trace.hoverlabel.font.style, cd, 'hty');
fillFn(trace.hoverlabel.font.variant, cd, 'htv');
fillFn(trace.hoverlabel.namelength, cd, 'hnl');
fillFn(trace.hoverlabel.align, cd, 'hta');
}
};
function paste(traceAttr, cd, cdAttr, fn) {
fn = fn || Lib.identity;
if (Array.isArray(traceAttr)) {
cd[0][cdAttr] = fn(traceAttr);
}
}
/***/ }),
/***/ 62376:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var hover = (__webpack_require__(83292).hover);
module.exports = function click(gd, evt, subplot) {
var annotationsDone = Registry.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata);
// fallback to fail-safe in case the plot type's hover method doesn't pass the subplot.
// Ternary, for example, didn't, but it was caught because tested.
if (subplot !== undefined) {
// The true flag at the end causes it to re-run the hover computation to figure out *which*
// point is being clicked. Without this, clicking is somewhat unreliable.
hover(gd, evt, subplot, true);
}
function emitClick() {
gd.emit('plotly_click', {
points: gd._hoverdata,
event: evt
});
}
if (gd._hoverdata && evt && evt.target) {
if (annotationsDone && annotationsDone.then) {
annotationsDone.then(emitClick);
} else emitClick();
// why do we get a double event without this???
if (evt.stopImmediatePropagation) evt.stopImmediatePropagation();
}
};
/***/ }),
/***/ 92456:
/***/ (function(module) {
"use strict";
module.exports = {
// hover labels for multiple horizontal bars get tilted by this angle
YANGLE: 60,
// size and display constants for hover text
// pixel size of hover arrows
HOVERARROWSIZE: 6,
// pixels padding around text
HOVERTEXTPAD: 3,
// hover font
HOVERFONTSIZE: 13,
HOVERFONT: 'Arial, sans-serif',
// minimum time (msec) between hover calls
HOVERMINTIME: 50,
// ID suffix (with fullLayout._uid) for hover events in the throttle cache
HOVERID: '-hover'
};
/***/ }),
/***/ 95448:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(55756);
var handleHoverLabelDefaults = __webpack_require__(16132);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var opts = Lib.extendFlat({}, layout.hoverlabel);
if (traceOut.hovertemplate) opts.namelength = -1;
handleHoverLabelDefaults(traceIn, traceOut, coerce, opts);
};
/***/ }),
/***/ 10624:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
// look for either subplot or xaxis and yaxis attributes
// does not handle splom case
exports.getSubplot = function (trace) {
return trace.subplot || trace.xaxis + trace.yaxis || trace.geo;
};
// is trace in given list of subplots?
// does handle splom case
exports.isTraceInSubplots = function (trace, subplots) {
if (trace.type === 'splom') {
var xaxes = trace.xaxes || [];
var yaxes = trace.yaxes || [];
for (var i = 0; i < xaxes.length; i++) {
for (var j = 0; j < yaxes.length; j++) {
if (subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) {
return true;
}
}
}
return false;
}
return subplots.indexOf(exports.getSubplot(trace)) !== -1;
};
// convenience functions for mapping all relevant axes
exports.flat = function (subplots, v) {
var out = new Array(subplots.length);
for (var i = 0; i < subplots.length; i++) {
out[i] = v;
}
return out;
};
exports.p2c = function (axArray, v) {
var out = new Array(axArray.length);
for (var i = 0; i < axArray.length; i++) {
out[i] = axArray[i].p2c(v);
}
return out;
};
exports.getDistanceFunction = function (mode, dx, dy, dxy) {
if (mode === 'closest') return dxy || exports.quadrature(dx, dy);
return mode.charAt(0) === 'x' ? dx : dy;
};
exports.getClosest = function (cd, distfn, pointData) {
// do we already have a point number? (array mode only)
if (pointData.index !== false) {
if (pointData.index >= 0 && pointData.index < cd.length) {
pointData.distance = 0;
} else pointData.index = false;
} else {
// apply the distance function to each data point
// this is the longest loop... if this bogs down, we may need
// to create pre-sorted data (by x or y), not sure how to
// do this for 'closest'
for (var i = 0; i < cd.length; i++) {
var newDistance = distfn(cd[i]);
if (newDistance <= pointData.distance) {
pointData.index = i;
pointData.distance = newDistance;
}
}
}
return pointData;
};
/*
* pseudo-distance function for hover effects on areas: inside the region
* distance is finite (`passVal`), outside it's Infinity.
*
* @param {number} v0: signed difference between the current position and the left edge
* @param {number} v1: signed difference between the current position and the right edge
* @param {number} passVal: the value to return on success
*/
exports.inbox = function (v0, v1, passVal) {
return v0 * v1 < 0 || v0 === 0 ? passVal : Infinity;
};
exports.quadrature = function (dx, dy) {
return function (di) {
var x = dx(di);
var y = dy(di);
return Math.sqrt(x * x + y * y);
};
};
/** Fill event data point object for hover and selection.
* Invokes _module.eventData if present.
*
* N.B. note that point 'index' corresponds to input data array index
* whereas 'number' is its post-transform version.
*
* If the hovered/selected pt corresponds to an multiple input points
* (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices'
* are include in the event data.
*
* @param {object} pt
* @param {object} trace
* @param {object} cd
* @return {object}
*/
exports.makeEventData = function (pt, trace, cd) {
// hover uses 'index', select uses 'pointNumber'
var pointNumber = 'index' in pt ? pt.index : pt.pointNumber;
var out = {
data: trace._input,
fullData: trace,
curveNumber: trace.index,
pointNumber: pointNumber
};
if (trace._indexToPoints) {
var pointIndices = trace._indexToPoints[pointNumber];
if (pointIndices.length === 1) {
out.pointIndex = pointIndices[0];
} else {
out.pointIndices = pointIndices;
}
} else {
out.pointIndex = pointNumber;
}
if (trace._module.eventData) {
out = trace._module.eventData(out, pt, trace, cd, pointNumber);
} else {
if ('xVal' in pt) out.x = pt.xVal;else if ('x' in pt) out.x = pt.x;
if ('yVal' in pt) out.y = pt.yVal;else if ('y' in pt) out.y = pt.y;
if (pt.xa) out.xaxis = pt.xa;
if (pt.ya) out.yaxis = pt.ya;
if (pt.zLabelVal !== undefined) out.z = pt.zLabelVal;
}
exports.appendArrayPointValue(out, trace, pointNumber);
return out;
};
/** Appends values inside array attributes corresponding to given point number
*
* @param {object} pointData : point data object (gets mutated here)
* @param {object} trace : full trace object
* @param {number|Array(number)} pointNumber : point number. May be a length-2 array
* [row, col] to dig into 2D arrays
*/
exports.appendArrayPointValue = function (pointData, trace, pointNumber) {
var arrayAttrs = trace._arrayAttrs;
if (!arrayAttrs) {
return;
}
for (var i = 0; i < arrayAttrs.length; i++) {
var astr = arrayAttrs[i];
var key = getPointKey(astr);
if (pointData[key] === undefined) {
var val = Lib.nestedProperty(trace, astr).get();
var pointVal = getPointData(val, pointNumber);
if (pointVal !== undefined) pointData[key] = pointVal;
}
}
};
/**
* Appends values inside array attributes corresponding to given point number array
* For use when pointData references a plot entity that arose (or potentially arose)
* from multiple points in the input data
*
* @param {object} pointData : point data object (gets mutated here)
* @param {object} trace : full trace object
* @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers.
* Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays
*/
exports.appendArrayMultiPointValues = function (pointData, trace, pointNumbers) {
var arrayAttrs = trace._arrayAttrs;
if (!arrayAttrs) {
return;
}
for (var i = 0; i < arrayAttrs.length; i++) {
var astr = arrayAttrs[i];
var key = getPointKey(astr);
if (pointData[key] === undefined) {
var val = Lib.nestedProperty(trace, astr).get();
var keyVal = new Array(pointNumbers.length);
for (var j = 0; j < pointNumbers.length; j++) {
keyVal[j] = getPointData(val, pointNumbers[j]);
}
pointData[key] = keyVal;
}
}
};
var pointKeyMap = {
ids: 'id',
locations: 'location',
labels: 'label',
values: 'value',
'marker.colors': 'color',
parents: 'parent'
};
function getPointKey(astr) {
return pointKeyMap[astr] || astr;
}
function getPointData(val, pointNumber) {
if (Array.isArray(pointNumber)) {
if (Array.isArray(val) && Array.isArray(val[pointNumber[0]])) {
return val[pointNumber[0]][pointNumber[1]];
}
} else {
return val[pointNumber];
}
}
var xyHoverMode = {
x: true,
y: true
};
var unifiedHoverMode = {
'x unified': true,
'y unified': true
};
exports.isUnifiedHover = function (hovermode) {
if (typeof hovermode !== 'string') return false;
return !!unifiedHoverMode[hovermode];
};
exports.isXYhover = function (hovermode) {
if (typeof hovermode !== 'string') return false;
return !!xyHoverMode[hovermode];
};
/***/ }),
/***/ 83292:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var isNumeric = __webpack_require__(38248);
var tinycolor = __webpack_require__(49760);
var Lib = __webpack_require__(3400);
var pushUnique = Lib.pushUnique;
var strTranslate = Lib.strTranslate;
var strRotate = Lib.strRotate;
var Events = __webpack_require__(95924);
var svgTextUtils = __webpack_require__(72736);
var overrideCursor = __webpack_require__(72213);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var dragElement = __webpack_require__(86476);
var Axes = __webpack_require__(54460);
var zindexSeparator = (__webpack_require__(33816).zindexSeparator);
var Registry = __webpack_require__(24040);
var helpers = __webpack_require__(10624);
var constants = __webpack_require__(92456);
var legendSupplyDefaults = __webpack_require__(77864);
var legendDraw = __webpack_require__(31140);
// hover labels for multiple horizontal bars get tilted by some angle,
// then need to be offset differently if they overlap
var YANGLE = constants.YANGLE;
var YA_RADIANS = Math.PI * YANGLE / 180;
// expansion of projected height
var YFACTOR = 1 / Math.sin(YA_RADIANS);
// to make the appropriate post-rotation x offset,
// you need both x and y offsets
var YSHIFTX = Math.cos(YA_RADIANS);
var YSHIFTY = Math.sin(YA_RADIANS);
// size and display constants for hover text
var HOVERARROWSIZE = constants.HOVERARROWSIZE;
var HOVERTEXTPAD = constants.HOVERTEXTPAD;
var multipleHoverPoints = {
box: true,
ohlc: true,
violin: true,
candlestick: true
};
var cartesianScatterPoints = {
scatter: true,
scattergl: true,
splom: true
};
function distanceSort(a, b) {
return a.distance - b.distance;
}
// fx.hover: highlight data on hover
// evt can be a mousemove event, or an object with data about what points
// to hover on
// {xpx,ypx[,hovermode]} - pixel locations from top left
// (with optional overriding hovermode)
// {xval,yval[,hovermode]} - data values
// [{curveNumber,(pointNumber|xval and/or yval)}] -
// array of specific points to highlight
// pointNumber is a single integer if gd.data[curveNumber] is 1D,
// or a two-element array if it's 2D
// xval and yval are data values,
// 1D data may specify either or both,
// 2D data must specify both
// subplot is an id string (default "xy")
// makes use of gl.hovermode, which can be:
// x (find the points with the closest x values, ie a column),
// closest (find the single closest point)
// internally there are two more that occasionally get used:
// y (pick out a row - only used for multiple horizontal bar charts)
// array (used when the user specifies an explicit
// array of points to hover on)
//
// We wrap the hovers in a timer, to limit their frequency.
// The actual rendering is done by private function _hover.
exports.hover = function hover(gd, evt, subplot, noHoverEvent) {
gd = Lib.getGraphDiv(gd);
// The 'target' property changes when bubbling out of Shadow DOM.
// Throttling can delay reading the target, so we save the current value.
var eventTarget = evt.target;
Lib.throttle(gd._fullLayout._uid + constants.HOVERID, constants.HOVERMINTIME, function () {
_hover(gd, evt, subplot, noHoverEvent, eventTarget);
});
};
/*
* Draw a single hover item or an array of hover item in a pre-existing svg container somewhere
* hoverItem should have keys:
* - x and y (or x0, x1, y0, and y1):
* the pixel position to mark, relative to opts.container
* - xLabel, yLabel, zLabel, text, and name:
* info to go in the label
* - color:
* the background color for the label.
* - idealAlign (optional):
* 'left' or 'right' for which side of the x/y box to try to put this on first
* - borderColor (optional):
* color for the border, defaults to strongest contrast with color
* - fontFamily (optional):
* string, the font for this label, defaults to constants.HOVERFONT
* - fontSize (optional):
* the label font size, defaults to constants.HOVERFONTSIZE
* - fontColor (optional):
* defaults to borderColor
* opts should have keys:
* - bgColor:
* the background color this is against, used if the trace is
* non-opaque, and for the name, which goes outside the box
* - container:
* a or element to add the hover label to
* - outerContainer:
* normally a parent of `container`, sets the bounding box to use to
* constrain the hover label and determine whether to show it on the left or right
* opts can have optional keys:
* - anchorIndex:
the index of the hover item used as an anchor for positioning.
The other hover items will be pushed up or down to prevent overlap.
*/
exports.loneHover = function loneHover(hoverItems, opts) {
var multiHover = true;
if (!Array.isArray(hoverItems)) {
multiHover = false;
hoverItems = [hoverItems];
}
var gd = opts.gd;
var gTop = getTopOffset(gd);
var gLeft = getLeftOffset(gd);
var pointsData = hoverItems.map(function (hoverItem) {
var _x0 = hoverItem._x0 || hoverItem.x0 || hoverItem.x || 0;
var _x1 = hoverItem._x1 || hoverItem.x1 || hoverItem.x || 0;
var _y0 = hoverItem._y0 || hoverItem.y0 || hoverItem.y || 0;
var _y1 = hoverItem._y1 || hoverItem.y1 || hoverItem.y || 0;
var eventData = hoverItem.eventData;
if (eventData) {
var x0 = Math.min(_x0, _x1);
var x1 = Math.max(_x0, _x1);
var y0 = Math.min(_y0, _y1);
var y1 = Math.max(_y0, _y1);
var trace = hoverItem.trace;
if (Registry.traceIs(trace, 'gl3d')) {
var container = gd._fullLayout[trace.scene]._scene.container;
var dx = container.offsetLeft;
var dy = container.offsetTop;
x0 += dx;
x1 += dx;
y0 += dy;
y1 += dy;
} // TODO: handle heatmapgl
eventData.bbox = {
x0: x0 + gLeft,
x1: x1 + gLeft,
y0: y0 + gTop,
y1: y1 + gTop
};
if (opts.inOut_bbox) {
opts.inOut_bbox.push(eventData.bbox);
}
} else {
eventData = false;
}
return {
color: hoverItem.color || Color.defaultLine,
x0: hoverItem.x0 || hoverItem.x || 0,
x1: hoverItem.x1 || hoverItem.x || 0,
y0: hoverItem.y0 || hoverItem.y || 0,
y1: hoverItem.y1 || hoverItem.y || 0,
xLabel: hoverItem.xLabel,
yLabel: hoverItem.yLabel,
zLabel: hoverItem.zLabel,
text: hoverItem.text,
name: hoverItem.name,
idealAlign: hoverItem.idealAlign,
// optional extra bits of styling
borderColor: hoverItem.borderColor,
fontFamily: hoverItem.fontFamily,
fontSize: hoverItem.fontSize,
fontColor: hoverItem.fontColor,
fontWeight: hoverItem.fontWeight,
fontStyle: hoverItem.fontStyle,
fontVariant: hoverItem.fontVariant,
nameLength: hoverItem.nameLength,
textAlign: hoverItem.textAlign,
// filler to make createHoverText happy
trace: hoverItem.trace || {
index: 0,
hoverinfo: ''
},
xa: {
_offset: 0
},
ya: {
_offset: 0
},
index: 0,
hovertemplate: hoverItem.hovertemplate || false,
hovertemplateLabels: hoverItem.hovertemplateLabels || false,
eventData: eventData
};
});
var rotateLabels = false;
var hoverText = createHoverText(pointsData, {
gd: gd,
hovermode: 'closest',
rotateLabels: rotateLabels,
bgColor: opts.bgColor || Color.background,
container: d3.select(opts.container),
outerContainer: opts.outerContainer || opts.container
});
var hoverLabel = hoverText.hoverLabels;
// Fix vertical overlap
var tooltipSpacing = 5;
var lastBottomY = 0;
var anchor = 0;
hoverLabel.sort(function (a, b) {
return a.y0 - b.y0;
}).each(function (d, i) {
var topY = d.y0 - d.by / 2;
if (topY - tooltipSpacing < lastBottomY) {
d.offset = lastBottomY - topY + tooltipSpacing;
} else {
d.offset = 0;
}
lastBottomY = topY + d.by + d.offset;
if (i === opts.anchorIndex || 0) anchor = d.offset;
}).each(function (d) {
d.offset -= anchor;
});
var scaleX = gd._fullLayout._invScaleX;
var scaleY = gd._fullLayout._invScaleY;
alignHoverText(hoverLabel, rotateLabels, scaleX, scaleY);
return multiHover ? hoverLabel : hoverLabel.node();
};
// The actual implementation is here:
function _hover(gd, evt, subplot, noHoverEvent, eventTarget) {
if (!subplot) subplot = 'xy';
if (typeof subplot === 'string') {
// drop zindex from subplot id
subplot = subplot.split(zindexSeparator)[0];
}
// if the user passed in an array of subplots,
// use those instead of finding overlayed plots
var subplots = Array.isArray(subplot) ? subplot : [subplot];
var spId;
var fullLayout = gd._fullLayout;
var hoversubplots = fullLayout.hoversubplots;
var plots = fullLayout._plots || [];
var plotinfo = plots[subplot];
var hasCartesian = fullLayout._has('cartesian');
var hovermode = evt.hovermode || fullLayout.hovermode;
var hovermodeHasX = (hovermode || '').charAt(0) === 'x';
var hovermodeHasY = (hovermode || '').charAt(0) === 'y';
var firstXaxis;
var firstYaxis;
if (hasCartesian && (hovermodeHasX || hovermodeHasY) && hoversubplots === 'axis') {
var subplotsLength = subplots.length;
for (var p = 0; p < subplotsLength; p++) {
spId = subplots[p];
if (plots[spId]) {
// 'cartesian' case
firstXaxis = Axes.getFromId(gd, spId, 'x');
firstYaxis = Axes.getFromId(gd, spId, 'y');
var subplotsWith = (hovermodeHasX ? firstXaxis : firstYaxis)._subplotsWith;
if (subplotsWith && subplotsWith.length) {
for (var q = 0; q < subplotsWith.length; q++) {
pushUnique(subplots, subplotsWith[q]);
}
}
}
}
}
// list of all overlaid subplots to look at
if (plotinfo && hoversubplots !== 'single') {
var overlayedSubplots = plotinfo.overlays.map(function (pi) {
return pi.id;
});
subplots = subplots.concat(overlayedSubplots);
}
var len = subplots.length;
var xaArray = new Array(len);
var yaArray = new Array(len);
var supportsCompare = false;
for (var i = 0; i < len; i++) {
spId = subplots[i];
if (plots[spId]) {
// 'cartesian' case
supportsCompare = true;
xaArray[i] = plots[spId].xaxis;
yaArray[i] = plots[spId].yaxis;
} else if (fullLayout[spId] && fullLayout[spId]._subplot) {
// other subplot types
var _subplot = fullLayout[spId]._subplot;
xaArray[i] = _subplot.xaxis;
yaArray[i] = _subplot.yaxis;
} else {
Lib.warn('Unrecognized subplot: ' + spId);
return;
}
}
if (hovermode && !supportsCompare) hovermode = 'closest';
if (['x', 'y', 'closest', 'x unified', 'y unified'].indexOf(hovermode) === -1 || !gd.calcdata || gd.querySelector('.zoombox') || gd._dragging) {
return dragElement.unhoverRaw(gd, evt);
}
var hoverdistance = fullLayout.hoverdistance;
if (hoverdistance === -1) hoverdistance = Infinity;
var spikedistance = fullLayout.spikedistance;
if (spikedistance === -1) spikedistance = Infinity;
// hoverData: the set of candidate points we've found to highlight
var hoverData = [];
// searchData: the data to search in. Mostly this is just a copy of
// gd.calcdata, filtered to the subplot and overlays we're on
// but if a point array is supplied it will be a mapping
// of indicated curves
var searchData = [];
// [x|y]valArray: the axis values of the hover event
// mapped onto each of the currently selected overlaid subplots
var xvalArray, yvalArray;
var itemnum, curvenum, cd, trace, subplotId, subploti, _mode, xval, yval, pointData, closedataPreviousLength;
// spikePoints: the set of candidate points we've found to draw spikes to
var spikePoints = {
hLinePoint: null,
vLinePoint: null
};
// does subplot have one (or more) horizontal traces?
// This is used to determine whether we rotate the labels or not
var hasOneHorizontalTrace = false;
// Figure out what we're hovering on:
// mouse location or user-supplied data
if (Array.isArray(evt)) {
// user specified an array of points to highlight
hovermode = 'array';
for (itemnum = 0; itemnum < evt.length; itemnum++) {
cd = gd.calcdata[evt[itemnum].curveNumber || 0];
if (cd) {
trace = cd[0].trace;
if (cd[0].trace.hoverinfo !== 'skip') {
searchData.push(cd);
if (trace.orientation === 'h') {
hasOneHorizontalTrace = true;
}
}
}
}
} else {
// take into account zorder
var zorderedCalcdata = gd.calcdata.slice();
zorderedCalcdata.sort(function (a, b) {
var aZorder = a[0].trace.zorder || 0;
var bZorder = b[0].trace.zorder || 0;
return aZorder - bZorder;
});
for (curvenum = 0; curvenum < zorderedCalcdata.length; curvenum++) {
cd = zorderedCalcdata[curvenum];
trace = cd[0].trace;
if (trace.hoverinfo !== 'skip' && helpers.isTraceInSubplots(trace, subplots)) {
searchData.push(cd);
if (trace.orientation === 'h') {
hasOneHorizontalTrace = true;
}
}
}
// [x|y]px: the pixels (from top left) of the mouse location
// on the currently selected plot area
// add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation
var hasUserCalledHover = !eventTarget;
var xpx, ypx;
if (hasUserCalledHover) {
if ('xpx' in evt) xpx = evt.xpx;else xpx = xaArray[0]._length / 2;
if ('ypx' in evt) ypx = evt.ypx;else ypx = yaArray[0]._length / 2;
} else {
// fire the beforehover event and quit if it returns false
// note that we're only calling this on real mouse events, so
// manual calls to fx.hover will always run.
if (Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
return;
}
var dbb = eventTarget.getBoundingClientRect();
xpx = evt.clientX - dbb.left;
ypx = evt.clientY - dbb.top;
fullLayout._calcInverseTransform(gd);
var transformedCoords = Lib.apply3DTransform(fullLayout._invTransform)(xpx, ypx);
xpx = transformedCoords[0];
ypx = transformedCoords[1];
// in case hover was called from mouseout into hovertext,
// it's possible you're not actually over the plot anymore
if (xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) {
return dragElement.unhoverRaw(gd, evt);
}
}
evt.pointerX = xpx + xaArray[0]._offset;
evt.pointerY = ypx + yaArray[0]._offset;
if ('xval' in evt) xvalArray = helpers.flat(subplots, evt.xval);else xvalArray = helpers.p2c(xaArray, xpx);
if ('yval' in evt) yvalArray = helpers.flat(subplots, evt.yval);else yvalArray = helpers.p2c(yaArray, ypx);
if (!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
Lib.warn('Fx.hover failed', evt, gd);
return dragElement.unhoverRaw(gd, evt);
}
}
// the pixel distance to beat as a matching point
// in 'x' or 'y' mode this resets for each trace
var distance = Infinity;
// find the closest point in each trace
// this is minimum dx and/or dy, depending on mode
// and the pixel position for the label (labelXpx, labelYpx)
function findHoverPoints(customXVal, customYVal) {
for (curvenum = 0; curvenum < searchData.length; curvenum++) {
cd = searchData[curvenum];
// filter out invisible or broken data
if (!cd || !cd[0] || !cd[0].trace) continue;
trace = cd[0].trace;
if (trace.visible !== true || trace._length === 0) continue;
// Explicitly bail out for these two. I don't know how to otherwise prevent
// the rest of this function from running and failing
if (['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue;
// within one trace mode can sometimes be overridden
_mode = hovermode;
if (helpers.isUnifiedHover(_mode)) {
_mode = _mode.charAt(0);
}
if (trace.type === 'splom') {
// splom traces do not generate overlay subplots,
// it is safe to assume here splom traces correspond to the 0th subplot
subploti = 0;
subplotId = subplots[subploti];
} else {
subplotId = helpers.getSubplot(trace);
subploti = subplots.indexOf(subplotId);
}
// container for new point, also used to pass info into module.hoverPoints
pointData = {
// trace properties
cd: cd,
trace: trace,
xa: xaArray[subploti],
ya: yaArray[subploti],
// max distances for hover and spikes - for points that want to show but do not
// want to override other points, set distance/spikeDistance equal to max*Distance
// and it will not get filtered out but it will be guaranteed to have a greater
// distance than any point that calculated a real distance.
maxHoverDistance: hoverdistance,
maxSpikeDistance: spikedistance,
// point properties - override all of these
index: false,
// point index in trace - only used by plotly.js hoverdata consumers
distance: Math.min(distance, hoverdistance),
// pixel distance or pseudo-distance
// distance/pseudo-distance for spikes. This distance should always be calculated
// as if in "closest" mode, and should only be set if this point should
// generate a spike.
spikeDistance: Infinity,
// in some cases the spikes have different positioning from the hover label
// they don't need x0/x1, just one position
xSpike: undefined,
ySpike: undefined,
// where and how to display the hover label
color: Color.defaultLine,
// trace color
name: trace.name,
x0: undefined,
x1: undefined,
y0: undefined,
y1: undefined,
xLabelVal: undefined,
yLabelVal: undefined,
zLabelVal: undefined,
text: undefined
};
// add ref to subplot object (non-cartesian case)
if (fullLayout[subplotId]) {
pointData.subplot = fullLayout[subplotId]._subplot;
}
// add ref to splom scene
if (fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) {
pointData.scene = fullLayout._splomScenes[trace.uid];
}
// for a highlighting array, figure out what
// we're searching for with this element
if (_mode === 'array') {
var selection = evt[curvenum];
if ('pointNumber' in selection) {
pointData.index = selection.pointNumber;
_mode = 'closest';
} else {
_mode = '';
if ('xval' in selection) {
xval = selection.xval;
_mode = 'x';
}
if ('yval' in selection) {
yval = selection.yval;
_mode = _mode ? 'closest' : 'y';
}
}
} else if (customXVal !== undefined && customYVal !== undefined) {
xval = customXVal;
yval = customYVal;
} else {
xval = xvalArray[subploti];
yval = yvalArray[subploti];
}
closedataPreviousLength = hoverData.length;
// Now if there is range to look in, find the points to hover.
if (hoverdistance !== 0) {
if (trace._module && trace._module.hoverPoints) {
var newPoints = trace._module.hoverPoints(pointData, xval, yval, _mode, {
finiteRange: true,
hoverLayer: fullLayout._hoverlayer,
// options for splom when hovering on same axis
hoversubplots: hoversubplots,
gd: gd
});
if (newPoints) {
var newPoint;
for (var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
newPoint = newPoints[newPointNum];
if (isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
hoverData.push(cleanPoint(newPoint, hovermode));
}
}
}
} else {
Lib.log('Unrecognized trace type in hover:', trace);
}
}
// in closest mode, remove any existing (farther) points
// and don't look any farther than this latest point (or points, some
// traces like box & violin make multiple hover labels at once)
if (hovermode === 'closest' && hoverData.length > closedataPreviousLength) {
hoverData.splice(0, closedataPreviousLength);
distance = hoverData[0].distance;
}
// Now if there is range to look in, find the points to draw the spikelines
// Do it only if there is no hoverData
if (hasCartesian && spikedistance !== 0) {
if (hoverData.length === 0) {
pointData.distance = spikedistance;
pointData.index = false;
var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', {
hoverLayer: fullLayout._hoverlayer
});
if (closestPoints) {
closestPoints = closestPoints.filter(function (point) {
// some hover points, like scatter fills, do not allow spikes,
// so will generate a hover point but without a valid spikeDistance
return point.spikeDistance <= spikedistance;
});
}
if (closestPoints && closestPoints.length) {
var tmpPoint;
var closestVPoints = closestPoints.filter(function (point) {
return point.xa.showspikes && point.xa.spikesnap !== 'hovered data';
});
if (closestVPoints.length) {
var closestVPt = closestVPoints[0];
if (isNumeric(closestVPt.x0) && isNumeric(closestVPt.y0)) {
tmpPoint = fillSpikePoint(closestVPt);
if (!spikePoints.vLinePoint || spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance) {
spikePoints.vLinePoint = tmpPoint;
}
}
}
var closestHPoints = closestPoints.filter(function (point) {
return point.ya.showspikes && point.ya.spikesnap !== 'hovered data';
});
if (closestHPoints.length) {
var closestHPt = closestHPoints[0];
if (isNumeric(closestHPt.x0) && isNumeric(closestHPt.y0)) {
tmpPoint = fillSpikePoint(closestHPt);
if (!spikePoints.hLinePoint || spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance) {
spikePoints.hLinePoint = tmpPoint;
}
}
}
}
}
}
}
}
findHoverPoints();
function selectClosestPoint(pointsData, spikedistance, spikeOnWinning) {
var resultPoint = null;
var minDistance = Infinity;
var thisSpikeDistance;
for (var i = 0; i < pointsData.length; i++) {
if (firstXaxis && firstXaxis._id !== pointsData[i].xa._id) continue;
if (firstYaxis && firstYaxis._id !== pointsData[i].ya._id) continue;
thisSpikeDistance = pointsData[i].spikeDistance;
if (spikeOnWinning && i === 0) thisSpikeDistance = -Infinity;
if (thisSpikeDistance <= minDistance && thisSpikeDistance <= spikedistance) {
resultPoint = pointsData[i];
minDistance = thisSpikeDistance;
}
}
return resultPoint;
}
function fillSpikePoint(point) {
if (!point) return null;
return {
xa: point.xa,
ya: point.ya,
x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2,
y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2,
distance: point.distance,
spikeDistance: point.spikeDistance,
curveNumber: point.trace.index,
color: point.color,
pointNumber: point.index
};
}
var spikelineOpts = {
fullLayout: fullLayout,
container: fullLayout._hoverlayer,
event: evt
};
var oldspikepoints = gd._spikepoints;
var newspikepoints = {
vLinePoint: spikePoints.vLinePoint,
hLinePoint: spikePoints.hLinePoint
};
gd._spikepoints = newspikepoints;
var sortHoverData = function () {
// When sorting keep the points in the main subplot at the top
// then add points in other subplots
var hoverDataInSubplot = hoverData.filter(function (a) {
return firstXaxis && firstXaxis._id === a.xa._id && firstYaxis && firstYaxis._id === a.ya._id;
});
var hoverDataOutSubplot = hoverData.filter(function (a) {
return !(firstXaxis && firstXaxis._id === a.xa._id && firstYaxis && firstYaxis._id === a.ya._id);
});
hoverDataInSubplot.sort(distanceSort);
hoverDataOutSubplot.sort(distanceSort);
hoverData = hoverDataInSubplot.concat(hoverDataOutSubplot);
// move period positioned points and box/bar-like traces to the end of the list
hoverData = orderRangePoints(hoverData, hovermode);
};
sortHoverData();
var axLetter = hovermode.charAt(0);
var spikeOnWinning = (axLetter === 'x' || axLetter === 'y') && hoverData[0] && cartesianScatterPoints[hoverData[0].trace.type];
// Now if it is not restricted by spikedistance option, set the points to draw the spikelines
if (hasCartesian && spikedistance !== 0) {
if (hoverData.length !== 0) {
var tmpHPointData = hoverData.filter(function (point) {
return point.ya.showspikes;
});
var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance, spikeOnWinning);
spikePoints.hLinePoint = fillSpikePoint(tmpHPoint);
var tmpVPointData = hoverData.filter(function (point) {
return point.xa.showspikes;
});
var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance, spikeOnWinning);
spikePoints.vLinePoint = fillSpikePoint(tmpVPoint);
}
}
// if hoverData is empty check for the spikes to draw and quit if there are none
if (hoverData.length === 0) {
var result = dragElement.unhoverRaw(gd, evt);
if (hasCartesian && (spikePoints.hLinePoint !== null || spikePoints.vLinePoint !== null)) {
if (spikesChanged(oldspikepoints)) {
createSpikelines(gd, spikePoints, spikelineOpts);
}
}
return result;
}
if (hasCartesian) {
if (spikesChanged(oldspikepoints)) {
createSpikelines(gd, spikePoints, spikelineOpts);
}
}
if (helpers.isXYhover(_mode) && hoverData[0].length !== 0 && hoverData[0].trace.type !== 'splom' // TODO: add support for splom
) {
// pick winning point
var winningPoint = hoverData[0];
// discard other points
if (multipleHoverPoints[winningPoint.trace.type]) {
hoverData = hoverData.filter(function (d) {
return d.trace.index === winningPoint.trace.index;
});
} else {
hoverData = [winningPoint];
}
var initLen = hoverData.length;
var winX = getCoord('x', winningPoint, fullLayout);
var winY = getCoord('y', winningPoint, fullLayout);
// in compare mode, select every point at position
findHoverPoints(winX, winY);
var finalPoints = [];
var seen = {};
var id = 0;
var insert = function (newHd) {
var key = multipleHoverPoints[newHd.trace.type] ? hoverDataKey(newHd) : newHd.trace.index;
if (!seen[key]) {
id++;
seen[key] = id;
finalPoints.push(newHd);
} else {
var oldId = seen[key] - 1;
var oldHd = finalPoints[oldId];
if (oldId > 0 && Math.abs(newHd.distance) < Math.abs(oldHd.distance)) {
// replace with closest
finalPoints[oldId] = newHd;
}
}
};
var k;
// insert the winnig point(s) first
for (k = 0; k < initLen; k++) {
insert(hoverData[k]);
}
// override from the end
for (k = hoverData.length - 1; k > initLen - 1; k--) {
insert(hoverData[k]);
}
hoverData = finalPoints;
sortHoverData();
}
// lastly, emit custom hover/unhover events
var oldhoverdata = gd._hoverdata;
var newhoverdata = [];
var gTop = getTopOffset(gd);
var gLeft = getLeftOffset(gd);
// pull out just the data that's useful to
// other people and send it to the event
for (itemnum = 0; itemnum < hoverData.length; itemnum++) {
var pt = hoverData[itemnum];
var eventData = helpers.makeEventData(pt, pt.trace, pt.cd);
if (pt.hovertemplate !== false) {
var ht = false;
if (pt.cd[pt.index] && pt.cd[pt.index].ht) {
ht = pt.cd[pt.index].ht;
}
pt.hovertemplate = ht || pt.trace.hovertemplate || false;
}
if (pt.xa && pt.ya) {
var _x0 = pt.x0 + pt.xa._offset;
var _x1 = pt.x1 + pt.xa._offset;
var _y0 = pt.y0 + pt.ya._offset;
var _y1 = pt.y1 + pt.ya._offset;
var x0 = Math.min(_x0, _x1);
var x1 = Math.max(_x0, _x1);
var y0 = Math.min(_y0, _y1);
var y1 = Math.max(_y0, _y1);
eventData.bbox = {
x0: x0 + gLeft,
x1: x1 + gLeft,
y0: y0 + gTop,
y1: y1 + gTop
};
}
pt.eventData = [eventData];
newhoverdata.push(eventData);
}
gd._hoverdata = newhoverdata;
var rotateLabels = hovermode === 'y' && (searchData.length > 1 || hoverData.length > 1) || hovermode === 'closest' && hasOneHorizontalTrace && hoverData.length > 1;
var bgColor = Color.combine(fullLayout.plot_bgcolor || Color.background, fullLayout.paper_bgcolor);
var hoverText = createHoverText(hoverData, {
gd: gd,
hovermode: hovermode,
rotateLabels: rotateLabels,
bgColor: bgColor,
container: fullLayout._hoverlayer,
outerContainer: fullLayout._paper.node(),
commonLabelOpts: fullLayout.hoverlabel,
hoverdistance: fullLayout.hoverdistance
});
var hoverLabels = hoverText.hoverLabels;
if (!helpers.isUnifiedHover(hovermode)) {
hoverAvoidOverlaps(hoverLabels, rotateLabels, fullLayout, hoverText.commonLabelBoundingBox);
alignHoverText(hoverLabels, rotateLabels, fullLayout._invScaleX, fullLayout._invScaleY);
} // TODO: tagName hack is needed to appease geo.js's hack of using eventTarget=true
// we should improve the "fx" API so other plots can use it without these hack.
if (eventTarget && eventTarget.tagName) {
var hasClickToShow = Registry.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata);
overrideCursor(d3.select(eventTarget), hasClickToShow ? 'pointer' : '');
}
// don't emit events if called manually
if (!eventTarget || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return;
if (oldhoverdata) {
gd.emit('plotly_unhover', {
event: evt,
points: oldhoverdata
});
}
gd.emit('plotly_hover', {
event: evt,
points: gd._hoverdata,
xaxes: xaArray,
yaxes: yaArray,
xvals: xvalArray,
yvals: yvalArray
});
}
function hoverDataKey(d) {
return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa ? d.xa._id : '', d.ya ? d.ya._id : ''].join(',');
}
var EXTRA_STRING_REGEX = /([\s\S]*)<\/extra>/;
function createHoverText(hoverData, opts) {
var gd = opts.gd;
var fullLayout = gd._fullLayout;
var hovermode = opts.hovermode;
var rotateLabels = opts.rotateLabels;
var bgColor = opts.bgColor;
var container = opts.container;
var outerContainer = opts.outerContainer;
var commonLabelOpts = opts.commonLabelOpts || {};
// Early exit if no labels are drawn
if (hoverData.length === 0) return [[]];
// opts.fontFamily/Size are used for the common label
// and as defaults for each hover label, though the individual labels
// can override this.
var fontFamily = opts.fontFamily || constants.HOVERFONT;
var fontSize = opts.fontSize || constants.HOVERFONTSIZE;
var fontWeight = opts.fontWeight || fullLayout.font.weight;
var fontStyle = opts.fontStyle || fullLayout.font.style;
var fontVariant = opts.fontVariant || fullLayout.font.variant;
var fontTextcase = opts.fontTextcase || fullLayout.font.textcase;
var fontLineposition = opts.fontLineposition || fullLayout.font.lineposition;
var fontShadow = opts.fontShadow || fullLayout.font.shadow;
var c0 = hoverData[0];
var xa = c0.xa;
var ya = c0.ya;
var axLetter = hovermode.charAt(0);
var axLabel = axLetter + 'Label';
var t0 = c0[axLabel];
// search in array for the label
if (t0 === undefined && xa.type === 'multicategory') {
for (var q = 0; q < hoverData.length; q++) {
t0 = hoverData[q][axLabel];
if (t0 !== undefined) break;
}
}
var outerContainerBB = getBoundingClientRect(gd, outerContainer);
var outerTop = outerContainerBB.top;
var outerWidth = outerContainerBB.width;
var outerHeight = outerContainerBB.height;
// show the common label, if any, on the axis
// never show a common label in array mode,
// even if sometimes there could be one
var showCommonLabel = t0 !== undefined && c0.distance <= opts.hoverdistance && (hovermode === 'x' || hovermode === 'y');
// all hover traces hoverinfo must contain the hovermode
// to have common labels
if (showCommonLabel) {
var allHaveZ = true;
var i, traceHoverinfo;
for (i = 0; i < hoverData.length; i++) {
if (allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false;
traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo;
if (traceHoverinfo) {
var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+');
if (parts.indexOf('all') === -1 && parts.indexOf(hovermode) === -1) {
showCommonLabel = false;
break;
}
}
}
// xyz labels put all info in their main label, so have no need of a common label
if (allHaveZ) showCommonLabel = false;
}
var commonLabel = container.selectAll('g.axistext').data(showCommonLabel ? [0] : []);
commonLabel.enter().append('g').classed('axistext', true);
commonLabel.exit().remove();
// set rect (without arrow) behind label below for later collision detection
var commonLabelRect = {
minX: 0,
maxX: 0,
minY: 0,
maxY: 0
};
commonLabel.each(function () {
var label = d3.select(this);
var lpath = Lib.ensureSingle(label, 'path', '', function (s) {
s.style({
'stroke-width': '1px'
});
});
var ltext = Lib.ensureSingle(label, 'text', '', function (s) {
// prohibit tex interpretation until we can handle
// tex and regular text together
s.attr('data-notex', 1);
});
var commonBgColor = commonLabelOpts.bgcolor || Color.defaultLine;
var commonStroke = commonLabelOpts.bordercolor || Color.contrast(commonBgColor);
var contrastColor = Color.contrast(commonBgColor);
var commonLabelOptsFont = commonLabelOpts.font;
var commonLabelFont = {
weight: commonLabelOptsFont.weight || fontWeight,
style: commonLabelOptsFont.style || fontStyle,
variant: commonLabelOptsFont.variant || fontVariant,
textcase: commonLabelOptsFont.textcase || fontTextcase,
lineposition: commonLabelOptsFont.lineposition || fontLineposition,
shadow: commonLabelOptsFont.shadow || fontShadow,
family: commonLabelOptsFont.family || fontFamily,
size: commonLabelOptsFont.size || fontSize,
color: commonLabelOptsFont.color || contrastColor
};
lpath.style({
fill: commonBgColor,
stroke: commonStroke
});
ltext.text(t0).call(Drawing.font, commonLabelFont).call(svgTextUtils.positionText, 0, 0).call(svgTextUtils.convertToTspans, gd);
label.attr('transform', '');
var tbb = getBoundingClientRect(gd, ltext.node());
var lx, ly;
if (hovermode === 'x') {
var topsign = xa.side === 'top' ? '-' : '';
ltext.attr('text-anchor', 'middle').call(svgTextUtils.positionText, 0, xa.side === 'top' ? outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD : outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD);
lx = xa._offset + (c0.x0 + c0.x1) / 2;
ly = ya._offset + (xa.side === 'top' ? 0 : ya._length);
var halfWidth = tbb.width / 2 + HOVERTEXTPAD;
var tooltipMidX = lx;
if (lx < halfWidth) {
tooltipMidX = halfWidth;
} else if (lx > fullLayout.width - halfWidth) {
tooltipMidX = fullLayout.width - halfWidth;
}
lpath.attr('d', 'M' + (lx - tooltipMidX) + ',0' + 'L' + (lx - tooltipMidX + HOVERARROWSIZE) + ',' + topsign + HOVERARROWSIZE + 'H' + halfWidth + 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + 'H' + -halfWidth + 'V' + topsign + HOVERARROWSIZE + 'H' + (lx - tooltipMidX - HOVERARROWSIZE) + 'Z');
lx = tooltipMidX;
commonLabelRect.minX = lx - halfWidth;
commonLabelRect.maxX = lx + halfWidth;
if (xa.side === 'top') {
// label on negative y side
commonLabelRect.minY = ly - (HOVERTEXTPAD * 2 + tbb.height);
commonLabelRect.maxY = ly - HOVERTEXTPAD;
} else {
commonLabelRect.minY = ly + HOVERTEXTPAD;
commonLabelRect.maxY = ly + (HOVERTEXTPAD * 2 + tbb.height);
}
} else {
var anchor;
var sgn;
var leftsign;
if (ya.side === 'right') {
anchor = 'start';
sgn = 1;
leftsign = '';
lx = xa._offset + xa._length;
} else {
anchor = 'end';
sgn = -1;
leftsign = '-';
lx = xa._offset;
}
ly = ya._offset + (c0.y0 + c0.y1) / 2;
ltext.attr('text-anchor', anchor);
lpath.attr('d', 'M0,0' + 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + 'V' + (HOVERTEXTPAD + tbb.height / 2) + 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + 'V-' + (HOVERTEXTPAD + tbb.height / 2) + 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z');
commonLabelRect.minY = ly - (HOVERTEXTPAD + tbb.height / 2);
commonLabelRect.maxY = ly + (HOVERTEXTPAD + tbb.height / 2);
if (ya.side === 'right') {
commonLabelRect.minX = lx + HOVERARROWSIZE;
commonLabelRect.maxX = lx + HOVERARROWSIZE + (HOVERTEXTPAD * 2 + tbb.width);
} else {
// label on negative x side
commonLabelRect.minX = lx - HOVERARROWSIZE - (HOVERTEXTPAD * 2 + tbb.width);
commonLabelRect.maxX = lx - HOVERARROWSIZE;
}
var halfHeight = tbb.height / 2;
var lty = outerTop - tbb.top - halfHeight;
var clipId = 'clip' + fullLayout._uid + 'commonlabel' + ya._id;
var clipPath;
if (lx < tbb.width + 2 * HOVERTEXTPAD + HOVERARROWSIZE) {
clipPath = 'M-' + (HOVERARROWSIZE + HOVERTEXTPAD) + '-' + halfHeight + 'h-' + (tbb.width - HOVERTEXTPAD) + 'V' + halfHeight + 'h' + (tbb.width - HOVERTEXTPAD) + 'Z';
var ltx = tbb.width - lx + HOVERTEXTPAD;
svgTextUtils.positionText(ltext, ltx, lty);
// shift each line (except the longest) so that start-of-line
// is always visible
if (anchor === 'end') {
ltext.selectAll('tspan').each(function () {
var s = d3.select(this);
var dummy = Drawing.tester.append('text').text(s.text()).call(Drawing.font, commonLabelFont);
var dummyBB = getBoundingClientRect(gd, dummy.node());
if (Math.round(dummyBB.width) < Math.round(tbb.width)) {
s.attr('x', ltx - dummyBB.width);
}
dummy.remove();
});
}
} else {
svgTextUtils.positionText(ltext, sgn * (HOVERTEXTPAD + HOVERARROWSIZE), lty);
clipPath = null;
}
var textClip = fullLayout._topclips.selectAll('#' + clipId).data(clipPath ? [0] : []);
textClip.enter().append('clipPath').attr('id', clipId).append('path');
textClip.exit().remove();
textClip.select('path').attr('d', clipPath);
Drawing.setClipUrl(ltext, clipPath ? clipId : null, gd);
}
label.attr('transform', strTranslate(lx, ly));
});
// Show a single hover label
if (helpers.isUnifiedHover(hovermode)) {
// Delete leftover hover labels from other hovermodes
container.selectAll('g.hovertext').remove();
var groupedHoverData = hoverData.filter(function (data) {
return data.hoverinfo !== 'none';
});
// Return early if nothing is hovered on
if (groupedHoverData.length === 0) return [];
// mock legend
var hoverlabel = fullLayout.hoverlabel;
var font = hoverlabel.font;
var mockLayoutIn = {
showlegend: true,
legend: {
title: {
text: t0,
font: font
},
font: font,
bgcolor: hoverlabel.bgcolor,
bordercolor: hoverlabel.bordercolor,
borderwidth: 1,
tracegroupgap: 7,
traceorder: fullLayout.legend ? fullLayout.legend.traceorder : undefined,
orientation: 'v'
}
};
var mockLayoutOut = {
font: font
};
legendSupplyDefaults(mockLayoutIn, mockLayoutOut, gd._fullData);
var mockLegend = mockLayoutOut.legend;
// prepare items for the legend
mockLegend.entries = [];
for (var j = 0; j < groupedHoverData.length; j++) {
var pt = groupedHoverData[j];
if (pt.hoverinfo === 'none') continue;
var texts = getHoverLabelText(pt, true, hovermode, fullLayout, t0);
var text = texts[0];
var name = texts[1];
pt.name = name;
if (name !== '') {
pt.text = name + ' : ' + text;
} else {
pt.text = text;
}
// pass through marker's calcdata to style legend items
var cd = pt.cd[pt.index];
if (cd) {
if (cd.mc) pt.mc = cd.mc;
if (cd.mcc) pt.mc = cd.mcc;
if (cd.mlc) pt.mlc = cd.mlc;
if (cd.mlcc) pt.mlc = cd.mlcc;
if (cd.mlw) pt.mlw = cd.mlw;
if (cd.mrc) pt.mrc = cd.mrc;
if (cd.dir) pt.dir = cd.dir;
}
pt._distinct = true;
mockLegend.entries.push([pt]);
}
mockLegend.entries.sort(function (a, b) {
return a[0].trace.index - b[0].trace.index;
});
mockLegend.layer = container;
// Draw unified hover label
mockLegend._inHover = true;
mockLegend._groupTitleFont = hoverlabel.grouptitlefont;
legendDraw(gd, mockLegend);
// Position the hover
var legendContainer = container.select('g.legend');
var tbb = getBoundingClientRect(gd, legendContainer.node());
var tWidth = tbb.width + 2 * HOVERTEXTPAD;
var tHeight = tbb.height + 2 * HOVERTEXTPAD;
var winningPoint = groupedHoverData[0];
var avgX = (winningPoint.x0 + winningPoint.x1) / 2;
var avgY = (winningPoint.y0 + winningPoint.y1) / 2;
// When a scatter (or e.g. heatmap) point wins, it's OK for the hovelabel to occlude the bar and other points.
var pointWon = !(Registry.traceIs(winningPoint.trace, 'bar-like') || Registry.traceIs(winningPoint.trace, 'box-violin'));
var lyBottom, lyTop;
if (axLetter === 'y') {
if (pointWon) {
lyTop = avgY - HOVERTEXTPAD;
lyBottom = avgY + HOVERTEXTPAD;
} else {
lyTop = Math.min.apply(null, groupedHoverData.map(function (c) {
return Math.min(c.y0, c.y1);
}));
lyBottom = Math.max.apply(null, groupedHoverData.map(function (c) {
return Math.max(c.y0, c.y1);
}));
}
} else {
lyTop = lyBottom = Lib.mean(groupedHoverData.map(function (c) {
return (c.y0 + c.y1) / 2;
})) - tHeight / 2;
}
var lxRight, lxLeft;
if (axLetter === 'x') {
if (pointWon) {
lxRight = avgX + HOVERTEXTPAD;
lxLeft = avgX - HOVERTEXTPAD;
} else {
lxRight = Math.max.apply(null, groupedHoverData.map(function (c) {
return Math.max(c.x0, c.x1);
}));
lxLeft = Math.min.apply(null, groupedHoverData.map(function (c) {
return Math.min(c.x0, c.x1);
}));
}
} else {
lxRight = lxLeft = Lib.mean(groupedHoverData.map(function (c) {
return (c.x0 + c.x1) / 2;
})) - tWidth / 2;
}
var xOffset = xa._offset;
var yOffset = ya._offset;
lyBottom += yOffset;
lxRight += xOffset;
lxLeft += xOffset - tWidth;
lyTop += yOffset - tHeight;
var lx, ly; // top and left positions of the hover box
// horizontal alignment to end up on screen
if (lxRight + tWidth < outerWidth && lxRight >= 0) {
lx = lxRight;
} else if (lxLeft + tWidth < outerWidth && lxLeft >= 0) {
lx = lxLeft;
} else if (xOffset + tWidth < outerWidth) {
lx = xOffset; // subplot left corner
} else {
// closest left or right side of the paper
if (lxRight - avgX < avgX - lxLeft + tWidth) {
lx = outerWidth - tWidth;
} else {
lx = 0;
}
}
lx += HOVERTEXTPAD;
// vertical alignement to end up on screen
if (lyBottom + tHeight < outerHeight && lyBottom >= 0) {
ly = lyBottom;
} else if (lyTop + tHeight < outerHeight && lyTop >= 0) {
ly = lyTop;
} else if (yOffset + tHeight < outerHeight) {
ly = yOffset; // subplot top corner
} else {
// closest top or bottom side of the paper
if (lyBottom - avgY < avgY - lyTop + tHeight) {
ly = outerHeight - tHeight;
} else {
ly = 0;
}
}
ly += HOVERTEXTPAD;
legendContainer.attr('transform', strTranslate(lx - 1, ly - 1));
return legendContainer;
}
// show all the individual labels
// first create the objects
var hoverLabels = container.selectAll('g.hovertext').data(hoverData, function (d) {
// N.B. when multiple items have the same result key-function value,
// only the first of those items in hoverData gets rendered
return hoverDataKey(d);
});
hoverLabels.enter().append('g').classed('hovertext', true).each(function () {
var g = d3.select(this);
// trace name label (rect and text.name)
g.append('rect').call(Color.fill, Color.addOpacity(bgColor, 0.8));
g.append('text').classed('name', true);
// trace data label (path and text.nums)
g.append('path').style('stroke-width', '1px');
g.append('text').classed('nums', true).call(Drawing.font, {
weight: fontWeight,
style: fontStyle,
variant: fontVariant,
textcase: fontTextcase,
lineposition: fontLineposition,
shadow: fontShadow,
family: fontFamily,
size: fontSize
});
});
hoverLabels.exit().remove();
// then put the text in, position the pointer to the data,
// and figure out sizes
hoverLabels.each(function (d) {
var g = d3.select(this).attr('transform', '');
var dColor = d.color;
if (Array.isArray(dColor)) {
dColor = dColor[d.eventData[0].pointNumber];
}
// combine possible non-opaque trace color with bgColor
var color0 = d.bgcolor || dColor;
// color for 'nums' part of the label
var numsColor = Color.combine(Color.opacity(color0) ? color0 : Color.defaultLine, bgColor);
// color for 'name' part of the label
var nameColor = Color.combine(Color.opacity(dColor) ? dColor : Color.defaultLine, bgColor);
// find a contrasting color for border and text
var contrastColor = d.borderColor || Color.contrast(numsColor);
var texts = getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t0, g);
var text = texts[0];
var name = texts[1];
// main label
var tx = g.select('text.nums').call(Drawing.font, {
family: d.fontFamily || fontFamily,
size: d.fontSize || fontSize,
color: d.fontColor || contrastColor,
weight: d.fontWeight || fontWeight,
style: d.fontStyle || fontStyle,
variant: d.fontVariant || fontVariant,
textcase: d.fontTextcase || fontTextcase,
lineposition: d.fontLineposition || fontLineposition,
shadow: d.fontShadow || fontShadow
}).text(text).attr('data-notex', 1).call(svgTextUtils.positionText, 0, 0).call(svgTextUtils.convertToTspans, gd);
var tx2 = g.select('text.name');
var tx2width = 0;
var tx2height = 0;
// secondary label for non-empty 'name'
if (name && name !== text) {
tx2.call(Drawing.font, {
family: d.fontFamily || fontFamily,
size: d.fontSize || fontSize,
color: nameColor,
weight: d.fontWeight || fontWeight,
style: d.fontStyle || fontStyle,
variant: d.fontVariant || fontVariant,
textcase: d.fontTextcase || fontTextcase,
lineposition: d.fontLineposition || fontLineposition,
shadow: d.fontShadow || fontShadow
}).text(name).attr('data-notex', 1).call(svgTextUtils.positionText, 0, 0).call(svgTextUtils.convertToTspans, gd);
var t2bb = getBoundingClientRect(gd, tx2.node());
tx2width = t2bb.width + 2 * HOVERTEXTPAD;
tx2height = t2bb.height + 2 * HOVERTEXTPAD;
} else {
tx2.remove();
g.select('rect').remove();
}
g.select('path').style({
fill: numsColor,
stroke: contrastColor
});
var htx = d.xa._offset + (d.x0 + d.x1) / 2;
var hty = d.ya._offset + (d.y0 + d.y1) / 2;
var dx = Math.abs(d.x1 - d.x0);
var dy = Math.abs(d.y1 - d.y0);
var tbb = getBoundingClientRect(gd, tx.node());
var tbbWidth = tbb.width / fullLayout._invScaleX;
var tbbHeight = tbb.height / fullLayout._invScaleY;
d.ty0 = (outerTop - tbb.top) / fullLayout._invScaleY;
d.bx = tbbWidth + 2 * HOVERTEXTPAD;
d.by = Math.max(tbbHeight + 2 * HOVERTEXTPAD, tx2height);
d.anchor = 'start';
d.txwidth = tbbWidth;
d.tx2width = tx2width;
d.offset = 0;
var txTotalWidth = (tbbWidth + HOVERARROWSIZE + HOVERTEXTPAD + tx2width) * fullLayout._invScaleX;
var anchorStartOK, anchorEndOK;
if (rotateLabels) {
d.pos = htx;
anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
if ((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) {
hty -= dy / 2;
d.anchor = 'end';
} else if (anchorStartOK) {
hty += dy / 2;
d.anchor = 'start';
} else {
d.anchor = 'middle';
}
d.crossPos = hty;
} else {
d.pos = hty;
anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
if ((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) {
htx -= dx / 2;
d.anchor = 'end';
} else if (anchorStartOK) {
htx += dx / 2;
d.anchor = 'start';
} else {
d.anchor = 'middle';
var txHalfWidth = txTotalWidth / 2;
var overflowR = htx + txHalfWidth - outerWidth;
var overflowL = htx - txHalfWidth;
if (overflowR > 0) htx -= overflowR;
if (overflowL < 0) htx += -overflowL;
}
d.crossPos = htx;
}
tx.attr('text-anchor', d.anchor);
if (tx2width) tx2.attr('text-anchor', d.anchor);
g.attr('transform', strTranslate(htx, hty) + (rotateLabels ? strRotate(YANGLE) : ''));
});
return {
hoverLabels: hoverLabels,
commonLabelBoundingBox: commonLabelRect
};
}
function getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t0, g) {
var name = '';
var text = '';
// to get custom 'name' labels pass cleanPoint
if (d.nameOverride !== undefined) d.name = d.nameOverride;
if (d.name) {
if (d.trace._meta) {
d.name = Lib.templateString(d.name, d.trace._meta);
}
name = plainText(d.name, d.nameLength);
}
var h0 = hovermode.charAt(0);
var h1 = h0 === 'x' ? 'y' : 'x';
if (d.zLabel !== undefined) {
if (d.xLabel !== undefined) text += 'x: ' + d.xLabel + ' ';
if (d.yLabel !== undefined) text += 'y: ' + d.yLabel + ' ';
if (d.trace.type !== 'choropleth' && d.trace.type !== 'choroplethmapbox') {
text += (text ? 'z: ' : '') + d.zLabel;
}
} else if (showCommonLabel && d[h0 + 'Label'] === t0) {
text = d[h1 + 'Label'] || '';
} else if (d.xLabel === undefined) {
if (d.yLabel !== undefined && d.trace.type !== 'scattercarpet') {
text = d.yLabel;
}
} else if (d.yLabel === undefined) text = d.xLabel;else text = '(' + d.xLabel + ', ' + d.yLabel + ')';
if ((d.text || d.text === 0) && !Array.isArray(d.text)) {
text += (text ? ' ' : '') + d.text;
}
// used by other modules (initially just ternary) that
// manage their own hoverinfo independent of cleanPoint
// the rest of this will still apply, so such modules
// can still put things in (x|y|z)Label, text, and name
// and hoverinfo will still determine their visibility
if (d.extraText !== undefined) text += (text ? ' ' : '') + d.extraText;
// if 'text' is empty at this point,
// and hovertemplate is not defined,
// put 'name' in main label and don't show secondary label
if (g && text === '' && !d.hovertemplate) {
// if 'name' is also empty, remove entire label
if (name === '') g.remove();
text = name;
}
// hovertemplate
var hovertemplate = d.hovertemplate || false;
if (hovertemplate) {
var labels = d.hovertemplateLabels || d;
if (d[h0 + 'Label'] !== t0) {
labels[h0 + 'other'] = labels[h0 + 'Val'];
labels[h0 + 'otherLabel'] = labels[h0 + 'Label'];
}
text = Lib.hovertemplateString(hovertemplate, labels, fullLayout._d3locale, d.eventData[0] || {}, d.trace._meta);
text = text.replace(EXTRA_STRING_REGEX, function (match, extra) {
// assign name for secondary text label
name = plainText(extra, d.nameLength);
// remove from main text label
return '';
});
}
return [text, name];
}
// Make groups of touching points, and within each group
// move each point so that no labels overlap, but the average
// label position is the same as it was before moving. Incidentally,
// this is equivalent to saying all the labels are on equal linear
// springs about their initial position. Initially, each point is
// its own group, but as we find overlaps we will clump the points.
//
// Also, there are hard constraints at the edges of the graphs,
// that push all groups to the middle so they are visible. I don't
// know what happens if the group spans all the way from one edge to
// the other, though it hardly matters - there's just too much
// information then.
function hoverAvoidOverlaps(hoverLabels, rotateLabels, fullLayout, commonLabelBoundingBox) {
var axKey = rotateLabels ? 'xa' : 'ya';
var crossAxKey = rotateLabels ? 'ya' : 'xa';
var nummoves = 0;
var axSign = 1;
var nLabels = hoverLabels.size();
// make groups of touching points
var pointgroups = new Array(nLabels);
var k = 0;
// get extent of axis hover label
var axisLabelMinX = commonLabelBoundingBox.minX;
var axisLabelMaxX = commonLabelBoundingBox.maxX;
var axisLabelMinY = commonLabelBoundingBox.minY;
var axisLabelMaxY = commonLabelBoundingBox.maxY;
var pX = function (x) {
return x * fullLayout._invScaleX;
};
var pY = function (y) {
return y * fullLayout._invScaleY;
};
hoverLabels.each(function (d) {
var ax = d[axKey];
var crossAx = d[crossAxKey];
var axIsX = ax._id.charAt(0) === 'x';
var rng = ax.range;
if (k === 0 && rng && rng[0] > rng[1] !== axIsX) {
axSign = -1;
}
var pmin = 0;
var pmax = axIsX ? fullLayout.width : fullLayout.height;
// in hovermode avoid overlap between hover labels and axis label
if (fullLayout.hovermode === 'x' || fullLayout.hovermode === 'y') {
// extent of rect behind hover label on cross axis:
var offsets = getHoverLabelOffsets(d, rotateLabels);
var anchor = d.anchor;
var horzSign = anchor === 'end' ? -1 : 1;
var labelMin;
var labelMax;
if (anchor === 'middle') {
// use extent of centered rect either on x or y axis depending on current axis
labelMin = d.crossPos + (axIsX ? pY(offsets.y - d.by / 2) : pX(d.bx / 2 + d.tx2width / 2));
labelMax = labelMin + (axIsX ? pY(d.by) : pX(d.bx));
} else {
// use extend of path (see alignHoverText function) without arrow
if (axIsX) {
labelMin = d.crossPos + pY(HOVERARROWSIZE + offsets.y) - pY(d.by / 2 - HOVERARROWSIZE);
labelMax = labelMin + pY(d.by);
} else {
var startX = pX(horzSign * HOVERARROWSIZE + offsets.x);
var endX = startX + pX(horzSign * d.bx);
labelMin = d.crossPos + Math.min(startX, endX);
labelMax = d.crossPos + Math.max(startX, endX);
}
}
if (axIsX) {
if (axisLabelMinY !== undefined && axisLabelMaxY !== undefined && Math.min(labelMax, axisLabelMaxY) - Math.max(labelMin, axisLabelMinY) > 1) {
// has at least 1 pixel overlap with axis label
if (crossAx.side === 'left') {
pmin = crossAx._mainLinePosition;
pmax = fullLayout.width;
} else {
pmax = crossAx._mainLinePosition;
}
}
} else {
if (axisLabelMinX !== undefined && axisLabelMaxX !== undefined && Math.min(labelMax, axisLabelMaxX) - Math.max(labelMin, axisLabelMinX) > 1) {
// has at least 1 pixel overlap with axis label
if (crossAx.side === 'top') {
pmin = crossAx._mainLinePosition;
pmax = fullLayout.height;
} else {
pmax = crossAx._mainLinePosition;
}
}
}
}
pointgroups[k++] = [{
datum: d,
traceIndex: d.trace.index,
dp: 0,
pos: d.pos,
posref: d.posref,
size: d.by * (axIsX ? YFACTOR : 1) / 2,
pmin: pmin,
pmax: pmax
}];
});
pointgroups.sort(function (a, b) {
return a[0].posref - b[0].posref ||
// for equal positions, sort trace indices increasing or decreasing
// depending on whether the axis is reversed or not... so stacked
// traces will generally keep their order even if one trace adds
// nothing to the stack.
axSign * (b[0].traceIndex - a[0].traceIndex);
});
var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp;
function constrainGroup(grp) {
var minPt = grp[0];
var maxPt = grp[grp.length - 1];
// overlap with the top - positive vals are overlaps
topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size;
// overlap with the bottom - positive vals are overlaps
bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax;
// check for min overlap first, so that we always
// see the largest labels
// allow for .01px overlap, so we don't get an
// infinite loop from rounding errors
if (topOverlap > 0.01) {
for (j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap;
donepositioning = false;
}
if (bottomOverlap < 0.01) return;
if (topOverlap < -0.01) {
// make sure we're not pushing back and forth
for (j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
donepositioning = false;
}
if (!donepositioning) return;
// no room to fix positioning, delete off-screen points
// first see how many points we need to delete
var deleteCount = 0;
for (i = 0; i < grp.length; i++) {
pti = grp[i];
if (pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++;
}
// start by deleting points whose data is off screen
for (i = grp.length - 1; i >= 0; i--) {
if (deleteCount <= 0) break;
pti = grp[i];
// pos has already been constrained to [pmin,pmax]
// so look for points close to that to delete
if (pti.pos > minPt.pmax - 1) {
pti.del = true;
deleteCount--;
}
}
for (i = 0; i < grp.length; i++) {
if (deleteCount <= 0) break;
pti = grp[i];
// pos has already been constrained to [pmin,pmax]
// so look for points close to that to delete
if (pti.pos < minPt.pmin + 1) {
pti.del = true;
deleteCount--;
// shift the whole group minus into this new space
bottomOverlap = pti.size * 2;
for (j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
}
}
// then delete points that go off the bottom
for (i = grp.length - 1; i >= 0; i--) {
if (deleteCount <= 0) break;
pti = grp[i];
if (pti.pos + pti.dp + pti.size > minPt.pmax) {
pti.del = true;
deleteCount--;
}
}
}
// loop through groups, combining them if they overlap,
// until nothing moves
while (!donepositioning && nummoves <= nLabels) {
// to avoid infinite loops, don't move more times
// than there are traces
nummoves++;
// assume nothing will move in this iteration,
// reverse this if it does
donepositioning = true;
i = 0;
while (i < pointgroups.length - 1) {
// the higher (g0) and lower (g1) point group
var g0 = pointgroups[i];
var g1 = pointgroups[i + 1];
// the lowest point in the higher group (p0)
// the highest point in the lower group (p1)
var p0 = g0[g0.length - 1];
var p1 = g1[0];
topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size;
if (topOverlap > 0.01) {
// push the new point(s) added to this group out of the way
for (j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap;
// add them to the group
g0.push.apply(g0, g1);
pointgroups.splice(i + 1, 1);
// adjust for minimum average movement
sumdp = 0;
for (j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp;
bottomOverlap = sumdp / g0.length;
for (j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap;
donepositioning = false;
} else i++;
}
// check if we're going off the plot on either side and fix
pointgroups.forEach(constrainGroup);
}
// now put these offsets into hoverData
for (i = pointgroups.length - 1; i >= 0; i--) {
var grp = pointgroups[i];
for (j = grp.length - 1; j >= 0; j--) {
var pt = grp[j];
var hoverPt = pt.datum;
hoverPt.offset = pt.dp;
hoverPt.del = pt.del;
}
}
}
function getHoverLabelOffsets(hoverLabel, rotateLabels) {
var offsetX = 0;
var offsetY = hoverLabel.offset;
if (rotateLabels) {
offsetY *= -YSHIFTY;
offsetX = hoverLabel.offset * YSHIFTX;
}
return {
x: offsetX,
y: offsetY
};
}
/**
* Calculate the shift in x for text and text2 elements
*/
function getTextShiftX(hoverLabel) {
var alignShift = {
start: 1,
end: -1,
middle: 0
}[hoverLabel.anchor];
var textShiftX = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD);
var text2ShiftX = textShiftX + alignShift * (hoverLabel.txwidth + HOVERTEXTPAD);
var isMiddle = hoverLabel.anchor === 'middle';
if (isMiddle) {
textShiftX -= hoverLabel.tx2width / 2;
text2ShiftX += hoverLabel.txwidth / 2 + HOVERTEXTPAD;
}
return {
alignShift: alignShift,
textShiftX: textShiftX,
text2ShiftX: text2ShiftX
};
}
function alignHoverText(hoverLabels, rotateLabels, scaleX, scaleY) {
var pX = function (x) {
return x * scaleX;
};
var pY = function (y) {
return y * scaleY;
};
// finally set the text positioning relative to the data and draw the
// box around it
hoverLabels.each(function (d) {
var g = d3.select(this);
if (d.del) return g.remove();
var tx = g.select('text.nums');
var anchor = d.anchor;
var horzSign = anchor === 'end' ? -1 : 1;
var shiftX = getTextShiftX(d);
var offsets = getHoverLabelOffsets(d, rotateLabels);
var offsetX = offsets.x;
var offsetY = offsets.y;
var isMiddle = anchor === 'middle';
g.select('path').attr('d', isMiddle ?
// middle aligned: rect centered on data
'M-' + pX(d.bx / 2 + d.tx2width / 2) + ',' + pY(offsetY - d.by / 2) + 'h' + pX(d.bx) + 'v' + pY(d.by) + 'h-' + pX(d.bx) + 'Z' :
// left or right aligned: side rect with arrow to data
'M0,0L' + pX(horzSign * HOVERARROWSIZE + offsetX) + ',' + pY(HOVERARROWSIZE + offsetY) + 'v' + pY(d.by / 2 - HOVERARROWSIZE) + 'h' + pX(horzSign * d.bx) + 'v-' + pY(d.by) + 'H' + pX(horzSign * HOVERARROWSIZE + offsetX) + 'V' + pY(offsetY - HOVERARROWSIZE) + 'Z');
var posX = offsetX + shiftX.textShiftX;
var posY = offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD;
var textAlign = d.textAlign || 'auto';
if (textAlign !== 'auto') {
if (textAlign === 'left' && anchor !== 'start') {
tx.attr('text-anchor', 'start');
posX = isMiddle ? -d.bx / 2 - d.tx2width / 2 + HOVERTEXTPAD : -d.bx - HOVERTEXTPAD;
} else if (textAlign === 'right' && anchor !== 'end') {
tx.attr('text-anchor', 'end');
posX = isMiddle ? d.bx / 2 - d.tx2width / 2 - HOVERTEXTPAD : d.bx + HOVERTEXTPAD;
}
}
tx.call(svgTextUtils.positionText, pX(posX), pY(posY));
if (d.tx2width) {
g.select('text.name').call(svgTextUtils.positionText, pX(shiftX.text2ShiftX + shiftX.alignShift * HOVERTEXTPAD + offsetX), pY(offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD));
g.select('rect').call(Drawing.setRect, pX(shiftX.text2ShiftX + (shiftX.alignShift - 1) * d.tx2width / 2 + offsetX), pY(offsetY - d.by / 2 - 1), pX(d.tx2width), pY(d.by + 2));
}
});
}
function cleanPoint(d, hovermode) {
var index = d.index;
var trace = d.trace || {};
var cd0 = d.cd[0];
var cd = d.cd[index] || {};
function pass(v) {
return v || isNumeric(v) && v === 0;
}
var getVal = Array.isArray(index) ? function (calcKey, traceKey) {
var v = Lib.castOption(cd0, index, calcKey);
return pass(v) ? v : Lib.extractOption({}, trace, '', traceKey);
} : function (calcKey, traceKey) {
return Lib.extractOption(cd, trace, calcKey, traceKey);
};
function fill(key, calcKey, traceKey) {
var val = getVal(calcKey, traceKey);
if (pass(val)) d[key] = val;
}
fill('hoverinfo', 'hi', 'hoverinfo');
fill('bgcolor', 'hbg', 'hoverlabel.bgcolor');
fill('borderColor', 'hbc', 'hoverlabel.bordercolor');
fill('fontFamily', 'htf', 'hoverlabel.font.family');
fill('fontSize', 'hts', 'hoverlabel.font.size');
fill('fontColor', 'htc', 'hoverlabel.font.color');
fill('fontWeight', 'htw', 'hoverlabel.font.weight');
fill('fontStyle', 'hty', 'hoverlabel.font.style');
fill('fontVariant', 'htv', 'hoverlabel.font.variant');
fill('nameLength', 'hnl', 'hoverlabel.namelength');
fill('textAlign', 'hta', 'hoverlabel.align');
d.posref = hovermode === 'y' || hovermode === 'closest' && trace.orientation === 'h' ? d.xa._offset + (d.x0 + d.x1) / 2 : d.ya._offset + (d.y0 + d.y1) / 2;
// then constrain all the positions to be on the plot
d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
d.y1 = Lib.constrain(d.y1, 0, d.ya._length);
// and convert the x and y label values into formatted text
if (d.xLabelVal !== undefined) {
d.xLabel = 'xLabel' in d ? d.xLabel : Axes.hoverLabelText(d.xa, d.xLabelVal, trace.xhoverformat);
d.xVal = d.xa.c2d(d.xLabelVal);
}
if (d.yLabelVal !== undefined) {
d.yLabel = 'yLabel' in d ? d.yLabel : Axes.hoverLabelText(d.ya, d.yLabelVal, trace.yhoverformat);
d.yVal = d.ya.c2d(d.yLabelVal);
}
// Traces like heatmaps generate the zLabel in their hoverPoints function
if (d.zLabelVal !== undefined && d.zLabel === undefined) {
d.zLabel = String(d.zLabelVal);
}
// for box means and error bars, add the range to the label
if (!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) {
var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
if (d.xerrneg !== undefined) {
d.xLabel += ' +' + xeText + ' / -' + Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
} else d.xLabel += ' ± ' + xeText;
// small distance penalty for error bars, so that if there are
// traces with errors and some without, the error bar label will
// hoist up to the point
if (hovermode === 'x') d.distance += 1;
}
if (!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) {
var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
if (d.yerrneg !== undefined) {
d.yLabel += ' +' + yeText + ' / -' + Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
} else d.yLabel += ' ± ' + yeText;
if (hovermode === 'y') d.distance += 1;
}
var infomode = d.hoverinfo || d.trace.hoverinfo;
if (infomode && infomode !== 'all') {
infomode = Array.isArray(infomode) ? infomode : infomode.split('+');
if (infomode.indexOf('x') === -1) d.xLabel = undefined;
if (infomode.indexOf('y') === -1) d.yLabel = undefined;
if (infomode.indexOf('z') === -1) d.zLabel = undefined;
if (infomode.indexOf('text') === -1) d.text = undefined;
if (infomode.indexOf('name') === -1) d.name = undefined;
}
return d;
}
function createSpikelines(gd, closestPoints, opts) {
var container = opts.container;
var fullLayout = opts.fullLayout;
var gs = fullLayout._size;
var evt = opts.event;
var showY = !!closestPoints.hLinePoint;
var showX = !!closestPoints.vLinePoint;
var xa, ya;
// Remove old spikeline items
container.selectAll('.spikeline').remove();
if (!(showX || showY)) return;
var contrastColor = Color.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor);
// Horizontal line (to y-axis)
if (showY) {
var hLinePoint = closestPoints.hLinePoint;
var hLinePointX, hLinePointY;
xa = hLinePoint && hLinePoint.xa;
ya = hLinePoint && hLinePoint.ya;
var ySnap = ya.spikesnap;
if (ySnap === 'cursor') {
hLinePointX = evt.pointerX;
hLinePointY = evt.pointerY;
} else {
hLinePointX = xa._offset + hLinePoint.x;
hLinePointY = ya._offset + hLinePoint.y;
}
var dfltHLineColor = tinycolor.readability(hLinePoint.color, contrastColor) < 1.5 ? Color.contrast(contrastColor) : hLinePoint.color;
var yMode = ya.spikemode;
var yThickness = ya.spikethickness;
var yColor = ya.spikecolor || dfltHLineColor;
var xEdge = Axes.getPxPosition(gd, ya);
var xBase, xEndSpike;
if (yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) {
if (yMode.indexOf('toaxis') !== -1) {
xBase = xEdge;
xEndSpike = hLinePointX;
}
if (yMode.indexOf('across') !== -1) {
var xAcross0 = ya._counterDomainMin;
var xAcross1 = ya._counterDomainMax;
if (ya.anchor === 'free') {
xAcross0 = Math.min(xAcross0, ya.position);
xAcross1 = Math.max(xAcross1, ya.position);
}
xBase = gs.l + xAcross0 * gs.w;
xEndSpike = gs.l + xAcross1 * gs.w;
}
// Foreground horizontal line (to y-axis)
container.insert('line', ':first-child').attr({
x1: xBase,
x2: xEndSpike,
y1: hLinePointY,
y2: hLinePointY,
'stroke-width': yThickness,
stroke: yColor,
'stroke-dasharray': Drawing.dashStyle(ya.spikedash, yThickness)
}).classed('spikeline', true).classed('crisp', true);
// Background horizontal Line (to y-axis)
container.insert('line', ':first-child').attr({
x1: xBase,
x2: xEndSpike,
y1: hLinePointY,
y2: hLinePointY,
'stroke-width': yThickness + 2,
stroke: contrastColor
}).classed('spikeline', true).classed('crisp', true);
}
// Y axis marker
if (yMode.indexOf('marker') !== -1) {
container.insert('circle', ':first-child').attr({
cx: xEdge + (ya.side !== 'right' ? yThickness : -yThickness),
cy: hLinePointY,
r: yThickness,
fill: yColor
}).classed('spikeline', true);
}
}
if (showX) {
var vLinePoint = closestPoints.vLinePoint;
var vLinePointX, vLinePointY;
xa = vLinePoint && vLinePoint.xa;
ya = vLinePoint && vLinePoint.ya;
var xSnap = xa.spikesnap;
if (xSnap === 'cursor') {
vLinePointX = evt.pointerX;
vLinePointY = evt.pointerY;
} else {
vLinePointX = xa._offset + vLinePoint.x;
vLinePointY = ya._offset + vLinePoint.y;
}
var dfltVLineColor = tinycolor.readability(vLinePoint.color, contrastColor) < 1.5 ? Color.contrast(contrastColor) : vLinePoint.color;
var xMode = xa.spikemode;
var xThickness = xa.spikethickness;
var xColor = xa.spikecolor || dfltVLineColor;
var yEdge = Axes.getPxPosition(gd, xa);
var yBase, yEndSpike;
if (xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) {
if (xMode.indexOf('toaxis') !== -1) {
yBase = yEdge;
yEndSpike = vLinePointY;
}
if (xMode.indexOf('across') !== -1) {
var yAcross0 = xa._counterDomainMin;
var yAcross1 = xa._counterDomainMax;
if (xa.anchor === 'free') {
yAcross0 = Math.min(yAcross0, xa.position);
yAcross1 = Math.max(yAcross1, xa.position);
}
yBase = gs.t + (1 - yAcross1) * gs.h;
yEndSpike = gs.t + (1 - yAcross0) * gs.h;
}
// Foreground vertical line (to x-axis)
container.insert('line', ':first-child').attr({
x1: vLinePointX,
x2: vLinePointX,
y1: yBase,
y2: yEndSpike,
'stroke-width': xThickness,
stroke: xColor,
'stroke-dasharray': Drawing.dashStyle(xa.spikedash, xThickness)
}).classed('spikeline', true).classed('crisp', true);
// Background vertical line (to x-axis)
container.insert('line', ':first-child').attr({
x1: vLinePointX,
x2: vLinePointX,
y1: yBase,
y2: yEndSpike,
'stroke-width': xThickness + 2,
stroke: contrastColor
}).classed('spikeline', true).classed('crisp', true);
}
// X axis marker
if (xMode.indexOf('marker') !== -1) {
container.insert('circle', ':first-child').attr({
cx: vLinePointX,
cy: yEdge - (xa.side !== 'top' ? xThickness : -xThickness),
r: xThickness,
fill: xColor
}).classed('spikeline', true);
}
}
}
function hoverChanged(gd, evt, oldhoverdata) {
// don't emit any events if nothing changed
if (!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true;
for (var i = oldhoverdata.length - 1; i >= 0; i--) {
var oldPt = oldhoverdata[i];
var newPt = gd._hoverdata[i];
if (oldPt.curveNumber !== newPt.curveNumber || String(oldPt.pointNumber) !== String(newPt.pointNumber) || String(oldPt.pointNumbers) !== String(newPt.pointNumbers)) {
return true;
}
}
return false;
}
function spikesChanged(gd, oldspikepoints) {
// don't relayout the plot because of new spikelines if spikelines points didn't change
if (!oldspikepoints) return true;
if (oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint) return true;
return false;
}
function plainText(s, len) {
return svgTextUtils.plainText(s || '', {
len: len,
allowedTags: ['br', 'sub', 'sup', 'b', 'i', 'em', 's', 'u']
});
}
function orderRangePoints(hoverData, hovermode) {
var axLetter = hovermode.charAt(0);
var first = [];
var second = [];
var last = [];
for (var i = 0; i < hoverData.length; i++) {
var d = hoverData[i];
if (Registry.traceIs(d.trace, 'bar-like') || Registry.traceIs(d.trace, 'box-violin')) {
last.push(d);
} else if (d.trace[axLetter + 'period']) {
second.push(d);
} else {
first.push(d);
}
}
return first.concat(second).concat(last);
}
function getCoord(axLetter, winningPoint, fullLayout) {
var ax = winningPoint[axLetter + 'a'];
var val = winningPoint[axLetter + 'Val'];
var cd0 = winningPoint.cd[0];
if (ax.type === 'category' || ax.type === 'multicategory') val = ax._categoriesMap[val];else if (ax.type === 'date') {
var periodalignment = winningPoint.trace[axLetter + 'periodalignment'];
if (periodalignment) {
var d = winningPoint.cd[winningPoint.index];
var start = d[axLetter + 'Start'];
if (start === undefined) start = d[axLetter];
var end = d[axLetter + 'End'];
if (end === undefined) end = d[axLetter];
var diff = end - start;
if (periodalignment === 'end') {
val += diff;
} else if (periodalignment === 'middle') {
val += diff / 2;
}
}
val = ax.d2c(val);
}
if (cd0 && cd0.t && cd0.t.posLetter === ax._id) {
if (fullLayout.boxmode === 'group' || fullLayout.violinmode === 'group') {
val += cd0.t.dPos;
}
}
return val;
}
// Top/left hover offsets relative to graph div. As long as hover content is
// a sibling of the graph div, it will be positioned correctly relative to
// the offset parent, whatever that may be.
function getTopOffset(gd) {
return gd.offsetTop + gd.clientTop;
}
function getLeftOffset(gd) {
return gd.offsetLeft + gd.clientLeft;
}
function getBoundingClientRect(gd, node) {
var fullLayout = gd._fullLayout;
var rect = node.getBoundingClientRect();
var x0 = rect.left;
var y0 = rect.top;
var x1 = x0 + rect.width;
var y1 = y0 + rect.height;
var A = Lib.apply3DTransform(fullLayout._invTransform)(x0, y0);
var B = Lib.apply3DTransform(fullLayout._invTransform)(x1, y1);
var Ax = A[0];
var Ay = A[1];
var Bx = B[0];
var By = B[1];
return {
x: Ax,
y: Ay,
width: Bx - Ax,
height: By - Ay,
top: Math.min(Ay, By),
left: Math.min(Ax, Bx),
right: Math.max(Ax, Bx),
bottom: Math.max(Ay, By)
};
}
/***/ }),
/***/ 16132:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var isUnifiedHover = (__webpack_require__(10624).isUnifiedHover);
module.exports = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) {
opts = opts || {};
var hasLegend = contOut.legend;
function inheritFontAttr(attr) {
if (!opts.font[attr]) {
opts.font[attr] = hasLegend ? contOut.legend.font[attr] : contOut.font[attr];
}
}
// In unified hover, inherit from layout.legend if available or layout
if (contOut && isUnifiedHover(contOut.hovermode)) {
if (!opts.font) opts.font = {};
inheritFontAttr('size');
inheritFontAttr('family');
inheritFontAttr('color');
inheritFontAttr('weight');
inheritFontAttr('style');
inheritFontAttr('variant');
if (hasLegend) {
if (!opts.bgcolor) opts.bgcolor = Color.combine(contOut.legend.bgcolor, contOut.paper_bgcolor);
if (!opts.bordercolor) opts.bordercolor = contOut.legend.bordercolor;
} else {
if (!opts.bgcolor) opts.bgcolor = contOut.paper_bgcolor;
}
}
coerce('hoverlabel.bgcolor', opts.bgcolor);
coerce('hoverlabel.bordercolor', opts.bordercolor);
coerce('hoverlabel.namelength', opts.namelength);
Lib.coerceFont(coerce, 'hoverlabel.font', opts.font);
coerce('hoverlabel.align', opts.align);
};
/***/ }),
/***/ 41008:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(65460);
module.exports = function handleHoverModeDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
// don't coerce if it is already coerced in other place e.g. in cartesian defaults
if (layoutOut[attr] !== undefined) return layoutOut[attr];
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
coerce('clickmode');
coerce('hoversubplots');
return coerce('hovermode');
};
/***/ }),
/***/ 93024:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var dragElement = __webpack_require__(86476);
var helpers = __webpack_require__(10624);
var layoutAttributes = __webpack_require__(65460);
var hoverModule = __webpack_require__(83292);
module.exports = {
moduleType: 'component',
name: 'fx',
constants: __webpack_require__(92456),
schema: {
layout: layoutAttributes
},
attributes: __webpack_require__(55756),
layoutAttributes: layoutAttributes,
supplyLayoutGlobalDefaults: __webpack_require__(81976),
supplyDefaults: __webpack_require__(95448),
supplyLayoutDefaults: __webpack_require__(88336),
calc: __webpack_require__(55056),
getDistanceFunction: helpers.getDistanceFunction,
getClosest: helpers.getClosest,
inbox: helpers.inbox,
quadrature: helpers.quadrature,
appendArrayPointValue: helpers.appendArrayPointValue,
castHoverOption: castHoverOption,
castHoverinfo: castHoverinfo,
hover: hoverModule.hover,
unhover: dragElement.unhover,
loneHover: hoverModule.loneHover,
loneUnhover: loneUnhover,
click: __webpack_require__(62376)
};
function loneUnhover(containerOrSelection) {
// duck type whether the arg is a d3 selection because ie9 doesn't
// handle instanceof like modern browsers do.
var selection = Lib.isD3Selection(containerOrSelection) ? containerOrSelection : d3.select(containerOrSelection);
selection.selectAll('g.hovertext').remove();
selection.selectAll('.spikeline').remove();
}
// helpers for traces that use Fx.loneHover
function castHoverOption(trace, ptNumber, attr) {
return Lib.castOption(trace, ptNumber, 'hoverlabel.' + attr);
}
function castHoverinfo(trace, fullLayout, ptNumber) {
function _coerce(val) {
return Lib.coerceHoverinfo({
hoverinfo: val
}, {
_module: trace._module
}, fullLayout);
}
return Lib.castOption(trace, ptNumber, 'hoverinfo', _coerce);
}
/***/ }),
/***/ 65460:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(92456);
var fontAttrs = __webpack_require__(25376);
var font = fontAttrs({
editType: 'none'
});
font.family.dflt = constants.HOVERFONT;
font.size.dflt = constants.HOVERFONTSIZE;
module.exports = {
clickmode: {
valType: 'flaglist',
flags: ['event', 'select'],
dflt: 'event',
editType: 'plot',
extras: ['none']
},
dragmode: {
valType: 'enumerated',
values: ['zoom', 'pan', 'select', 'lasso', 'drawclosedpath', 'drawopenpath', 'drawline', 'drawrect', 'drawcircle', 'orbit', 'turntable', false],
dflt: 'zoom',
editType: 'modebar'
},
hovermode: {
valType: 'enumerated',
values: ['x', 'y', 'closest', false, 'x unified', 'y unified'],
dflt: 'closest',
editType: 'modebar'
},
hoversubplots: {
valType: 'enumerated',
values: ['single', 'overlaying', 'axis'],
dflt: 'overlaying',
editType: 'none'
},
hoverdistance: {
valType: 'integer',
min: -1,
dflt: 20,
editType: 'none'
},
spikedistance: {
valType: 'integer',
min: -1,
dflt: -1,
editType: 'none'
},
hoverlabel: {
bgcolor: {
valType: 'color',
editType: 'none'
},
bordercolor: {
valType: 'color',
editType: 'none'
},
font: font,
grouptitlefont: fontAttrs({
editType: 'none'
}),
align: {
valType: 'enumerated',
values: ['left', 'right', 'auto'],
dflt: 'auto',
editType: 'none'
},
namelength: {
valType: 'integer',
min: -1,
dflt: 15,
editType: 'none'
},
editType: 'none'
},
selectdirection: {
valType: 'enumerated',
values: ['h', 'v', 'd', 'any'],
dflt: 'any',
editType: 'none'
}
};
/***/ }),
/***/ 88336:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(65460);
var handleHoverModeDefaults = __webpack_require__(41008);
var handleHoverLabelDefaults = __webpack_require__(16132);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
var hoverMode = handleHoverModeDefaults(layoutIn, layoutOut);
if (hoverMode) {
coerce('hoverdistance');
coerce('spikedistance');
}
var dragMode = coerce('dragmode');
if (dragMode === 'select') coerce('selectdirection');
// if only mapbox or geo subplots is present on graph,
// reset 'zoom' dragmode to 'pan' until 'zoom' is implemented,
// so that the correct modebar button is active
var hasMapbox = layoutOut._has('mapbox');
var hasGeo = layoutOut._has('geo');
var len = layoutOut._basePlotModules.length;
if (layoutOut.dragmode === 'zoom' && ((hasMapbox || hasGeo) && len === 1 || hasMapbox && hasGeo && len === 2)) {
layoutOut.dragmode = 'pan';
}
handleHoverLabelDefaults(layoutIn, layoutOut, coerce);
Lib.coerceFont(coerce, 'hoverlabel.grouptitlefont', layoutOut.hoverlabel.font);
};
/***/ }),
/***/ 81976:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleHoverLabelDefaults = __webpack_require__(16132);
var layoutAttributes = __webpack_require__(65460);
module.exports = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
handleHoverLabelDefaults(layoutIn, layoutOut, coerce);
};
/***/ }),
/***/ 12704:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var counterRegex = (__webpack_require__(53756).counter);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var cartesianIdRegex = (__webpack_require__(33816).idRegex);
var Template = __webpack_require__(31780);
var gridAttrs = {
rows: {
valType: 'integer',
min: 1,
editType: 'plot'
},
roworder: {
valType: 'enumerated',
values: ['top to bottom', 'bottom to top'],
dflt: 'top to bottom',
editType: 'plot'
},
columns: {
valType: 'integer',
min: 1,
editType: 'plot'
},
subplots: {
valType: 'info_array',
freeLength: true,
dimensions: 2,
items: {
valType: 'enumerated',
values: [counterRegex('xy').toString(), ''],
editType: 'plot'
},
editType: 'plot'
},
xaxes: {
valType: 'info_array',
freeLength: true,
items: {
valType: 'enumerated',
values: [cartesianIdRegex.x.toString(), ''],
editType: 'plot'
},
editType: 'plot'
},
yaxes: {
valType: 'info_array',
freeLength: true,
items: {
valType: 'enumerated',
values: [cartesianIdRegex.y.toString(), ''],
editType: 'plot'
},
editType: 'plot'
},
pattern: {
valType: 'enumerated',
values: ['independent', 'coupled'],
dflt: 'coupled',
editType: 'plot'
},
xgap: {
valType: 'number',
min: 0,
max: 1,
editType: 'plot'
},
ygap: {
valType: 'number',
min: 0,
max: 1,
editType: 'plot'
},
domain: domainAttrs({
name: 'grid',
editType: 'plot',
noGridCell: true
}, {}),
xside: {
valType: 'enumerated',
values: ['bottom', 'bottom plot', 'top plot', 'top'],
dflt: 'bottom plot',
editType: 'plot'
},
yside: {
valType: 'enumerated',
values: ['left', 'left plot', 'right plot', 'right'],
dflt: 'left plot',
editType: 'plot'
},
editType: 'plot'
};
function getAxes(layout, grid, axLetter) {
var gridVal = grid[axLetter + 'axes'];
var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {});
if (Array.isArray(gridVal)) return gridVal;
if (splomVal.length) return splomVal;
}
// the shape of the grid - this needs to be done BEFORE supplyDataDefaults
// so that non-subplot traces can place themselves in the grid
function sizeDefaults(layoutIn, layoutOut) {
var gridIn = layoutIn.grid || {};
var xAxes = getAxes(layoutOut, gridIn, 'x');
var yAxes = getAxes(layoutOut, gridIn, 'y');
if (!layoutIn.grid && !xAxes && !yAxes) return;
var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]);
var hasXaxes = Array.isArray(xAxes);
var hasYaxes = Array.isArray(yAxes);
var isSplomGenerated = hasXaxes && xAxes !== gridIn.xaxes && hasYaxes && yAxes !== gridIn.yaxes;
var dfltRows, dfltColumns;
if (hasSubplotGrid) {
dfltRows = gridIn.subplots.length;
dfltColumns = gridIn.subplots[0].length;
} else {
if (hasYaxes) dfltRows = yAxes.length;
if (hasXaxes) dfltColumns = xAxes.length;
}
var gridOut = Template.newContainer(layoutOut, 'grid');
function coerce(attr, dflt) {
return Lib.coerce(gridIn, gridOut, gridAttrs, attr, dflt);
}
var rows = coerce('rows', dfltRows);
var columns = coerce('columns', dfltColumns);
if (!(rows * columns > 1)) {
delete layoutOut.grid;
return;
}
if (!hasSubplotGrid && !hasXaxes && !hasYaxes) {
var useDefaultSubplots = coerce('pattern') === 'independent';
if (useDefaultSubplots) hasSubplotGrid = true;
}
gridOut._hasSubplotGrid = hasSubplotGrid;
var rowOrder = coerce('roworder');
var reversed = rowOrder === 'top to bottom';
var dfltGapX = hasSubplotGrid ? 0.2 : 0.1;
var dfltGapY = hasSubplotGrid ? 0.3 : 0.1;
var dfltSideX, dfltSideY;
if (isSplomGenerated && layoutOut._splomGridDflt) {
dfltSideX = layoutOut._splomGridDflt.xside;
dfltSideY = layoutOut._splomGridDflt.yside;
}
gridOut._domains = {
x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns),
y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed)
};
}
// coerce x or y sizing attributes and return an array of domains for this direction
function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) {
var dirGap = coerce(axLetter + 'gap', dfltGap);
var domain = coerce('domain.' + axLetter);
coerce(axLetter + 'side', dfltSide);
var out = new Array(len);
var start = domain[0];
var step = (domain[1] - start) / (len - dirGap);
var cellDomain = step * (1 - dirGap);
for (var i = 0; i < len; i++) {
var cellStart = start + step * i;
out[reversed ? len - 1 - i : i] = [cellStart, cellStart + cellDomain];
}
return out;
}
// the (cartesian) contents of the grid - this needs to happen AFTER supplyDataDefaults
// so that we know what cartesian subplots are available
function contentDefaults(layoutIn, layoutOut) {
var gridOut = layoutOut.grid;
// make sure we got to the end of handleGridSizing
if (!gridOut || !gridOut._domains) return;
var gridIn = layoutIn.grid || {};
var subplots = layoutOut._subplots;
var hasSubplotGrid = gridOut._hasSubplotGrid;
var rows = gridOut.rows;
var columns = gridOut.columns;
var useDefaultSubplots = gridOut.pattern === 'independent';
var i, j, xId, yId, subplotId, subplotsOut, yPos;
var axisMap = gridOut._axisMap = {};
if (hasSubplotGrid) {
var subplotsIn = gridIn.subplots || [];
subplotsOut = gridOut.subplots = new Array(rows);
var index = 1;
for (i = 0; i < rows; i++) {
var rowOut = subplotsOut[i] = new Array(columns);
var rowIn = subplotsIn[i] || [];
for (j = 0; j < columns; j++) {
if (useDefaultSubplots) {
subplotId = index === 1 ? 'xy' : 'x' + index + 'y' + index;
index++;
} else subplotId = rowIn[j];
rowOut[j] = '';
if (subplots.cartesian.indexOf(subplotId) !== -1) {
yPos = subplotId.indexOf('y');
xId = subplotId.slice(0, yPos);
yId = subplotId.slice(yPos);
if (axisMap[xId] !== undefined && axisMap[xId] !== j || axisMap[yId] !== undefined && axisMap[yId] !== i) {
continue;
}
rowOut[j] = subplotId;
axisMap[xId] = j;
axisMap[yId] = i;
}
}
}
} else {
var xAxes = getAxes(layoutOut, gridIn, 'x');
var yAxes = getAxes(layoutOut, gridIn, 'y');
gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');
gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');
}
var anchors = gridOut._anchors = {};
var reversed = gridOut.roworder === 'top to bottom';
for (var axisId in axisMap) {
var axLetter = axisId.charAt(0);
var side = gridOut[axLetter + 'side'];
var i0, inc, iFinal;
if (side.length < 8) {
// grid edge - ie not "* plot" - make these as free axes
// since we're not guaranteed to have a subplot there at all
anchors[axisId] = 'free';
} else if (axLetter === 'x') {
if (side.charAt(0) === 't' === reversed) {
i0 = 0;
inc = 1;
iFinal = rows;
} else {
i0 = rows - 1;
inc = -1;
iFinal = -1;
}
if (hasSubplotGrid) {
var column = axisMap[axisId];
for (i = i0; i !== iFinal; i += inc) {
subplotId = subplotsOut[i][column];
if (!subplotId) continue;
yPos = subplotId.indexOf('y');
if (subplotId.slice(0, yPos) === axisId) {
anchors[axisId] = subplotId.slice(yPos);
break;
}
}
} else {
for (i = i0; i !== iFinal; i += inc) {
yId = gridOut.yaxes[i];
if (subplots.cartesian.indexOf(axisId + yId) !== -1) {
anchors[axisId] = yId;
break;
}
}
}
} else {
if (side.charAt(0) === 'l') {
i0 = 0;
inc = 1;
iFinal = columns;
} else {
i0 = columns - 1;
inc = -1;
iFinal = -1;
}
if (hasSubplotGrid) {
var row = axisMap[axisId];
for (i = i0; i !== iFinal; i += inc) {
subplotId = subplotsOut[row][i];
if (!subplotId) continue;
yPos = subplotId.indexOf('y');
if (subplotId.slice(yPos) === axisId) {
anchors[axisId] = subplotId.slice(0, yPos);
break;
}
}
} else {
for (i = i0; i !== iFinal; i += inc) {
xId = gridOut.xaxes[i];
if (subplots.cartesian.indexOf(xId + axisId) !== -1) {
anchors[axisId] = xId;
break;
}
}
}
}
}
}
function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) {
var out = new Array(len);
var i;
function fillOneAxis(i, axisId) {
if (axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) {
out[i] = axisId;
axisMap[axisId] = i;
} else out[i] = '';
}
if (Array.isArray(axesIn)) {
for (i = 0; i < len; i++) {
fillOneAxis(i, axesIn[i]);
}
} else {
// default axis list is the first `len` axis ids
fillOneAxis(0, axLetter);
for (i = 1; i < len; i++) {
fillOneAxis(i, axLetter + (i + 1));
}
}
return out;
}
module.exports = {
moduleType: 'component',
name: 'grid',
schema: {
layout: {
grid: gridAttrs
}
},
layoutAttributes: gridAttrs,
sizeDefaults: sizeDefaults,
contentDefaults: contentDefaults
};
/***/ }),
/***/ 65760:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var cartesianConstants = __webpack_require__(33816);
var templatedArray = (__webpack_require__(31780).templatedArray);
var axisPlaceableObjs = __webpack_require__(36208);
module.exports = templatedArray('image', {
visible: {
valType: 'boolean',
dflt: true,
editType: 'arraydraw'
},
source: {
valType: 'string',
editType: 'arraydraw'
},
layer: {
valType: 'enumerated',
values: ['below', 'above'],
dflt: 'above',
editType: 'arraydraw'
},
sizex: {
valType: 'number',
dflt: 0,
editType: 'arraydraw'
},
sizey: {
valType: 'number',
dflt: 0,
editType: 'arraydraw'
},
sizing: {
valType: 'enumerated',
values: ['fill', 'contain', 'stretch'],
dflt: 'contain',
editType: 'arraydraw'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1,
editType: 'arraydraw'
},
x: {
valType: 'any',
dflt: 0,
editType: 'arraydraw'
},
y: {
valType: 'any',
dflt: 0,
editType: 'arraydraw'
},
xanchor: {
valType: 'enumerated',
values: ['left', 'center', 'right'],
dflt: 'left',
editType: 'arraydraw'
},
yanchor: {
valType: 'enumerated',
values: ['top', 'middle', 'bottom'],
dflt: 'top',
editType: 'arraydraw'
},
xref: {
valType: 'enumerated',
values: ['paper', cartesianConstants.idRegex.x.toString()],
dflt: 'paper',
editType: 'arraydraw'
},
yref: {
valType: 'enumerated',
values: ['paper', cartesianConstants.idRegex.y.toString()],
dflt: 'paper',
editType: 'arraydraw'
},
editType: 'arraydraw'
});
/***/ }),
/***/ 63556:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var toLogRange = __webpack_require__(36896);
/*
* convertCoords: when converting an axis between log and linear
* you need to alter any images on that axis to keep them
* pointing at the same data point.
* In v3.0 this will become obsolete (or perhaps size will still need conversion?)
* we convert size by declaring that the maximum extent *in data units* should be
* the same, assuming the image is anchored by its center (could remove that restriction
* if we think it's important) even though the actual left and right values will not be
* quite the same since the scale becomes nonlinear (and central anchor means the pixel
* center of the image, not the data units center)
*
* gd: the plot div
* ax: the axis being changed
* newType: the type it's getting
* doExtra: function(attr, val) from inside relayout that sets the attribute.
* Use this to make the changes as it's aware if any other changes in the
* same relayout call should override this conversion.
*/
module.exports = function convertCoords(gd, ax, newType, doExtra) {
ax = ax || {};
var toLog = newType === 'log' && ax.type === 'linear';
var fromLog = newType === 'linear' && ax.type === 'log';
if (!(toLog || fromLog)) return;
var images = gd._fullLayout.images;
var axLetter = ax._id.charAt(0);
var image;
var attrPrefix;
for (var i = 0; i < images.length; i++) {
image = images[i];
attrPrefix = 'images[' + i + '].';
if (image[axLetter + 'ref'] === ax._id) {
var currentPos = image[axLetter];
var currentSize = image['size' + axLetter];
var newPos = null;
var newSize = null;
if (toLog) {
newPos = toLogRange(currentPos, ax.range);
// this is the inverse of the conversion we do in fromLog below
// so that the conversion is reversible (notice the fromLog conversion
// is like sinh, and this one looks like arcsinh)
var dx = currentSize / Math.pow(10, newPos) / 2;
newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10;
} else {
newPos = Math.pow(10, currentPos);
newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2));
}
// if conversion failed, delete the value so it can get a default later on
if (!isNumeric(newPos)) {
newPos = null;
newSize = null;
} else if (!isNumeric(newSize)) newSize = null;
doExtra(attrPrefix + axLetter, newPos);
doExtra(attrPrefix + 'size' + axLetter, newSize);
}
}
};
/***/ }),
/***/ 25024:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var handleArrayContainerDefaults = __webpack_require__(51272);
var attributes = __webpack_require__(65760);
var name = 'images';
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
var opts = {
name: name,
handleItemDefaults: imageDefaults
};
handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};
function imageDefaults(imageIn, imageOut, fullLayout) {
function coerce(attr, dflt) {
return Lib.coerce(imageIn, imageOut, attributes, attr, dflt);
}
var source = coerce('source');
var visible = coerce('visible', !!source);
if (!visible) return imageOut;
coerce('layer');
coerce('xanchor');
coerce('yanchor');
coerce('sizex');
coerce('sizey');
coerce('sizing');
coerce('opacity');
var gdMock = {
_fullLayout: fullLayout
};
var axLetters = ['x', 'y'];
for (var i = 0; i < 2; i++) {
// 'paper' is the fallback axref
var axLetter = axLetters[i];
var axRef = Axes.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper', undefined);
if (axRef !== 'paper') {
var ax = Axes.getFromId(gdMock, axRef);
ax._imgIndices.push(imageOut._index);
}
Axes.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0);
}
return imageOut;
}
/***/ }),
/***/ 60963:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var Axes = __webpack_require__(54460);
var axisIds = __webpack_require__(79811);
var xmlnsNamespaces = __webpack_require__(9616);
module.exports = function draw(gd) {
var fullLayout = gd._fullLayout;
var imageDataAbove = [];
var imageDataSubplot = {};
var imageDataBelow = [];
var subplot;
var i;
// Sort into top, subplot, and bottom layers
for (i = 0; i < fullLayout.images.length; i++) {
var img = fullLayout.images[i];
if (img.visible) {
if (img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') {
subplot = axisIds.ref2id(img.xref) + axisIds.ref2id(img.yref);
var plotinfo = fullLayout._plots[subplot];
if (!plotinfo) {
// Fall back to _imageLowerLayer in case the requested subplot doesn't exist.
// This can happen if you reference the image to an x / y axis combination
// that doesn't have any data on it (and layer is below)
imageDataBelow.push(img);
continue;
}
if (plotinfo.mainplot) {
subplot = plotinfo.mainplot.id;
}
if (!imageDataSubplot[subplot]) {
imageDataSubplot[subplot] = [];
}
imageDataSubplot[subplot].push(img);
} else if (img.layer === 'above') {
imageDataAbove.push(img);
} else {
imageDataBelow.push(img);
}
}
}
var anchors = {
x: {
left: {
sizing: 'xMin',
offset: 0
},
center: {
sizing: 'xMid',
offset: -1 / 2
},
right: {
sizing: 'xMax',
offset: -1
}
},
y: {
top: {
sizing: 'YMin',
offset: 0
},
middle: {
sizing: 'YMid',
offset: -1 / 2
},
bottom: {
sizing: 'YMax',
offset: -1
}
}
};
// Images must be converted to dataURL's for exporting.
function setImage(d) {
var thisImage = d3.select(this);
if (this._imgSrc === d.source) {
return;
}
thisImage.attr('xmlns', xmlnsNamespaces.svg);
if (d.source && d.source.slice(0, 5) === 'data:') {
thisImage.attr('xlink:href', d.source);
this._imgSrc = d.source;
} else {
var imagePromise = new Promise(function (resolve) {
var img = new Image();
this.img = img;
// If not set, a `tainted canvas` error is thrown
img.setAttribute('crossOrigin', 'anonymous');
img.onerror = errorHandler;
img.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d', {
willReadFrequently: true
});
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL('image/png');
thisImage.attr('xlink:href', dataURL);
// resolve promise in onload handler instead of on 'load' to support IE11
// see https://github.com/plotly/plotly.js/issues/1685
// for more details
resolve();
};
thisImage.on('error', errorHandler);
img.src = d.source;
this._imgSrc = d.source;
function errorHandler() {
thisImage.remove();
resolve();
}
}.bind(this));
gd._promises.push(imagePromise);
}
}
function applyAttributes(d) {
var thisImage = d3.select(this);
// Axes if specified
var xa = Axes.getFromId(gd, d.xref);
var ya = Axes.getFromId(gd, d.yref);
var xIsDomain = Axes.getRefType(d.xref) === 'domain';
var yIsDomain = Axes.getRefType(d.yref) === 'domain';
var size = fullLayout._size;
var width, height;
if (xa !== undefined) {
width = typeof d.xref === 'string' && xIsDomain ? xa._length * d.sizex : Math.abs(xa.l2p(d.sizex) - xa.l2p(0));
} else {
width = d.sizex * size.w;
}
if (ya !== undefined) {
height = typeof d.yref === 'string' && yIsDomain ? ya._length * d.sizey : Math.abs(ya.l2p(d.sizey) - ya.l2p(0));
} else {
height = d.sizey * size.h;
}
// Offsets for anchor positioning
var xOffset = width * anchors.x[d.xanchor].offset;
var yOffset = height * anchors.y[d.yanchor].offset;
var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing;
// Final positions
var xPos, yPos;
if (xa !== undefined) {
xPos = typeof d.xref === 'string' && xIsDomain ? xa._length * d.x + xa._offset : xa.r2p(d.x) + xa._offset;
} else {
xPos = d.x * size.w + size.l;
}
xPos += xOffset;
if (ya !== undefined) {
yPos = typeof d.yref === 'string' && yIsDomain ?
// consistent with "paper" yref value, where positive values
// move up the page
ya._length * (1 - d.y) + ya._offset : ya.r2p(d.y) + ya._offset;
} else {
yPos = size.h - d.y * size.h + size.t;
}
yPos += yOffset;
// Construct the proper aspectRatio attribute
switch (d.sizing) {
case 'fill':
sizing += ' slice';
break;
case 'stretch':
sizing = 'none';
break;
}
thisImage.attr({
x: xPos,
y: yPos,
width: width,
height: height,
preserveAspectRatio: sizing,
opacity: d.opacity
});
// Set proper clipping on images
var xId = xa && Axes.getRefType(d.xref) !== 'domain' ? xa._id : '';
var yId = ya && Axes.getRefType(d.yref) !== 'domain' ? ya._id : '';
var clipAxes = xId + yId;
Drawing.setClipUrl(thisImage, clipAxes ? 'clip' + fullLayout._uid + clipAxes : null, gd);
}
var imagesBelow = fullLayout._imageLowerLayer.selectAll('image').data(imageDataBelow);
var imagesAbove = fullLayout._imageUpperLayer.selectAll('image').data(imageDataAbove);
imagesBelow.enter().append('image');
imagesAbove.enter().append('image');
imagesBelow.exit().remove();
imagesAbove.exit().remove();
imagesBelow.each(function (d) {
setImage.bind(this)(d);
applyAttributes.bind(this)(d);
});
imagesAbove.each(function (d) {
setImage.bind(this)(d);
applyAttributes.bind(this)(d);
});
var allSubplots = Object.keys(fullLayout._plots);
for (i = 0; i < allSubplots.length; i++) {
subplot = allSubplots[i];
var subplotObj = fullLayout._plots[subplot];
// filter out overlaid plots (which have their images on the main plot)
// and gl2d plots (which don't support below images, at least not yet)
if (!subplotObj.imagelayer) continue;
var imagesOnSubplot = subplotObj.imagelayer.selectAll('image')
// even if there are no images on this subplot, we need to run
// enter and exit in case there were previously
.data(imageDataSubplot[subplot] || []);
imagesOnSubplot.enter().append('image');
imagesOnSubplot.exit().remove();
imagesOnSubplot.each(function (d) {
setImage.bind(this)(d);
applyAttributes.bind(this)(d);
});
}
};
/***/ }),
/***/ 7402:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'component',
name: 'images',
layoutAttributes: __webpack_require__(65760),
supplyLayoutDefaults: __webpack_require__(25024),
includeBasePlot: __webpack_require__(36632)('images'),
draw: __webpack_require__(60963),
convertCoords: __webpack_require__(63556)
};
/***/ }),
/***/ 3800:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var colorAttrs = __webpack_require__(22548);
module.exports = {
// not really a 'subplot' attribute container,
// but this is the flag we use to denote attributes that
// support yaxis, yaxis2, yaxis3, ... counters
_isSubplotObj: true,
visible: {
valType: 'boolean',
dflt: true,
editType: 'legend'
},
bgcolor: {
valType: 'color',
editType: 'legend'
},
bordercolor: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'legend'
},
borderwidth: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'legend'
},
font: fontAttrs({
editType: 'legend'
}),
grouptitlefont: fontAttrs({
editType: 'legend'
}),
orientation: {
valType: 'enumerated',
values: ['v', 'h'],
dflt: 'v',
editType: 'legend'
},
traceorder: {
valType: 'flaglist',
flags: ['reversed', 'grouped'],
extras: ['normal'],
editType: 'legend'
},
tracegroupgap: {
valType: 'number',
min: 0,
dflt: 10,
editType: 'legend'
},
entrywidth: {
valType: 'number',
min: 0,
editType: 'legend'
},
entrywidthmode: {
valType: 'enumerated',
values: ['fraction', 'pixels'],
dflt: 'pixels',
editType: 'legend'
},
indentation: {
valType: 'number',
min: -15,
dflt: 0,
editType: 'legend'
},
itemsizing: {
valType: 'enumerated',
values: ['trace', 'constant'],
dflt: 'trace',
editType: 'legend'
},
itemwidth: {
valType: 'number',
min: 30,
dflt: 30,
editType: 'legend'
},
itemclick: {
valType: 'enumerated',
values: ['toggle', 'toggleothers', false],
dflt: 'toggle',
editType: 'legend'
},
itemdoubleclick: {
valType: 'enumerated',
values: ['toggle', 'toggleothers', false],
dflt: 'toggleothers',
editType: 'legend'
},
groupclick: {
valType: 'enumerated',
values: ['toggleitem', 'togglegroup'],
dflt: 'togglegroup',
editType: 'legend'
},
x: {
valType: 'number',
editType: 'legend'
},
xref: {
valType: 'enumerated',
dflt: 'paper',
values: ['container', 'paper'],
editType: 'layoutstyle'
},
xanchor: {
valType: 'enumerated',
values: ['auto', 'left', 'center', 'right'],
dflt: 'left',
editType: 'legend'
},
y: {
valType: 'number',
editType: 'legend'
},
yref: {
valType: 'enumerated',
dflt: 'paper',
values: ['container', 'paper'],
editType: 'layoutstyle'
},
yanchor: {
valType: 'enumerated',
values: ['auto', 'top', 'middle', 'bottom'],
editType: 'legend'
},
uirevision: {
valType: 'any',
editType: 'none'
},
valign: {
valType: 'enumerated',
values: ['top', 'middle', 'bottom'],
dflt: 'middle',
editType: 'legend'
},
title: {
text: {
valType: 'string',
dflt: '',
editType: 'legend'
},
font: fontAttrs({
editType: 'legend'
}),
side: {
valType: 'enumerated',
values: ['top', 'left', 'top left', 'top center', 'top right'],
editType: 'legend'
},
editType: 'legend'
},
editType: 'legend'
};
/***/ }),
/***/ 65196:
/***/ (function(module) {
"use strict";
module.exports = {
scrollBarWidth: 6,
scrollBarMinHeight: 20,
scrollBarColor: '#808BA4',
scrollBarMargin: 4,
scrollBarEnterAttrs: {
rx: 20,
ry: 3,
width: 0,
height: 0
},
// number of px between legend title and (left) side of legend (always in x direction and from inner border)
titlePad: 2,
// number of px between each legend item (x and/or y direction)
itemGap: 5
};
/***/ }),
/***/ 77864:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
var plotsAttrs = __webpack_require__(45464);
var attributes = __webpack_require__(3800);
var basePlotLayoutAttributes = __webpack_require__(64859);
var helpers = __webpack_require__(42451);
function groupDefaults(legendId, layoutIn, layoutOut, fullData) {
var containerIn = layoutIn[legendId] || {};
var containerOut = Template.newContainer(layoutOut, legendId);
function coerce(attr, dflt) {
return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
}
// N.B. unified hover needs to inherit from font, bgcolor & bordercolor even when legend.visible is false
var itemFont = Lib.coerceFont(coerce, 'font', layoutOut.font);
coerce('bgcolor', layoutOut.paper_bgcolor);
coerce('bordercolor');
var visible = coerce('visible');
if (!visible) return;
var trace;
var traceCoerce = function (attr, dflt) {
var traceIn = trace._input;
var traceOut = trace;
return Lib.coerce(traceIn, traceOut, plotsAttrs, attr, dflt);
};
var globalFont = layoutOut.font || {};
var grouptitlefont = Lib.coerceFont(coerce, 'grouptitlefont', globalFont, {
overrideDflt: {
size: Math.round(globalFont.size * 1.1)
}
});
var legendTraceCount = 0;
var legendReallyHasATrace = false;
var defaultOrder = 'normal';
var shapesWithLegend = (layoutOut.shapes || []).filter(function (d) {
return d.showlegend;
});
var allLegendItems = fullData.concat(shapesWithLegend).filter(function (d) {
return legendId === (d.legend || 'legend');
});
for (var i = 0; i < allLegendItems.length; i++) {
trace = allLegendItems[i];
if (!trace.visible) continue;
var isShape = trace._isShape;
// Note that we explicitly count any trace that is either shown or
// *would* be shown by default, toward the two traces you need to
// ensure the legend is shown by default, because this can still help
// disambiguate.
if (trace.showlegend || trace._dfltShowLegend && !(trace._module && trace._module.attributes && trace._module.attributes.showlegend && trace._module.attributes.showlegend.dflt === false)) {
legendTraceCount++;
if (trace.showlegend) {
legendReallyHasATrace = true;
// Always show the legend by default if there's a pie,
// or if there's only one trace but it's explicitly shown
if (!isShape && Registry.traceIs(trace, 'pie-like') || trace._input.showlegend === true) {
legendTraceCount++;
}
}
Lib.coerceFont(traceCoerce, 'legendgrouptitle.font', grouptitlefont);
}
if (!isShape && Registry.traceIs(trace, 'bar') && layoutOut.barmode === 'stack' || ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) {
defaultOrder = helpers.isGrouped({
traceorder: defaultOrder
}) ? 'grouped+reversed' : 'reversed';
}
if (trace.legendgroup !== undefined && trace.legendgroup !== '') {
defaultOrder = helpers.isReversed({
traceorder: defaultOrder
}) ? 'reversed+grouped' : 'grouped';
}
}
var showLegend = Lib.coerce(layoutIn, layoutOut, basePlotLayoutAttributes, 'showlegend', legendReallyHasATrace && legendTraceCount > (legendId === 'legend' ? 1 : 0));
// delete legend
if (showLegend === false) layoutOut[legendId] = undefined;
if (showLegend === false && !containerIn.uirevision) return;
coerce('uirevision', layoutOut.uirevision);
if (showLegend === false) return;
coerce('borderwidth');
var orientation = coerce('orientation');
var yref = coerce('yref');
var xref = coerce('xref');
var isHorizontal = orientation === 'h';
var isPaperY = yref === 'paper';
var isPaperX = xref === 'paper';
var defaultX, defaultY, defaultYAnchor;
var defaultXAnchor = 'left';
if (isHorizontal) {
defaultX = 0;
if (Registry.getComponentMethod('rangeslider', 'isVisible')(layoutIn.xaxis)) {
if (isPaperY) {
defaultY = 1.1;
defaultYAnchor = 'bottom';
} else {
defaultY = 1;
defaultYAnchor = 'top';
}
} else {
// maybe use y=1.1 / yanchor=bottom as above
// to avoid https://github.com/plotly/plotly.js/issues/1199
// in v3
if (isPaperY) {
defaultY = -0.1;
defaultYAnchor = 'top';
} else {
defaultY = 0;
defaultYAnchor = 'bottom';
}
}
} else {
defaultY = 1;
defaultYAnchor = 'auto';
if (isPaperX) {
defaultX = 1.02;
} else {
defaultX = 1;
defaultXAnchor = 'right';
}
}
Lib.coerce(containerIn, containerOut, {
x: {
valType: 'number',
editType: 'legend',
min: isPaperX ? -2 : 0,
max: isPaperX ? 3 : 1,
dflt: defaultX
}
}, 'x');
Lib.coerce(containerIn, containerOut, {
y: {
valType: 'number',
editType: 'legend',
min: isPaperY ? -2 : 0,
max: isPaperY ? 3 : 1,
dflt: defaultY
}
}, 'y');
coerce('traceorder', defaultOrder);
if (helpers.isGrouped(layoutOut[legendId])) coerce('tracegroupgap');
coerce('entrywidth');
coerce('entrywidthmode');
coerce('indentation');
coerce('itemsizing');
coerce('itemwidth');
coerce('itemclick');
coerce('itemdoubleclick');
coerce('groupclick');
coerce('xanchor', defaultXAnchor);
coerce('yanchor', defaultYAnchor);
coerce('valign');
Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
var titleText = coerce('title.text');
if (titleText) {
coerce('title.side', isHorizontal ? 'left' : 'top');
var dfltTitleFont = Lib.extendFlat({}, itemFont, {
size: Lib.bigFont(itemFont.size)
});
Lib.coerceFont(coerce, 'title.font', dfltTitleFont);
}
}
module.exports = function legendDefaults(layoutIn, layoutOut, fullData) {
var i;
var allLegendsData = fullData.slice();
// shapes could also show up in legends
var shapes = layoutOut.shapes;
if (shapes) {
for (i = 0; i < shapes.length; i++) {
var shape = shapes[i];
if (!shape.showlegend) continue;
var mockTrace = {
_input: shape._input,
visible: shape.visible,
showlegend: shape.showlegend,
legend: shape.legend
};
allLegendsData.push(mockTrace);
}
}
var legends = ['legend'];
for (i = 0; i < allLegendsData.length; i++) {
Lib.pushUnique(legends, allLegendsData[i].legend);
}
layoutOut._legends = [];
for (i = 0; i < legends.length; i++) {
var legendId = legends[i];
groupDefaults(legendId, layoutIn, layoutOut, allLegendsData);
if (layoutOut[legendId] && layoutOut[legendId].visible) {
layoutOut[legendId]._id = legendId;
}
layoutOut._legends.push(legendId);
}
};
/***/ }),
/***/ 31140:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var Plots = __webpack_require__(7316);
var Registry = __webpack_require__(24040);
var Events = __webpack_require__(95924);
var dragElement = __webpack_require__(86476);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var svgTextUtils = __webpack_require__(72736);
var handleClick = __webpack_require__(33048);
var constants = __webpack_require__(65196);
var alignmentConstants = __webpack_require__(84284);
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;
var getLegendData = __webpack_require__(35456);
var style = __webpack_require__(2012);
var helpers = __webpack_require__(42451);
var MAIN_TITLE = 1;
var LEGEND_PATTERN = /^legend[0-9]*$/;
module.exports = function draw(gd, opts) {
if (opts) {
drawOne(gd, opts);
} else {
var fullLayout = gd._fullLayout;
var newLegends = fullLayout._legends;
// remove old legends that won't stay on the graph
var oldLegends = fullLayout._infolayer.selectAll('[class^="legend"]');
oldLegends.each(function () {
var el = d3.select(this);
var classes = el.attr('class');
var cls = classes.split(' ')[0];
if (cls.match(LEGEND_PATTERN) && newLegends.indexOf(cls) === -1) {
el.remove();
}
});
// draw/update new legends
for (var i = 0; i < newLegends.length; i++) {
var legendId = newLegends[i];
var legendObj = gd._fullLayout[legendId];
drawOne(gd, legendObj);
}
}
};
// After legend dimensions are calculated the title can be aligned horizontally left, center, right
function horizontalAlignTitle(titleEl, legendObj, bw) {
if (legendObj.title.side !== 'top center' && legendObj.title.side !== 'top right') return;
var font = legendObj.title.font;
var lineHeight = font.size * LINE_SPACING;
var titleOffset = 0;
var textNode = titleEl.node();
var width = Drawing.bBox(textNode).width; // width of the title text
if (legendObj.title.side === 'top center') {
titleOffset = 0.5 * (legendObj._width - 2 * bw - 2 * constants.titlePad - width);
} else if (legendObj.title.side === 'top right') {
titleOffset = legendObj._width - 2 * bw - 2 * constants.titlePad - width;
}
svgTextUtils.positionText(titleEl, bw + constants.titlePad + titleOffset, bw + lineHeight);
}
function drawOne(gd, opts) {
var legendObj = opts || {};
var fullLayout = gd._fullLayout;
var legendId = getId(legendObj);
var clipId, layer;
var inHover = legendObj._inHover;
if (inHover) {
layer = legendObj.layer;
clipId = 'hover';
} else {
layer = fullLayout._infolayer;
clipId = legendId;
}
if (!layer) return;
clipId += fullLayout._uid;
if (!gd._legendMouseDownTime) gd._legendMouseDownTime = 0;
var legendData;
if (!inHover) {
var calcdata = (gd.calcdata || []).slice();
var shapes = fullLayout.shapes;
for (var i = 0; i < shapes.length; i++) {
var shape = shapes[i];
if (!shape.showlegend) continue;
var shapeLegend = {
_isShape: true,
_fullInput: shape,
index: shape._index,
name: shape.name || shape.label.text || 'shape ' + shape._index,
legend: shape.legend,
legendgroup: shape.legendgroup,
legendgrouptitle: shape.legendgrouptitle,
legendrank: shape.legendrank,
legendwidth: shape.legendwidth,
showlegend: shape.showlegend,
visible: shape.visible,
opacity: shape.opacity,
mode: shape.type === 'line' ? 'lines' : 'markers',
line: shape.line,
marker: {
line: shape.line,
color: shape.fillcolor,
size: 12,
symbol: shape.type === 'rect' ? 'square' : shape.type === 'circle' ? 'circle' :
// case of path
'hexagon2'
}
};
calcdata.push([{
trace: shapeLegend
}]);
}
legendData = fullLayout.showlegend && getLegendData(calcdata, legendObj, fullLayout._legends.length > 1);
} else {
if (!legendObj.entries) return;
legendData = getLegendData(legendObj.entries, legendObj);
}
var hiddenSlices = fullLayout.hiddenlabels || [];
if (!inHover && (!fullLayout.showlegend || !legendData.length)) {
layer.selectAll('.' + legendId).remove();
fullLayout._topdefs.select('#' + clipId).remove();
return Plots.autoMargin(gd, legendId);
}
var legend = Lib.ensureSingle(layer, 'g', legendId, function (s) {
if (!inHover) s.attr('pointer-events', 'all');
});
var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function (s) {
s.append('rect');
});
var bg = Lib.ensureSingle(legend, 'rect', 'bg', function (s) {
s.attr('shape-rendering', 'crispEdges');
});
bg.call(Color.stroke, legendObj.bordercolor).call(Color.fill, legendObj.bgcolor).style('stroke-width', legendObj.borderwidth + 'px');
var scrollBox = Lib.ensureSingle(legend, 'g', 'scrollbox');
var title = legendObj.title;
legendObj._titleWidth = 0;
legendObj._titleHeight = 0;
var titleEl;
if (title.text) {
titleEl = Lib.ensureSingle(scrollBox, 'text', legendId + 'titletext');
titleEl.attr('text-anchor', 'start').call(Drawing.font, title.font).text(title.text);
textLayout(titleEl, scrollBox, gd, legendObj, MAIN_TITLE); // handle mathjax or multi-line text and compute title height
} else {
scrollBox.selectAll('.' + legendId + 'titletext').remove();
}
var scrollBar = Lib.ensureSingle(legend, 'rect', 'scrollbar', function (s) {
s.attr(constants.scrollBarEnterAttrs).call(Color.fill, constants.scrollBarColor);
});
var groups = scrollBox.selectAll('g.groups').data(legendData);
groups.enter().append('g').attr('class', 'groups');
groups.exit().remove();
var traces = groups.selectAll('g.traces').data(Lib.identity);
traces.enter().append('g').attr('class', 'traces');
traces.exit().remove();
traces.style('opacity', function (d) {
var trace = d[0].trace;
if (Registry.traceIs(trace, 'pie-like')) {
return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1;
} else {
return trace.visible === 'legendonly' ? 0.5 : 1;
}
}).each(function () {
d3.select(this).call(drawTexts, gd, legendObj);
}).call(style, gd, legendObj).each(function () {
if (!inHover) d3.select(this).call(setupTraceToggle, gd, legendId);
});
Lib.syncOrAsync([Plots.previousPromises, function () {
return computeLegendDimensions(gd, groups, traces, legendObj);
}, function () {
var gs = fullLayout._size;
var bw = legendObj.borderwidth;
var isPaperX = legendObj.xref === 'paper';
var isPaperY = legendObj.yref === 'paper';
// re-calculate title position after legend width is derived. To allow for horizontal alignment
if (title.text) {
horizontalAlignTitle(titleEl, legendObj, bw);
}
if (!inHover) {
var lx, ly;
if (isPaperX) {
lx = gs.l + gs.w * legendObj.x - FROM_TL[getXanchor(legendObj)] * legendObj._width;
} else {
lx = fullLayout.width * legendObj.x - FROM_TL[getXanchor(legendObj)] * legendObj._width;
}
if (isPaperY) {
ly = gs.t + gs.h * (1 - legendObj.y) - FROM_TL[getYanchor(legendObj)] * legendObj._effHeight;
} else {
ly = fullLayout.height * (1 - legendObj.y) - FROM_TL[getYanchor(legendObj)] * legendObj._effHeight;
}
var expMargin = expandMargin(gd, legendId, lx, ly);
// IF expandMargin return a Promise (which is truthy),
// we're under a doAutoMargin redraw, so we don't have to
// draw the remaining pieces below
if (expMargin) return;
if (fullLayout.margin.autoexpand) {
var lx0 = lx;
var ly0 = ly;
lx = isPaperX ? Lib.constrain(lx, 0, fullLayout.width - legendObj._width) : lx0;
ly = isPaperY ? Lib.constrain(ly, 0, fullLayout.height - legendObj._effHeight) : ly0;
if (lx !== lx0) {
Lib.log('Constrain ' + legendId + '.x to make legend fit inside graph');
}
if (ly !== ly0) {
Lib.log('Constrain ' + legendId + '.y to make legend fit inside graph');
}
}
// Set size and position of all the elements that make up a legend:
// legend, background and border, scroll box and scroll bar as well as title
Drawing.setTranslate(legend, lx, ly);
}
// to be safe, remove previous listeners
scrollBar.on('.drag', null);
legend.on('wheel', null);
if (inHover || legendObj._height <= legendObj._maxHeight || gd._context.staticPlot) {
// if scrollbar should not be shown.
var height = legendObj._effHeight;
// if unified hover, let it be its full size
if (inHover) height = legendObj._height;
bg.attr({
width: legendObj._width - bw,
height: height - bw,
x: bw / 2,
y: bw / 2
});
Drawing.setTranslate(scrollBox, 0, 0);
clipPath.select('rect').attr({
width: legendObj._width - 2 * bw,
height: height - 2 * bw,
x: bw,
y: bw
});
Drawing.setClipUrl(scrollBox, clipId, gd);
Drawing.setRect(scrollBar, 0, 0, 0, 0);
delete legendObj._scrollY;
} else {
var scrollBarHeight = Math.max(constants.scrollBarMinHeight, legendObj._effHeight * legendObj._effHeight / legendObj._height);
var scrollBarYMax = legendObj._effHeight - scrollBarHeight - 2 * constants.scrollBarMargin;
var scrollBoxYMax = legendObj._height - legendObj._effHeight;
var scrollRatio = scrollBarYMax / scrollBoxYMax;
var scrollBoxY = Math.min(legendObj._scrollY || 0, scrollBoxYMax);
// increase the background and clip-path width
// by the scrollbar width and margin
bg.attr({
width: legendObj._width - 2 * bw + constants.scrollBarWidth + constants.scrollBarMargin,
height: legendObj._effHeight - bw,
x: bw / 2,
y: bw / 2
});
clipPath.select('rect').attr({
width: legendObj._width - 2 * bw + constants.scrollBarWidth + constants.scrollBarMargin,
height: legendObj._effHeight - 2 * bw,
x: bw,
y: bw + scrollBoxY
});
Drawing.setClipUrl(scrollBox, clipId, gd);
scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
// scroll legend by mousewheel or touchpad swipe up/down
legend.on('wheel', function () {
scrollBoxY = Lib.constrain(legendObj._scrollY + d3.event.deltaY / scrollBarYMax * scrollBoxYMax, 0, scrollBoxYMax);
scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
if (scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) {
d3.event.preventDefault();
}
});
var eventY0, eventY1, scrollBoxY0;
var getScrollBarDragY = function (scrollBoxY0, eventY0, eventY1) {
var y = (eventY1 - eventY0) / scrollRatio + scrollBoxY0;
return Lib.constrain(y, 0, scrollBoxYMax);
};
var getNaturalDragY = function (scrollBoxY0, eventY0, eventY1) {
var y = (eventY0 - eventY1) / scrollRatio + scrollBoxY0;
return Lib.constrain(y, 0, scrollBoxYMax);
};
// scroll legend by dragging scrollBAR
var scrollBarDrag = d3.behavior.drag().on('dragstart', function () {
var e = d3.event.sourceEvent;
if (e.type === 'touchstart') {
eventY0 = e.changedTouches[0].clientY;
} else {
eventY0 = e.clientY;
}
scrollBoxY0 = scrollBoxY;
}).on('drag', function () {
var e = d3.event.sourceEvent;
if (e.buttons === 2 || e.ctrlKey) return;
if (e.type === 'touchmove') {
eventY1 = e.changedTouches[0].clientY;
} else {
eventY1 = e.clientY;
}
scrollBoxY = getScrollBarDragY(scrollBoxY0, eventY0, eventY1);
scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
});
scrollBar.call(scrollBarDrag);
// scroll legend by touch-dragging scrollBOX
var scrollBoxTouchDrag = d3.behavior.drag().on('dragstart', function () {
var e = d3.event.sourceEvent;
if (e.type === 'touchstart') {
eventY0 = e.changedTouches[0].clientY;
scrollBoxY0 = scrollBoxY;
}
}).on('drag', function () {
var e = d3.event.sourceEvent;
if (e.type === 'touchmove') {
eventY1 = e.changedTouches[0].clientY;
scrollBoxY = getNaturalDragY(scrollBoxY0, eventY0, eventY1);
scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
}
});
scrollBox.call(scrollBoxTouchDrag);
}
function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) {
legendObj._scrollY = gd._fullLayout[legendId]._scrollY = scrollBoxY;
Drawing.setTranslate(scrollBox, 0, -scrollBoxY);
Drawing.setRect(scrollBar, legendObj._width, constants.scrollBarMargin + scrollBoxY * scrollRatio, constants.scrollBarWidth, scrollBarHeight);
clipPath.select('rect').attr('y', bw + scrollBoxY);
}
if (gd._context.edits.legendPosition) {
var xf, yf, x0, y0;
legend.classed('cursor-move', true);
dragElement.init({
element: legend.node(),
gd: gd,
prepFn: function (e) {
if (e.target === scrollBar.node()) {
return;
}
var transform = Drawing.getTranslate(legend);
x0 = transform.x;
y0 = transform.y;
},
moveFn: function (dx, dy) {
if (x0 !== undefined && y0 !== undefined) {
var newX = x0 + dx;
var newY = y0 + dy;
Drawing.setTranslate(legend, newX, newY);
xf = dragElement.align(newX, legendObj._width, gs.l, gs.l + gs.w, legendObj.xanchor);
yf = dragElement.align(newY + legendObj._height, -legendObj._height, gs.t + gs.h, gs.t, legendObj.yanchor);
}
},
doneFn: function () {
if (xf !== undefined && yf !== undefined) {
var obj = {};
obj[legendId + '.x'] = xf;
obj[legendId + '.y'] = yf;
Registry.call('_guiRelayout', gd, obj);
}
},
clickFn: function (numClicks, e) {
var clickedTrace = layer.selectAll('g.traces').filter(function () {
var bbox = this.getBoundingClientRect();
return e.clientX >= bbox.left && e.clientX <= bbox.right && e.clientY >= bbox.top && e.clientY <= bbox.bottom;
});
if (clickedTrace.size() > 0) {
clickOrDoubleClick(gd, legend, clickedTrace, numClicks, e);
}
}
});
}
}], gd);
}
function getTraceWidth(d, legendObj, textGap) {
var legendItem = d[0];
var legendWidth = legendItem.width;
var mode = legendObj.entrywidthmode;
var traceLegendWidth = legendItem.trace.legendwidth || legendObj.entrywidth;
if (mode === 'fraction') return legendObj._maxWidth * traceLegendWidth;
return textGap + (traceLegendWidth || legendWidth);
}
function clickOrDoubleClick(gd, legend, legendItem, numClicks, evt) {
var trace = legendItem.data()[0][0].trace;
var evtData = {
event: evt,
node: legendItem.node(),
curveNumber: trace.index,
expandedIndex: trace._expandedIndex,
data: gd.data,
layout: gd.layout,
frames: gd._transitionData._frames,
config: gd._context,
fullData: gd._fullData,
fullLayout: gd._fullLayout
};
if (trace._group) {
evtData.group = trace._group;
}
if (Registry.traceIs(trace, 'pie-like')) {
evtData.label = legendItem.datum()[0].label;
}
var clickVal = Events.triggerHandler(gd, 'plotly_legendclick', evtData);
if (numClicks === 1) {
if (clickVal === false) return;
legend._clickTimeout = setTimeout(function () {
if (!gd._fullLayout) return;
handleClick(legendItem, gd, numClicks);
}, gd._context.doubleClickDelay);
} else if (numClicks === 2) {
if (legend._clickTimeout) clearTimeout(legend._clickTimeout);
gd._legendMouseDownTime = 0;
var dblClickVal = Events.triggerHandler(gd, 'plotly_legenddoubleclick', evtData);
// Activate default double click behaviour only when both single click and double click values are not false
if (dblClickVal !== false && clickVal !== false) handleClick(legendItem, gd, numClicks);
}
}
function drawTexts(g, gd, legendObj) {
var legendId = getId(legendObj);
var legendItem = g.data()[0][0];
var trace = legendItem.trace;
var isPieLike = Registry.traceIs(trace, 'pie-like');
var isEditable = !legendObj._inHover && gd._context.edits.legendText && !isPieLike;
var maxNameLength = legendObj._maxNameLength;
var name, font;
if (legendItem.groupTitle) {
name = legendItem.groupTitle.text;
font = legendItem.groupTitle.font;
} else {
font = legendObj.font;
if (!legendObj.entries) {
name = isPieLike ? legendItem.label : trace.name;
if (trace._meta) {
name = Lib.templateString(name, trace._meta);
}
} else {
name = legendItem.text;
}
}
var textEl = Lib.ensureSingle(g, 'text', legendId + 'text');
textEl.attr('text-anchor', 'start').call(Drawing.font, font).text(isEditable ? ensureLength(name, maxNameLength) : name);
var textGap = legendObj.indentation + legendObj.itemwidth + constants.itemGap * 2;
svgTextUtils.positionText(textEl, textGap, 0);
if (isEditable) {
textEl.call(svgTextUtils.makeEditable, {
gd: gd,
text: name
}).call(textLayout, g, gd, legendObj).on('edit', function (newName) {
this.text(ensureLength(newName, maxNameLength)).call(textLayout, g, gd, legendObj);
var fullInput = legendItem.trace._fullInput || {};
var update = {};
if (Registry.hasTransform(fullInput, 'groupby')) {
var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
var _index = groupbyIndices[groupbyIndices.length - 1];
var kcont = Lib.keyedContainer(fullInput, 'transforms[' + _index + '].styles', 'target', 'value.name');
kcont.set(legendItem.trace._group, newName);
update = kcont.constructUpdate();
} else {
update.name = newName;
}
if (fullInput._isShape) {
return Registry.call('_guiRelayout', gd, 'shapes[' + trace.index + '].name', update.name);
} else {
return Registry.call('_guiRestyle', gd, update, trace.index);
}
});
} else {
textLayout(textEl, g, gd, legendObj);
}
}
/*
* Make sure we have a reasonably clickable region.
* If this string is missing or very short, pad it with spaces out to at least
* 4 characters, up to the max length of other labels, on the assumption that
* most characters are wider than spaces so a string of spaces will usually be
* no wider than the real labels.
*/
function ensureLength(str, maxLength) {
var targetLength = Math.max(4, maxLength);
if (str && str.trim().length >= targetLength / 2) return str;
str = str || '';
for (var i = targetLength - str.length; i > 0; i--) str += ' ';
return str;
}
function setupTraceToggle(g, gd, legendId) {
var doubleClickDelay = gd._context.doubleClickDelay;
var newMouseDownTime;
var numClicks = 1;
var traceToggle = Lib.ensureSingle(g, 'rect', legendId + 'toggle', function (s) {
if (!gd._context.staticPlot) {
s.style('cursor', 'pointer').attr('pointer-events', 'all');
}
s.call(Color.fill, 'rgba(0,0,0,0)');
});
if (gd._context.staticPlot) return;
traceToggle.on('mousedown', function () {
newMouseDownTime = new Date().getTime();
if (newMouseDownTime - gd._legendMouseDownTime < doubleClickDelay) {
// in a click train
numClicks += 1;
} else {
// new click train
numClicks = 1;
gd._legendMouseDownTime = newMouseDownTime;
}
});
traceToggle.on('mouseup', function () {
if (gd._dragged || gd._editing) return;
var legend = gd._fullLayout[legendId];
if (new Date().getTime() - gd._legendMouseDownTime > doubleClickDelay) {
numClicks = Math.max(numClicks - 1, 1);
}
clickOrDoubleClick(gd, legend, g, numClicks, d3.event);
});
}
function textLayout(s, g, gd, legendObj, aTitle) {
if (legendObj._inHover) s.attr('data-notex', true); // do not process MathJax for unified hover
svgTextUtils.convertToTspans(s, gd, function () {
computeTextDimensions(g, gd, legendObj, aTitle);
});
}
function computeTextDimensions(g, gd, legendObj, aTitle) {
var legendItem = g.data()[0][0];
if (!legendObj._inHover && legendItem && !legendItem.trace.showlegend) {
g.remove();
return;
}
var mathjaxGroup = g.select('g[class*=math-group]');
var mathjaxNode = mathjaxGroup.node();
var legendId = getId(legendObj);
if (!legendObj) {
legendObj = gd._fullLayout[legendId];
}
var bw = legendObj.borderwidth;
var font;
if (aTitle === MAIN_TITLE) {
font = legendObj.title.font;
} else if (legendItem.groupTitle) {
font = legendItem.groupTitle.font;
} else {
font = legendObj.font;
}
var lineHeight = font.size * LINE_SPACING;
var height, width;
if (mathjaxNode) {
var mathjaxBB = Drawing.bBox(mathjaxNode);
height = mathjaxBB.height;
width = mathjaxBB.width;
if (aTitle === MAIN_TITLE) {
Drawing.setTranslate(mathjaxGroup, bw, bw + height * 0.75);
} else {
// legend item
Drawing.setTranslate(mathjaxGroup, 0, height * 0.25);
}
} else {
var cls = '.' + legendId + (aTitle === MAIN_TITLE ? 'title' : '') + 'text';
var textEl = g.select(cls);
var textLines = svgTextUtils.lineCount(textEl);
var textNode = textEl.node();
height = lineHeight * textLines;
width = textNode ? Drawing.bBox(textNode).width : 0;
// approximation to height offset to center the font
// to avoid getBoundingClientRect
if (aTitle === MAIN_TITLE) {
if (legendObj.title.side === 'left') {
// add extra space between legend title and itmes
width += constants.itemGap * 2;
}
svgTextUtils.positionText(textEl, bw + constants.titlePad, bw + lineHeight);
} else {
// legend item
var x = constants.itemGap * 2 + legendObj.indentation + legendObj.itemwidth;
if (legendItem.groupTitle) {
x = constants.itemGap;
width -= legendObj.indentation + legendObj.itemwidth;
}
svgTextUtils.positionText(textEl, x, -lineHeight * ((textLines - 1) / 2 - 0.3));
}
}
if (aTitle === MAIN_TITLE) {
legendObj._titleWidth = width;
legendObj._titleHeight = height;
} else {
// legend item
legendItem.lineHeight = lineHeight;
legendItem.height = Math.max(height, 16) + 3;
legendItem.width = width;
}
}
function getTitleSize(legendObj) {
var w = 0;
var h = 0;
var side = legendObj.title.side;
if (side) {
if (side.indexOf('left') !== -1) {
w = legendObj._titleWidth;
}
if (side.indexOf('top') !== -1) {
h = legendObj._titleHeight;
}
}
return [w, h];
}
/*
* Computes in fullLayout[legendId]:
*
* - _height: legend height including items past scrollbox height
* - _maxHeight: maximum legend height before scrollbox is required
* - _effHeight: legend height w/ or w/o scrollbox
*
* - _width: legend width
* - _maxWidth (for orientation:h only): maximum width before starting new row
*/
function computeLegendDimensions(gd, groups, traces, legendObj) {
var fullLayout = gd._fullLayout;
var legendId = getId(legendObj);
if (!legendObj) {
legendObj = fullLayout[legendId];
}
var gs = fullLayout._size;
var isVertical = helpers.isVertical(legendObj);
var isGrouped = helpers.isGrouped(legendObj);
var isFraction = legendObj.entrywidthmode === 'fraction';
var bw = legendObj.borderwidth;
var bw2 = 2 * bw;
var itemGap = constants.itemGap;
var textGap = legendObj.indentation + legendObj.itemwidth + itemGap * 2;
var endPad = 2 * (bw + itemGap);
var yanchor = getYanchor(legendObj);
var isBelowPlotArea = legendObj.y < 0 || legendObj.y === 0 && yanchor === 'top';
var isAbovePlotArea = legendObj.y > 1 || legendObj.y === 1 && yanchor === 'bottom';
var traceGroupGap = legendObj.tracegroupgap;
var legendGroupWidths = {};
// - if below/above plot area, give it the maximum potential margin-push value
// - otherwise, extend the height of the plot area
legendObj._maxHeight = Math.max(isBelowPlotArea || isAbovePlotArea ? fullLayout.height / 2 : gs.h, 30);
var toggleRectWidth = 0;
legendObj._width = 0;
legendObj._height = 0;
var titleSize = getTitleSize(legendObj);
if (isVertical) {
traces.each(function (d) {
var h = d[0].height;
Drawing.setTranslate(this, bw + titleSize[0], bw + titleSize[1] + legendObj._height + h / 2 + itemGap);
legendObj._height += h;
legendObj._width = Math.max(legendObj._width, d[0].width);
});
toggleRectWidth = textGap + legendObj._width;
legendObj._width += itemGap + textGap + bw2;
legendObj._height += endPad;
if (isGrouped) {
groups.each(function (d, i) {
Drawing.setTranslate(this, 0, i * legendObj.tracegroupgap);
});
legendObj._height += (legendObj._lgroupsLength - 1) * legendObj.tracegroupgap;
}
} else {
var xanchor = getXanchor(legendObj);
var isLeftOfPlotArea = legendObj.x < 0 || legendObj.x === 0 && xanchor === 'right';
var isRightOfPlotArea = legendObj.x > 1 || legendObj.x === 1 && xanchor === 'left';
var isBeyondPlotAreaY = isAbovePlotArea || isBelowPlotArea;
var hw = fullLayout.width / 2;
// - if placed within x-margins, extend the width of the plot area
// - else if below/above plot area and anchored in the margin, extend to opposite margin,
// - otherwise give it the maximum potential margin-push value
legendObj._maxWidth = Math.max(isLeftOfPlotArea ? isBeyondPlotAreaY && xanchor === 'left' ? gs.l + gs.w : hw : isRightOfPlotArea ? isBeyondPlotAreaY && xanchor === 'right' ? gs.r + gs.w : hw : gs.w, 2 * textGap);
var maxItemWidth = 0;
var combinedItemWidth = 0;
traces.each(function (d) {
var w = getTraceWidth(d, legendObj, textGap);
maxItemWidth = Math.max(maxItemWidth, w);
combinedItemWidth += w;
});
toggleRectWidth = null;
var maxRowWidth = 0;
if (isGrouped) {
var maxGroupHeightInRow = 0;
var groupOffsetX = 0;
var groupOffsetY = 0;
groups.each(function () {
var maxWidthInGroup = 0;
var offsetY = 0;
d3.select(this).selectAll('g.traces').each(function (d) {
var w = getTraceWidth(d, legendObj, textGap);
var h = d[0].height;
Drawing.setTranslate(this, titleSize[0], titleSize[1] + bw + itemGap + h / 2 + offsetY);
offsetY += h;
maxWidthInGroup = Math.max(maxWidthInGroup, w);
legendGroupWidths[d[0].trace.legendgroup] = maxWidthInGroup;
});
var next = maxWidthInGroup + itemGap;
// horizontal_wrapping
if (
// not on the first column already
groupOffsetX > 0 &&
// goes beyound limit
next + bw + groupOffsetX > legendObj._maxWidth) {
maxRowWidth = Math.max(maxRowWidth, groupOffsetX);
groupOffsetX = 0;
groupOffsetY += maxGroupHeightInRow + traceGroupGap;
maxGroupHeightInRow = offsetY;
} else {
maxGroupHeightInRow = Math.max(maxGroupHeightInRow, offsetY);
}
Drawing.setTranslate(this, groupOffsetX, groupOffsetY);
groupOffsetX += next;
});
legendObj._width = Math.max(maxRowWidth, groupOffsetX) + bw;
legendObj._height = groupOffsetY + maxGroupHeightInRow + endPad;
} else {
var nTraces = traces.size();
var oneRowLegend = combinedItemWidth + bw2 + (nTraces - 1) * itemGap < legendObj._maxWidth;
var maxItemHeightInRow = 0;
var offsetX = 0;
var offsetY = 0;
var rowWidth = 0;
traces.each(function (d) {
var h = d[0].height;
var w = getTraceWidth(d, legendObj, textGap, isGrouped);
var next = oneRowLegend ? w : maxItemWidth;
if (!isFraction) {
next += itemGap;
}
if (next + bw + offsetX - itemGap >= legendObj._maxWidth) {
maxRowWidth = Math.max(maxRowWidth, rowWidth);
offsetX = 0;
offsetY += maxItemHeightInRow;
legendObj._height += maxItemHeightInRow;
maxItemHeightInRow = 0;
}
Drawing.setTranslate(this, titleSize[0] + bw + offsetX, titleSize[1] + bw + offsetY + h / 2 + itemGap);
rowWidth = offsetX + w + itemGap;
offsetX += next;
maxItemHeightInRow = Math.max(maxItemHeightInRow, h);
});
if (oneRowLegend) {
legendObj._width = offsetX + bw2;
legendObj._height = maxItemHeightInRow + endPad;
} else {
legendObj._width = Math.max(maxRowWidth, rowWidth) + bw2;
legendObj._height += maxItemHeightInRow + endPad;
}
}
}
legendObj._width = Math.ceil(Math.max(legendObj._width + titleSize[0], legendObj._titleWidth + 2 * (bw + constants.titlePad)));
legendObj._height = Math.ceil(Math.max(legendObj._height + titleSize[1], legendObj._titleHeight + 2 * (bw + constants.itemGap)));
legendObj._effHeight = Math.min(legendObj._height, legendObj._maxHeight);
var edits = gd._context.edits;
var isEditable = edits.legendText || edits.legendPosition;
traces.each(function (d) {
var traceToggle = d3.select(this).select('.' + legendId + 'toggle');
var h = d[0].height;
var legendgroup = d[0].trace.legendgroup;
var traceWidth = getTraceWidth(d, legendObj, textGap);
if (isGrouped && legendgroup !== '') {
traceWidth = legendGroupWidths[legendgroup];
}
var w = isEditable ? textGap : toggleRectWidth || traceWidth;
if (!isVertical && !isFraction) {
w += itemGap / 2;
}
Drawing.setRect(traceToggle, 0, -h / 2, w, h);
});
}
function expandMargin(gd, legendId, lx, ly) {
var fullLayout = gd._fullLayout;
var legendObj = fullLayout[legendId];
var xanchor = getXanchor(legendObj);
var yanchor = getYanchor(legendObj);
var isPaperX = legendObj.xref === 'paper';
var isPaperY = legendObj.yref === 'paper';
gd._fullLayout._reservedMargin[legendId] = {};
var sideY = legendObj.y < 0.5 ? 'b' : 't';
var sideX = legendObj.x < 0.5 ? 'l' : 'r';
var possibleReservedMargins = {
r: fullLayout.width - lx,
l: lx + legendObj._width,
b: fullLayout.height - ly,
t: ly + legendObj._effHeight
};
if (isPaperX && isPaperY) {
return Plots.autoMargin(gd, legendId, {
x: legendObj.x,
y: legendObj.y,
l: legendObj._width * FROM_TL[xanchor],
r: legendObj._width * FROM_BR[xanchor],
b: legendObj._effHeight * FROM_BR[yanchor],
t: legendObj._effHeight * FROM_TL[yanchor]
});
} else if (isPaperX) {
gd._fullLayout._reservedMargin[legendId][sideY] = possibleReservedMargins[sideY];
} else if (isPaperY) {
gd._fullLayout._reservedMargin[legendId][sideX] = possibleReservedMargins[sideX];
} else {
if (legendObj.orientation === 'v') {
gd._fullLayout._reservedMargin[legendId][sideX] = possibleReservedMargins[sideX];
} else {
gd._fullLayout._reservedMargin[legendId][sideY] = possibleReservedMargins[sideY];
}
}
}
function getXanchor(legendObj) {
return Lib.isRightAnchor(legendObj) ? 'right' : Lib.isCenterAnchor(legendObj) ? 'center' : 'left';
}
function getYanchor(legendObj) {
return Lib.isBottomAnchor(legendObj) ? 'bottom' : Lib.isMiddleAnchor(legendObj) ? 'middle' : 'top';
}
function getId(legendObj) {
return legendObj._id || 'legend';
}
/***/ }),
/***/ 35456:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var helpers = __webpack_require__(42451);
module.exports = function getLegendData(calcdata, opts, hasMultipleLegends) {
var inHover = opts._inHover;
var grouped = helpers.isGrouped(opts);
var reversed = helpers.isReversed(opts);
var lgroupToTraces = {};
var lgroups = [];
var hasOneNonBlankGroup = false;
var slicesShown = {};
var lgroupi = 0;
var maxNameLength = 0;
var i, j;
function addOneItem(legendId, legendGroup, legendItem) {
if (opts.visible === false) return;
if (hasMultipleLegends && legendId !== opts._id) return;
// each '' legend group is treated as a separate group
if (legendGroup === '' || !helpers.isGrouped(opts)) {
// TODO: check this against fullData legendgroups?
var uniqueGroup = '~~i' + lgroupi;
lgroups.push(uniqueGroup);
lgroupToTraces[uniqueGroup] = [legendItem];
lgroupi++;
} else if (lgroups.indexOf(legendGroup) === -1) {
lgroups.push(legendGroup);
hasOneNonBlankGroup = true;
lgroupToTraces[legendGroup] = [legendItem];
} else {
lgroupToTraces[legendGroup].push(legendItem);
}
}
// build an { legendgroup: [cd0, cd0], ... } object
for (i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var cd0 = cd[0];
var trace = cd0.trace;
var lid = trace.legend;
var lgroup = trace.legendgroup;
if (!inHover && (!trace.visible || !trace.showlegend)) continue;
if (Registry.traceIs(trace, 'pie-like')) {
if (!slicesShown[lgroup]) slicesShown[lgroup] = {};
for (j = 0; j < cd.length; j++) {
var labelj = cd[j].label;
if (!slicesShown[lgroup][labelj]) {
addOneItem(lid, lgroup, {
label: labelj,
color: cd[j].color,
i: cd[j].i,
trace: trace,
pts: cd[j].pts
});
slicesShown[lgroup][labelj] = true;
maxNameLength = Math.max(maxNameLength, (labelj || '').length);
}
}
} else {
addOneItem(lid, lgroup, cd0);
maxNameLength = Math.max(maxNameLength, (trace.name || '').length);
}
}
// won't draw a legend in this case
if (!lgroups.length) return [];
// collapse all groups into one if all groups are blank
var shouldCollapse = !hasOneNonBlankGroup || !grouped;
var legendData = [];
for (i = 0; i < lgroups.length; i++) {
var t = lgroupToTraces[lgroups[i]];
if (shouldCollapse) {
legendData.push(t[0]);
} else {
legendData.push(t);
}
}
if (shouldCollapse) legendData = [legendData];
for (i = 0; i < legendData.length; i++) {
// find minimum rank within group
var groupMinRank = Infinity;
for (j = 0; j < legendData[i].length; j++) {
var rank = legendData[i][j].trace.legendrank;
if (groupMinRank > rank) groupMinRank = rank;
}
// record on first group element
legendData[i][0]._groupMinRank = groupMinRank;
legendData[i][0]._preGroupSort = i;
}
var orderFn1 = function (a, b) {
return a[0]._groupMinRank - b[0]._groupMinRank || a[0]._preGroupSort - b[0]._preGroupSort // fallback for old Chrome < 70 https://bugs.chromium.org/p/v8/issues/detail?id=90
;
};
var orderFn2 = function (a, b) {
return a.trace.legendrank - b.trace.legendrank || a._preSort - b._preSort // fallback for old Chrome < 70 https://bugs.chromium.org/p/v8/issues/detail?id=90
;
};
// sort considering minimum group legendrank
legendData.forEach(function (a, k) {
a[0]._preGroupSort = k;
});
legendData.sort(orderFn1);
for (i = 0; i < legendData.length; i++) {
// sort considering trace.legendrank and legend.traceorder
legendData[i].forEach(function (a, k) {
a._preSort = k;
});
legendData[i].sort(orderFn2);
var firstItemTrace = legendData[i][0].trace;
var groupTitle = null;
// get group title text
for (j = 0; j < legendData[i].length; j++) {
var gt = legendData[i][j].trace.legendgrouptitle;
if (gt && gt.text) {
groupTitle = gt;
if (inHover) gt.font = opts._groupTitleFont;
break;
}
}
// reverse order
if (reversed) legendData[i].reverse();
if (groupTitle) {
var hasPieLike = false;
for (j = 0; j < legendData[i].length; j++) {
if (Registry.traceIs(legendData[i][j].trace, 'pie-like')) {
hasPieLike = true;
break;
}
}
// set group title text
legendData[i].unshift({
i: -1,
groupTitle: groupTitle,
noClick: hasPieLike,
trace: {
showlegend: firstItemTrace.showlegend,
legendgroup: firstItemTrace.legendgroup,
visible: opts.groupclick === 'toggleitem' ? true : firstItemTrace.visible
}
});
}
// rearrange lgroupToTraces into a d3-friendly array of arrays
for (j = 0; j < legendData[i].length; j++) {
legendData[i][j] = [legendData[i][j]];
}
}
// number of legend groups - needed in legend/draw.js
opts._lgroupsLength = legendData.length;
// maximum name/label length - needed in legend/draw.js
opts._maxNameLength = maxNameLength;
return legendData;
};
/***/ }),
/***/ 33048:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var pushUnique = Lib.pushUnique;
var SHOWISOLATETIP = true;
module.exports = function handleClick(g, gd, numClicks) {
var fullLayout = gd._fullLayout;
if (gd._dragged || gd._editing) return;
var itemClick = fullLayout.legend.itemclick;
var itemDoubleClick = fullLayout.legend.itemdoubleclick;
var groupClick = fullLayout.legend.groupclick;
if (numClicks === 1 && itemClick === 'toggle' && itemDoubleClick === 'toggleothers' && SHOWISOLATETIP && gd.data && gd._context.showTips) {
Lib.notifier(Lib._(gd, 'Double-click on legend to isolate one trace'), 'long');
SHOWISOLATETIP = false;
} else {
SHOWISOLATETIP = false;
}
var mode;
if (numClicks === 1) mode = itemClick;else if (numClicks === 2) mode = itemDoubleClick;
if (!mode) return;
var toggleGroup = groupClick === 'togglegroup';
var hiddenSlices = fullLayout.hiddenlabels ? fullLayout.hiddenlabels.slice() : [];
var legendItem = g.data()[0][0];
if (legendItem.groupTitle && legendItem.noClick) return;
var fullData = gd._fullData;
var shapesWithLegend = (fullLayout.shapes || []).filter(function (d) {
return d.showlegend;
});
var allLegendItems = fullData.concat(shapesWithLegend);
var fullTrace = legendItem.trace;
if (fullTrace._isShape) {
fullTrace = fullTrace._fullInput;
}
var legendgroup = fullTrace.legendgroup;
var i, j, kcont, key, keys, val;
var dataUpdate = {};
var dataIndices = [];
var carrs = [];
var carrIdx = [];
function insertDataUpdate(traceIndex, value) {
var attrIndex = dataIndices.indexOf(traceIndex);
var valueArray = dataUpdate.visible;
if (!valueArray) {
valueArray = dataUpdate.visible = [];
}
if (dataIndices.indexOf(traceIndex) === -1) {
dataIndices.push(traceIndex);
attrIndex = dataIndices.length - 1;
}
valueArray[attrIndex] = value;
return attrIndex;
}
var updatedShapes = (fullLayout.shapes || []).map(function (d) {
return d._input;
});
var shapesUpdated = false;
function insertShapesUpdate(shapeIndex, value) {
updatedShapes[shapeIndex].visible = value;
shapesUpdated = true;
}
function setVisibility(fullTrace, visibility) {
if (legendItem.groupTitle && !toggleGroup) return;
var fullInput = fullTrace._fullInput || fullTrace;
var isShape = fullInput._isShape;
var index = fullInput.index;
if (index === undefined) index = fullInput._index;
if (Registry.hasTransform(fullInput, 'groupby')) {
var kcont = carrs[index];
if (!kcont) {
var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1];
kcont = Lib.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible');
carrs[index] = kcont;
}
var curState = kcont.get(fullTrace._group);
// If not specified, assume visible. This happens if there are other style
// properties set for a group but not the visibility. There are many similar
// ways to do this (e.g. why not just `curState = fullTrace.visible`??? The
// answer is: because it breaks other things like groupby trace names in
// subtle ways.)
if (curState === undefined) {
curState = true;
}
if (curState !== false) {
// true -> legendonly. All others toggle to true:
kcont.set(fullTrace._group, visibility);
}
carrIdx[index] = insertDataUpdate(index, fullInput.visible === false ? false : true);
} else {
// false -> false (not possible since will not be visible in legend)
// true -> legendonly
// legendonly -> true
var nextVisibility = fullInput.visible === false ? false : visibility;
if (isShape) {
insertShapesUpdate(index, nextVisibility);
} else {
insertDataUpdate(index, nextVisibility);
}
}
}
var thisLegend = fullTrace.legend;
var fullInput = fullTrace._fullInput;
var isShape = fullInput && fullInput._isShape;
if (!isShape && Registry.traceIs(fullTrace, 'pie-like')) {
var thisLabel = legendItem.label;
var thisLabelIndex = hiddenSlices.indexOf(thisLabel);
if (mode === 'toggle') {
if (thisLabelIndex === -1) hiddenSlices.push(thisLabel);else hiddenSlices.splice(thisLabelIndex, 1);
} else if (mode === 'toggleothers') {
var changed = thisLabelIndex !== -1;
var unhideList = [];
for (i = 0; i < gd.calcdata.length; i++) {
var cdi = gd.calcdata[i];
for (j = 0; j < cdi.length; j++) {
var d = cdi[j];
var dLabel = d.label;
// ensure we toggle slices that are in this legend)
if (thisLegend === cdi[0].trace.legend) {
if (thisLabel !== dLabel) {
if (hiddenSlices.indexOf(dLabel) === -1) changed = true;
pushUnique(hiddenSlices, dLabel);
unhideList.push(dLabel);
}
}
}
}
if (!changed) {
for (var q = 0; q < unhideList.length; q++) {
var pos = hiddenSlices.indexOf(unhideList[q]);
if (pos !== -1) {
hiddenSlices.splice(pos, 1);
}
}
}
}
Registry.call('_guiRelayout', gd, 'hiddenlabels', hiddenSlices);
} else {
var hasLegendgroup = legendgroup && legendgroup.length;
var traceIndicesInGroup = [];
var tracei;
if (hasLegendgroup) {
for (i = 0; i < allLegendItems.length; i++) {
tracei = allLegendItems[i];
if (!tracei.visible) continue;
if (tracei.legendgroup === legendgroup) {
traceIndicesInGroup.push(i);
}
}
}
if (mode === 'toggle') {
var nextVisibility;
switch (fullTrace.visible) {
case true:
nextVisibility = 'legendonly';
break;
case false:
nextVisibility = false;
break;
case 'legendonly':
nextVisibility = true;
break;
}
if (hasLegendgroup) {
if (toggleGroup) {
for (i = 0; i < allLegendItems.length; i++) {
var item = allLegendItems[i];
if (item.visible !== false && item.legendgroup === legendgroup) {
setVisibility(item, nextVisibility);
}
}
} else {
setVisibility(fullTrace, nextVisibility);
}
} else {
setVisibility(fullTrace, nextVisibility);
}
} else if (mode === 'toggleothers') {
// Compute the clicked index. expandedIndex does what we want for expanded traces
// but also culls hidden traces. That means we have some work to do.
var isClicked, isInGroup, notInLegend, otherState, _item;
var isIsolated = true;
for (i = 0; i < allLegendItems.length; i++) {
_item = allLegendItems[i];
isClicked = _item === fullTrace;
notInLegend = _item.showlegend !== true;
if (isClicked || notInLegend) continue;
isInGroup = hasLegendgroup && _item.legendgroup === legendgroup;
if (!isInGroup && _item.legend === thisLegend && _item.visible === true && !Registry.traceIs(_item, 'notLegendIsolatable')) {
isIsolated = false;
break;
}
}
for (i = 0; i < allLegendItems.length; i++) {
_item = allLegendItems[i];
// False is sticky; we don't change it. Also ensure we don't change states of itmes in other legend
if (_item.visible === false || _item.legend !== thisLegend) continue;
if (Registry.traceIs(_item, 'notLegendIsolatable')) {
continue;
}
switch (fullTrace.visible) {
case 'legendonly':
setVisibility(_item, true);
break;
case true:
otherState = isIsolated ? true : 'legendonly';
isClicked = _item === fullTrace;
// N.B. consider traces that have a set legendgroup as toggleable
notInLegend = _item.showlegend !== true && !_item.legendgroup;
isInGroup = isClicked || hasLegendgroup && _item.legendgroup === legendgroup;
setVisibility(_item, isInGroup || notInLegend ? true : otherState);
break;
}
}
}
for (i = 0; i < carrs.length; i++) {
kcont = carrs[i];
if (!kcont) continue;
var update = kcont.constructUpdate();
var updateKeys = Object.keys(update);
for (j = 0; j < updateKeys.length; j++) {
key = updateKeys[j];
val = dataUpdate[key] = dataUpdate[key] || [];
val[carrIdx[i]] = update[key];
}
}
// The length of the value arrays should be equal and any unspecified
// values should be explicitly undefined for them to get properly culled
// as updates and not accidentally reset to the default value. This fills
// out sparse arrays with the required number of undefined values:
keys = Object.keys(dataUpdate);
for (i = 0; i < keys.length; i++) {
key = keys[i];
for (j = 0; j < dataIndices.length; j++) {
// Use hasOwnProperty to protect against falsy values:
if (!dataUpdate[key].hasOwnProperty(j)) {
dataUpdate[key][j] = undefined;
}
}
}
if (shapesUpdated) {
Registry.call('_guiUpdate', gd, dataUpdate, {
shapes: updatedShapes
}, dataIndices);
} else {
Registry.call('_guiRestyle', gd, dataUpdate, dataIndices);
}
}
};
/***/ }),
/***/ 42451:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
exports.isGrouped = function isGrouped(legendLayout) {
return (legendLayout.traceorder || '').indexOf('grouped') !== -1;
};
exports.isVertical = function isVertical(legendLayout) {
return legendLayout.orientation !== 'h';
};
exports.isReversed = function isReversed(legendLayout) {
return (legendLayout.traceorder || '').indexOf('reversed') !== -1;
};
/***/ }),
/***/ 2780:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'component',
name: 'legend',
layoutAttributes: __webpack_require__(3800),
supplyLayoutDefaults: __webpack_require__(77864),
draw: __webpack_require__(31140),
style: __webpack_require__(2012)
};
/***/ }),
/***/ 2012:
/***/ (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 strTranslate = Lib.strTranslate;
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var extractOpts = (__webpack_require__(94288).extractOpts);
var subTypes = __webpack_require__(43028);
var stylePie = __webpack_require__(10528);
var pieCastOption = (__webpack_require__(69656).castOption);
var constants = __webpack_require__(65196);
var CST_MARKER_SIZE = 12;
var CST_LINE_WIDTH = 5;
var CST_MARKER_LINE_WIDTH = 2;
var MAX_LINE_WIDTH = 10;
var MAX_MARKER_LINE_WIDTH = 5;
module.exports = function style(s, gd, legend) {
var fullLayout = gd._fullLayout;
if (!legend) legend = fullLayout.legend;
var constantItemSizing = legend.itemsizing === 'constant';
var itemWidth = legend.itemwidth;
var centerPos = (itemWidth + constants.itemGap * 2) / 2;
var centerTransform = strTranslate(centerPos, 0);
var boundLineWidth = function (mlw, cont, max, cst) {
var v;
if (mlw + 1) {
v = mlw;
} else if (cont && cont.width > 0) {
v = cont.width;
} else {
return 0;
}
return constantItemSizing ? cst : Math.min(v, max);
};
s.each(function (d) {
var traceGroup = d3.select(this);
var layers = Lib.ensureSingle(traceGroup, 'g', 'layers');
layers.style('opacity', d[0].trace.opacity);
var indentation = legend.indentation;
var valign = legend.valign;
var lineHeight = d[0].lineHeight;
var height = d[0].height;
if (valign === 'middle' && indentation === 0 || !lineHeight || !height) {
layers.attr('transform', null);
} else {
var factor = {
top: 1,
bottom: -1
}[valign];
var markerOffsetY = factor * (0.5 * (lineHeight - height + 3)) || 0;
var markerOffsetX = legend.indentation;
layers.attr('transform', strTranslate(markerOffsetX, markerOffsetY));
}
var fill = layers.selectAll('g.legendfill').data([d]);
fill.enter().append('g').classed('legendfill', true);
var line = layers.selectAll('g.legendlines').data([d]);
line.enter().append('g').classed('legendlines', true);
var symbol = layers.selectAll('g.legendsymbols').data([d]);
symbol.enter().append('g').classed('legendsymbols', true);
symbol.selectAll('g.legendpoints').data([d]).enter().append('g').classed('legendpoints', true);
}).each(styleSpatial).each(styleWaterfalls).each(styleFunnels).each(styleBars).each(styleBoxes).each(styleFunnelareas).each(stylePies).each(styleLines).each(stylePoints).each(styleCandles).each(styleOHLC);
function styleLines(d) {
var styleGuide = getStyleGuide(d);
var showFill = styleGuide.showFill;
var showLine = styleGuide.showLine;
var showGradientLine = styleGuide.showGradientLine;
var showGradientFill = styleGuide.showGradientFill;
var anyFill = styleGuide.anyFill;
var anyLine = styleGuide.anyLine;
var d0 = d[0];
var trace = d0.trace;
var dMod, tMod;
var cOpts = extractOpts(trace);
var colorscale = cOpts.colorscale;
var reversescale = cOpts.reversescale;
var fillStyle = function (s) {
if (s.size()) {
if (showFill) {
Drawing.fillGroupStyle(s, gd, true);
} else {
var gradientID = 'legendfill-' + trace.uid;
Drawing.gradient(s, gd, gradientID, getGradientDirection(reversescale), colorscale, 'fill');
}
}
};
var lineGradient = function (s) {
if (s.size()) {
var gradientID = 'legendline-' + trace.uid;
Drawing.lineGroupStyle(s);
Drawing.gradient(s, gd, gradientID, getGradientDirection(reversescale), colorscale, 'stroke');
}
};
// with fill and no markers or text, move the line and fill up a bit
// so it's more centered
var pathStart = subTypes.hasMarkers(trace) || !anyFill ? 'M5,0' :
// with a line leave it slightly below center, to leave room for the
// line thickness and because the line is usually more prominent
anyLine ? 'M5,-2' : 'M5,-3';
var this3 = d3.select(this);
var fill = this3.select('.legendfill').selectAll('path').data(showFill || showGradientFill ? [d] : []);
fill.enter().append('path').classed('js-fill', true);
fill.exit().remove();
fill.attr('d', pathStart + 'h' + itemWidth + 'v6h-' + itemWidth + 'z').call(fillStyle);
if (showLine || showGradientLine) {
var lw = boundLineWidth(undefined, trace.line, MAX_LINE_WIDTH, CST_LINE_WIDTH);
tMod = Lib.minExtend(trace, {
line: {
width: lw
}
});
dMod = [Lib.minExtend(d0, {
trace: tMod
})];
}
var line = this3.select('.legendlines').selectAll('path').data(showLine || showGradientLine ? [dMod] : []);
line.enter().append('path').classed('js-line', true);
line.exit().remove();
// this is ugly... but you can't apply a gradient to a perfectly
// horizontal or vertical line. Presumably because then
// the system doesn't know how to scale vertical variation, even
// though there *is* no vertical variation in this case.
// so add an invisibly small angle to the line
// This issue (and workaround) exist across (Mac) Chrome, FF, and Safari
line.attr('d', pathStart + (showGradientLine ? 'l' + itemWidth + ',0.0001' : 'h' + itemWidth)).call(showLine ? Drawing.lineGroupStyle : lineGradient);
}
function stylePoints(d) {
var styleGuide = getStyleGuide(d);
var anyFill = styleGuide.anyFill;
var anyLine = styleGuide.anyLine;
var showLine = styleGuide.showLine;
var showMarker = styleGuide.showMarker;
var d0 = d[0];
var trace = d0.trace;
var showText = !showMarker && !anyLine && !anyFill && subTypes.hasText(trace);
var dMod, tMod;
// 'scatter3d' don't use gd.calcdata,
// use d0.trace to infer arrayOk attributes
function boundVal(attrIn, arrayToValFn, bounds, cst) {
var valIn = Lib.nestedProperty(trace, attrIn).get();
var valToBound = Lib.isArrayOrTypedArray(valIn) && arrayToValFn ? arrayToValFn(valIn) : valIn;
if (constantItemSizing && valToBound && cst !== undefined) {
valToBound = cst;
}
if (bounds) {
if (valToBound < bounds[0]) return bounds[0];else if (valToBound > bounds[1]) return bounds[1];
}
return valToBound;
}
function pickFirst(array) {
if (d0._distinct && d0.index && array[d0.index]) return array[d0.index];
return array[0];
}
// constrain text, markers, etc so they'll fit on the legend
if (showMarker || showText || showLine) {
var dEdit = {};
var tEdit = {};
if (showMarker) {
dEdit.mc = boundVal('marker.color', pickFirst);
dEdit.mx = boundVal('marker.symbol', pickFirst);
dEdit.mo = boundVal('marker.opacity', Lib.mean, [0.2, 1]);
dEdit.mlc = boundVal('marker.line.color', pickFirst);
dEdit.mlw = boundVal('marker.line.width', Lib.mean, [0, 5], CST_MARKER_LINE_WIDTH);
tEdit.marker = {
sizeref: 1,
sizemin: 1,
sizemode: 'diameter'
};
var ms = boundVal('marker.size', Lib.mean, [2, 16], CST_MARKER_SIZE);
dEdit.ms = ms;
tEdit.marker.size = ms;
}
if (showLine) {
tEdit.line = {
width: boundVal('line.width', pickFirst, [0, 10], CST_LINE_WIDTH)
};
}
if (showText) {
dEdit.tx = 'Aa';
dEdit.tp = boundVal('textposition', pickFirst);
dEdit.ts = 10;
dEdit.tc = boundVal('textfont.color', pickFirst);
dEdit.tf = boundVal('textfont.family', pickFirst);
dEdit.tw = boundVal('textfont.weight', pickFirst);
dEdit.ty = boundVal('textfont.style', pickFirst);
dEdit.tv = boundVal('textfont.variant', pickFirst);
dEdit.tC = boundVal('textfont.textcase', pickFirst);
dEdit.tE = boundVal('textfont.lineposition', pickFirst);
dEdit.tS = boundVal('textfont.shadow', pickFirst);
}
dMod = [Lib.minExtend(d0, dEdit)];
tMod = Lib.minExtend(trace, tEdit);
// always show legend items in base state
tMod.selectedpoints = null;
// never show texttemplate
tMod.texttemplate = null;
}
var ptgroup = d3.select(this).select('g.legendpoints');
var pts = ptgroup.selectAll('path.scatterpts').data(showMarker ? dMod : []);
// make sure marker is on the bottom, in case it enters after text
pts.enter().insert('path', ':first-child').classed('scatterpts', true).attr('transform', centerTransform);
pts.exit().remove();
pts.call(Drawing.pointStyle, tMod, gd);
// 'mrc' is set in pointStyle and used in textPointStyle:
// constrain it here
if (showMarker) dMod[0].mrc = 3;
var txt = ptgroup.selectAll('g.pointtext').data(showText ? dMod : []);
txt.enter().append('g').classed('pointtext', true).append('text').attr('transform', centerTransform);
txt.exit().remove();
txt.selectAll('text').call(Drawing.textPointStyle, tMod, gd);
}
function styleWaterfalls(d) {
var trace = d[0].trace;
var isWaterfall = trace.type === 'waterfall';
if (d[0]._distinct && isWaterfall) {
var cont = d[0].trace[d[0].dir].marker;
d[0].mc = cont.color;
d[0].mlw = cont.line.width;
d[0].mlc = cont.line.color;
return styleBarLike(d, this, 'waterfall');
}
var ptsData = [];
if (trace.visible && isWaterfall) {
ptsData = d[0].hasTotals ? [['increasing', 'M-6,-6V6H0Z'], ['totals', 'M6,6H0L-6,-6H-0Z'], ['decreasing', 'M6,6V-6H0Z']] : [['increasing', 'M-6,-6V6H6Z'], ['decreasing', 'M6,6V-6H-6Z']];
}
var pts = d3.select(this).select('g.legendpoints').selectAll('path.legendwaterfall').data(ptsData);
pts.enter().append('path').classed('legendwaterfall', true).attr('transform', centerTransform).style('stroke-miterlimit', 1);
pts.exit().remove();
pts.each(function (dd) {
var pt = d3.select(this);
var cont = trace[dd[0]].marker;
var lw = boundLineWidth(undefined, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
pt.attr('d', dd[1]).style('stroke-width', lw + 'px').call(Color.fill, cont.color);
if (lw) {
pt.call(Color.stroke, cont.line.color);
}
});
}
function styleBars(d) {
styleBarLike(d, this);
}
function styleFunnels(d) {
styleBarLike(d, this, 'funnel');
}
function styleBarLike(d, lThis, desiredType) {
var trace = d[0].trace;
var marker = trace.marker || {};
var markerLine = marker.line || {};
// If bar has rounded corners, round corners of legend icon
var pathStr = marker.cornerradius ? 'M6,3a3,3,0,0,1-3,3H-3a3,3,0,0,1-3-3V-3a3,3,0,0,1,3-3H3a3,3,0,0,1,3,3Z' :
// Square with rounded corners
'M6,6H-6V-6H6Z'; // Normal square
var isVisible = !desiredType ? Registry.traceIs(trace, 'bar') : trace.visible && trace.type === desiredType;
var barpath = d3.select(lThis).select('g.legendpoints').selectAll('path.legend' + desiredType).data(isVisible ? [d] : []);
barpath.enter().append('path').classed('legend' + desiredType, true).attr('d', pathStr).attr('transform', centerTransform);
barpath.exit().remove();
barpath.each(function (d) {
var p = d3.select(this);
var d0 = d[0];
var w = boundLineWidth(d0.mlw, marker.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
p.style('stroke-width', w + 'px');
var mcc = d0.mcc;
if (!legend._inHover && 'mc' in d0) {
// not in unified hover but
// for legend use the color in the middle of scale
var cOpts = extractOpts(marker);
var mid = cOpts.mid;
if (mid === undefined) mid = (cOpts.max + cOpts.min) / 2;
mcc = Drawing.tryColorscale(marker, '')(mid);
}
var fillColor = mcc || d0.mc || marker.color;
var markerPattern = marker.pattern;
var patternShape = markerPattern && Drawing.getPatternAttr(markerPattern.shape, 0, '');
if (patternShape) {
var patternBGColor = Drawing.getPatternAttr(markerPattern.bgcolor, 0, null);
var patternFGColor = Drawing.getPatternAttr(markerPattern.fgcolor, 0, null);
var patternFGOpacity = markerPattern.fgopacity;
var patternSize = dimAttr(markerPattern.size, 8, 10);
var patternSolidity = dimAttr(markerPattern.solidity, 0.5, 1);
var patternID = 'legend-' + trace.uid;
p.call(Drawing.pattern, 'legend', gd, patternID, patternShape, patternSize, patternSolidity, mcc, markerPattern.fillmode, patternBGColor, patternFGColor, patternFGOpacity);
} else {
p.call(Color.fill, fillColor);
}
if (w) Color.stroke(p, d0.mlc || markerLine.color);
});
}
function styleBoxes(d) {
var trace = d[0].trace;
var pts = d3.select(this).select('g.legendpoints').selectAll('path.legendbox').data(trace.visible && Registry.traceIs(trace, 'box-violin') ? [d] : []);
pts.enter().append('path').classed('legendbox', true)
// if we want the median bar, prepend M6,0H-6
.attr('d', 'M6,6H-6V-6H6Z').attr('transform', centerTransform);
pts.exit().remove();
pts.each(function () {
var p = d3.select(this);
if ((trace.boxpoints === 'all' || trace.points === 'all') && Color.opacity(trace.fillcolor) === 0 && Color.opacity((trace.line || {}).color) === 0) {
var tMod = Lib.minExtend(trace, {
marker: {
size: constantItemSizing ? CST_MARKER_SIZE : Lib.constrain(trace.marker.size, 2, 16),
sizeref: 1,
sizemin: 1,
sizemode: 'diameter'
}
});
pts.call(Drawing.pointStyle, tMod, gd);
} else {
var w = boundLineWidth(undefined, trace.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
p.style('stroke-width', w + 'px').call(Color.fill, trace.fillcolor);
if (w) Color.stroke(p, trace.line.color);
}
});
}
function styleCandles(d) {
var trace = d[0].trace;
var pts = d3.select(this).select('g.legendpoints').selectAll('path.legendcandle').data(trace.visible && trace.type === 'candlestick' ? [d, d] : []);
pts.enter().append('path').classed('legendcandle', true).attr('d', function (_, i) {
if (i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing
return 'M15,0H8M8,-6V6H-8Z'; // decreasing
}).attr('transform', centerTransform).style('stroke-miterlimit', 1);
pts.exit().remove();
pts.each(function (_, i) {
var p = d3.select(this);
var cont = trace[i ? 'increasing' : 'decreasing'];
var w = boundLineWidth(undefined, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
p.style('stroke-width', w + 'px').call(Color.fill, cont.fillcolor);
if (w) Color.stroke(p, cont.line.color);
});
}
function styleOHLC(d) {
var trace = d[0].trace;
var pts = d3.select(this).select('g.legendpoints').selectAll('path.legendohlc').data(trace.visible && trace.type === 'ohlc' ? [d, d] : []);
pts.enter().append('path').classed('legendohlc', true).attr('d', function (_, i) {
if (i) return 'M-15,0H0M-8,-6V0'; // increasing
return 'M15,0H0M8,6V0'; // decreasing
}).attr('transform', centerTransform).style('stroke-miterlimit', 1);
pts.exit().remove();
pts.each(function (_, i) {
var p = d3.select(this);
var cont = trace[i ? 'increasing' : 'decreasing'];
var w = boundLineWidth(undefined, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
p.style('fill', 'none').call(Drawing.dashLine, cont.line.dash, w);
if (w) Color.stroke(p, cont.line.color);
});
}
function stylePies(d) {
stylePieLike(d, this, 'pie');
}
function styleFunnelareas(d) {
stylePieLike(d, this, 'funnelarea');
}
function stylePieLike(d, lThis, desiredType) {
var d0 = d[0];
var trace = d0.trace;
var isVisible = !desiredType ? Registry.traceIs(trace, desiredType) : trace.visible && trace.type === desiredType;
var pts = d3.select(lThis).select('g.legendpoints').selectAll('path.legend' + desiredType).data(isVisible ? [d] : []);
pts.enter().append('path').classed('legend' + desiredType, true).attr('d', 'M6,6H-6V-6H6Z').attr('transform', centerTransform);
pts.exit().remove();
if (pts.size()) {
var cont = trace.marker || {};
var lw = boundLineWidth(pieCastOption(cont.line.width, d0.pts), cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
var opt = 'pieLike';
var tMod = Lib.minExtend(trace, {
marker: {
line: {
width: lw
}
}
}, opt);
var d0Mod = Lib.minExtend(d0, {
trace: tMod
}, opt);
stylePie(pts, d0Mod, tMod, gd);
}
}
function styleSpatial(d) {
// i.e. maninly traces having z and colorscale
var trace = d[0].trace;
var useGradient;
var ptsData = [];
if (trace.visible) {
switch (trace.type) {
case 'histogram2d':
case 'heatmap':
ptsData = [['M-15,-2V4H15V-2Z'] // similar to contour
];
useGradient = true;
break;
case 'choropleth':
case 'choroplethmapbox':
ptsData = [['M-6,-6V6H6V-6Z']];
useGradient = true;
break;
case 'densitymapbox':
ptsData = [['M-6,0 a6,6 0 1,0 12,0 a 6,6 0 1,0 -12,0']];
useGradient = 'radial';
break;
case 'cone':
ptsData = [['M-6,2 A2,2 0 0,0 -6,6 V6L6,4Z'], ['M-6,-6 A2,2 0 0,0 -6,-2 L6,-4Z'], ['M-6,-2 A2,2 0 0,0 -6,2 L6,0Z']];
useGradient = false;
break;
case 'streamtube':
ptsData = [['M-6,2 A2,2 0 0,0 -6,6 H6 A2,2 0 0,1 6,2 Z'], ['M-6,-6 A2,2 0 0,0 -6,-2 H6 A2,2 0 0,1 6,-6 Z'], ['M-6,-2 A2,2 0 0,0 -6,2 H6 A2,2 0 0,1 6,-2 Z']];
useGradient = false;
break;
case 'surface':
ptsData = [['M-6,-6 A2,3 0 0,0 -6,0 H6 A2,3 0 0,1 6,-6 Z'], ['M-6,1 A2,3 0 0,1 -6,6 H6 A2,3 0 0,0 6,0 Z']];
useGradient = true;
break;
case 'mesh3d':
ptsData = [['M-6,6H0L-6,-6Z'], ['M6,6H0L6,-6Z'], ['M-6,-6H6L0,6Z']];
useGradient = false;
break;
case 'volume':
ptsData = [['M-6,6H0L-6,-6Z'], ['M6,6H0L6,-6Z'], ['M-6,-6H6L0,6Z']];
useGradient = true;
break;
case 'isosurface':
ptsData = [['M-6,6H0L-6,-6Z'], ['M6,6H0L6,-6Z'], ['M-6,-6 A12,24 0 0,0 6,-6 L0,6Z']];
useGradient = false;
break;
}
}
var pts = d3.select(this).select('g.legendpoints').selectAll('path.legend3dandfriends').data(ptsData);
pts.enter().append('path').classed('legend3dandfriends', true).attr('transform', centerTransform).style('stroke-miterlimit', 1);
pts.exit().remove();
pts.each(function (dd, i) {
var pt = d3.select(this);
var cOpts = extractOpts(trace);
var colorscale = cOpts.colorscale;
var reversescale = cOpts.reversescale;
var fillGradient = function (s) {
if (s.size()) {
var gradientID = 'legendfill-' + trace.uid;
Drawing.gradient(s, gd, gradientID, getGradientDirection(reversescale, useGradient === 'radial'), colorscale, 'fill');
}
};
var fillColor;
if (!colorscale) {
var color = trace.vertexcolor || trace.facecolor || trace.color;
fillColor = Lib.isArrayOrTypedArray(color) ? color[i] || color[0] : color;
} else {
if (!useGradient) {
var len = colorscale.length;
fillColor = i === 0 ? colorscale[reversescale ? len - 1 : 0][1] :
// minimum
i === 1 ? colorscale[reversescale ? 0 : len - 1][1] :
// maximum
colorscale[Math.floor((len - 1) / 2)][1]; // middle
}
}
pt.attr('d', dd[0]);
if (fillColor) {
pt.call(Color.fill, fillColor);
} else {
pt.call(fillGradient);
}
});
}
};
function getGradientDirection(reversescale, isRadial) {
var str = isRadial ? 'radial' : 'horizontal';
return str + (reversescale ? '' : 'reversed');
}
function getStyleGuide(d) {
var trace = d[0].trace;
var contours = trace.contours;
var showLine = subTypes.hasLines(trace);
var showMarker = subTypes.hasMarkers(trace);
var showFill = trace.visible && trace.fill && trace.fill !== 'none';
var showGradientLine = false;
var showGradientFill = false;
if (contours) {
var coloring = contours.coloring;
if (coloring === 'lines') {
showGradientLine = true;
} else {
showLine = coloring === 'none' || coloring === 'heatmap' || contours.showlines;
}
if (contours.type === 'constraint') {
showFill = contours._operation !== '=';
} else if (coloring === 'fill' || coloring === 'heatmap') {
showGradientFill = true;
}
}
return {
showMarker: showMarker,
showLine: showLine,
showFill: showFill,
showGradientLine: showGradientLine,
showGradientFill: showGradientFill,
anyLine: showLine || showGradientLine,
anyFill: showFill || showGradientFill
};
}
function dimAttr(v, dflt, max) {
if (v && Lib.isArrayOrTypedArray(v)) return dflt;
if (v > max) return max;
return v;
}
/***/ }),
/***/ 66540:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(76052);
module.exports = {
editType: 'modebar',
orientation: {
valType: 'enumerated',
values: ['v', 'h'],
dflt: 'h',
editType: 'modebar'
},
bgcolor: {
valType: 'color',
editType: 'modebar'
},
color: {
valType: 'color',
editType: 'modebar'
},
activecolor: {
valType: 'color',
editType: 'modebar'
},
uirevision: {
valType: 'any',
editType: 'none'
},
add: {
valType: 'string',
arrayOk: true,
dflt: '',
editType: 'modebar'
},
remove: {
valType: 'string',
arrayOk: true,
dflt: '',
editType: 'modebar'
}
};
/***/ }),
/***/ 44248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Plots = __webpack_require__(7316);
var axisIds = __webpack_require__(79811);
var Icons = __webpack_require__(9224);
var eraseActiveShape = (__webpack_require__(4016).eraseActiveShape);
var Lib = __webpack_require__(3400);
var _ = Lib._;
var modeBarButtons = module.exports = {};
/**
* ModeBar buttons configuration
*
* @param {string} name
* name / id of the buttons (for tracking)
* @param {string} title
* text that appears while hovering over the button,
* enter null, false or '' for no hover text
* @param {string} icon
* svg icon object associated with the button
* can be linked to Plotly.Icons to use the default plotly icons
* @param {string} [gravity]
* icon positioning
* @param {function} click
* click handler associated with the button, a function of
* 'gd' (the main graph object) and
* 'ev' (the event object)
* @param {string} [attr]
* attribute associated with button,
* use this with 'val' to keep track of the state
* @param {*} [val]
* initial 'attr' value, can be a function of gd
* @param {boolean} [toggle]
* is the button a toggle button?
*/
modeBarButtons.toImage = {
name: 'toImage',
title: function (gd) {
var opts = gd._context.toImageButtonOptions || {};
var format = opts.format || 'png';
return format === 'png' ? _(gd, 'Download plot as a png') :
// legacy text
_(gd, 'Download plot'); // generic non-PNG text
},
icon: Icons.camera,
click: function (gd) {
var toImageButtonOptions = gd._context.toImageButtonOptions;
var opts = {
format: toImageButtonOptions.format || 'png'
};
Lib.notifier(_(gd, 'Taking snapshot - this may take a few seconds'), 'long');
if (opts.format !== 'svg' && Lib.isIE()) {
Lib.notifier(_(gd, 'IE only supports svg. Changing format to svg.'), 'long');
opts.format = 'svg';
}
['filename', 'width', 'height', 'scale'].forEach(function (key) {
if (key in toImageButtonOptions) {
opts[key] = toImageButtonOptions[key];
}
});
Registry.call('downloadImage', gd, opts).then(function (filename) {
Lib.notifier(_(gd, 'Snapshot succeeded') + ' - ' + filename, 'long');
}).catch(function () {
Lib.notifier(_(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long');
});
}
};
modeBarButtons.sendDataToCloud = {
name: 'sendDataToCloud',
title: function (gd) {
return _(gd, 'Edit in Chart Studio');
},
icon: Icons.disk,
click: function (gd) {
Plots.sendDataToCloud(gd);
}
};
modeBarButtons.editInChartStudio = {
name: 'editInChartStudio',
title: function (gd) {
return _(gd, 'Edit in Chart Studio');
},
icon: Icons.pencil,
click: function (gd) {
Plots.sendDataToCloud(gd);
}
};
modeBarButtons.zoom2d = {
name: 'zoom2d',
_cat: 'zoom',
title: function (gd) {
return _(gd, 'Zoom');
},
attr: 'dragmode',
val: 'zoom',
icon: Icons.zoombox,
click: handleCartesian
};
modeBarButtons.pan2d = {
name: 'pan2d',
_cat: 'pan',
title: function (gd) {
return _(gd, 'Pan');
},
attr: 'dragmode',
val: 'pan',
icon: Icons.pan,
click: handleCartesian
};
modeBarButtons.select2d = {
name: 'select2d',
_cat: 'select',
title: function (gd) {
return _(gd, 'Box Select');
},
attr: 'dragmode',
val: 'select',
icon: Icons.selectbox,
click: handleCartesian
};
modeBarButtons.lasso2d = {
name: 'lasso2d',
_cat: 'lasso',
title: function (gd) {
return _(gd, 'Lasso Select');
},
attr: 'dragmode',
val: 'lasso',
icon: Icons.lasso,
click: handleCartesian
};
modeBarButtons.drawclosedpath = {
name: 'drawclosedpath',
title: function (gd) {
return _(gd, 'Draw closed freeform');
},
attr: 'dragmode',
val: 'drawclosedpath',
icon: Icons.drawclosedpath,
click: handleCartesian
};
modeBarButtons.drawopenpath = {
name: 'drawopenpath',
title: function (gd) {
return _(gd, 'Draw open freeform');
},
attr: 'dragmode',
val: 'drawopenpath',
icon: Icons.drawopenpath,
click: handleCartesian
};
modeBarButtons.drawline = {
name: 'drawline',
title: function (gd) {
return _(gd, 'Draw line');
},
attr: 'dragmode',
val: 'drawline',
icon: Icons.drawline,
click: handleCartesian
};
modeBarButtons.drawrect = {
name: 'drawrect',
title: function (gd) {
return _(gd, 'Draw rectangle');
},
attr: 'dragmode',
val: 'drawrect',
icon: Icons.drawrect,
click: handleCartesian
};
modeBarButtons.drawcircle = {
name: 'drawcircle',
title: function (gd) {
return _(gd, 'Draw circle');
},
attr: 'dragmode',
val: 'drawcircle',
icon: Icons.drawcircle,
click: handleCartesian
};
modeBarButtons.eraseshape = {
name: 'eraseshape',
title: function (gd) {
return _(gd, 'Erase active shape');
},
icon: Icons.eraseshape,
click: eraseActiveShape
};
modeBarButtons.zoomIn2d = {
name: 'zoomIn2d',
_cat: 'zoomin',
title: function (gd) {
return _(gd, 'Zoom in');
},
attr: 'zoom',
val: 'in',
icon: Icons.zoom_plus,
click: handleCartesian
};
modeBarButtons.zoomOut2d = {
name: 'zoomOut2d',
_cat: 'zoomout',
title: function (gd) {
return _(gd, 'Zoom out');
},
attr: 'zoom',
val: 'out',
icon: Icons.zoom_minus,
click: handleCartesian
};
modeBarButtons.autoScale2d = {
name: 'autoScale2d',
_cat: 'autoscale',
title: function (gd) {
return _(gd, 'Autoscale');
},
attr: 'zoom',
val: 'auto',
icon: Icons.autoscale,
click: handleCartesian
};
modeBarButtons.resetScale2d = {
name: 'resetScale2d',
_cat: 'resetscale',
title: function (gd) {
return _(gd, 'Reset axes');
},
attr: 'zoom',
val: 'reset',
icon: Icons.home,
click: handleCartesian
};
modeBarButtons.hoverClosestCartesian = {
name: 'hoverClosestCartesian',
_cat: 'hoverclosest',
title: function (gd) {
return _(gd, 'Show closest data on hover');
},
attr: 'hovermode',
val: 'closest',
icon: Icons.tooltip_basic,
gravity: 'ne',
click: handleCartesian
};
modeBarButtons.hoverCompareCartesian = {
name: 'hoverCompareCartesian',
_cat: 'hoverCompare',
title: function (gd) {
return _(gd, 'Compare data on hover');
},
attr: 'hovermode',
val: function (gd) {
return gd._fullLayout._isHoriz ? 'y' : 'x';
},
icon: Icons.tooltip_compare,
gravity: 'ne',
click: handleCartesian
};
function handleCartesian(gd, ev) {
var button = ev.currentTarget;
var astr = button.getAttribute('data-attr');
var val = button.getAttribute('data-val') || true;
var fullLayout = gd._fullLayout;
var aobj = {};
var axList = axisIds.list(gd, null, true);
var allSpikesEnabled = fullLayout._cartesianSpikesEnabled;
var ax, i;
if (astr === 'zoom') {
var mag = val === 'in' ? 0.5 : 2;
var r0 = (1 + mag) / 2;
var r1 = (1 - mag) / 2;
var axName;
for (i = 0; i < axList.length; i++) {
ax = axList[i];
if (!ax.fixedrange) {
axName = ax._name;
if (val === 'auto') {
aobj[axName + '.autorange'] = true;
} else if (val === 'reset') {
if (ax._rangeInitial0 === undefined && ax._rangeInitial1 === undefined) {
aobj[axName + '.autorange'] = true;
} else if (ax._rangeInitial0 === undefined) {
aobj[axName + '.autorange'] = ax._autorangeInitial;
aobj[axName + '.range'] = [null, ax._rangeInitial1];
} else if (ax._rangeInitial1 === undefined) {
aobj[axName + '.range'] = [ax._rangeInitial0, null];
aobj[axName + '.autorange'] = ax._autorangeInitial;
} else {
aobj[axName + '.range'] = [ax._rangeInitial0, ax._rangeInitial1];
}
// N.B. "reset" also resets showspikes
if (ax._showSpikeInitial !== undefined) {
aobj[axName + '.showspikes'] = ax._showSpikeInitial;
if (allSpikesEnabled === 'on' && !ax._showSpikeInitial) {
allSpikesEnabled = 'off';
}
}
} else {
var rangeNow = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])];
var rangeNew = [r0 * rangeNow[0] + r1 * rangeNow[1], r0 * rangeNow[1] + r1 * rangeNow[0]];
aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]);
aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]);
}
}
}
} else {
// if ALL traces have orientation 'h', 'hovermode': 'x' otherwise: 'y'
if (astr === 'hovermode' && (val === 'x' || val === 'y')) {
val = fullLayout._isHoriz ? 'y' : 'x';
button.setAttribute('data-val', val);
}
aobj[astr] = val;
}
fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
Registry.call('_guiRelayout', gd, aobj);
}
modeBarButtons.zoom3d = {
name: 'zoom3d',
_cat: 'zoom',
title: function (gd) {
return _(gd, 'Zoom');
},
attr: 'scene.dragmode',
val: 'zoom',
icon: Icons.zoombox,
click: handleDrag3d
};
modeBarButtons.pan3d = {
name: 'pan3d',
_cat: 'pan',
title: function (gd) {
return _(gd, 'Pan');
},
attr: 'scene.dragmode',
val: 'pan',
icon: Icons.pan,
click: handleDrag3d
};
modeBarButtons.orbitRotation = {
name: 'orbitRotation',
title: function (gd) {
return _(gd, 'Orbital rotation');
},
attr: 'scene.dragmode',
val: 'orbit',
icon: Icons['3d_rotate'],
click: handleDrag3d
};
modeBarButtons.tableRotation = {
name: 'tableRotation',
title: function (gd) {
return _(gd, 'Turntable rotation');
},
attr: 'scene.dragmode',
val: 'turntable',
icon: Icons['z-axis'],
click: handleDrag3d
};
function handleDrag3d(gd, ev) {
var button = ev.currentTarget;
var attr = button.getAttribute('data-attr');
var val = button.getAttribute('data-val') || true;
var sceneIds = gd._fullLayout._subplots.gl3d || [];
var layoutUpdate = {};
var parts = attr.split('.');
for (var i = 0; i < sceneIds.length; i++) {
layoutUpdate[sceneIds[i] + '.' + parts[1]] = val;
}
// for multi-type subplots
var val2d = val === 'pan' ? val : 'zoom';
layoutUpdate.dragmode = val2d;
Registry.call('_guiRelayout', gd, layoutUpdate);
}
modeBarButtons.resetCameraDefault3d = {
name: 'resetCameraDefault3d',
_cat: 'resetCameraDefault',
title: function (gd) {
return _(gd, 'Reset camera to default');
},
attr: 'resetDefault',
icon: Icons.home,
click: handleCamera3d
};
modeBarButtons.resetCameraLastSave3d = {
name: 'resetCameraLastSave3d',
_cat: 'resetCameraLastSave',
title: function (gd) {
return _(gd, 'Reset camera to last save');
},
attr: 'resetLastSave',
icon: Icons.movie,
click: handleCamera3d
};
function handleCamera3d(gd, ev) {
var button = ev.currentTarget;
var attr = button.getAttribute('data-attr');
var resetLastSave = attr === 'resetLastSave';
var resetDefault = attr === 'resetDefault';
var fullLayout = gd._fullLayout;
var sceneIds = fullLayout._subplots.gl3d || [];
var aobj = {};
for (var i = 0; i < sceneIds.length; i++) {
var sceneId = sceneIds[i];
var camera = sceneId + '.camera';
var aspectratio = sceneId + '.aspectratio';
var aspectmode = sceneId + '.aspectmode';
var scene = fullLayout[sceneId]._scene;
var didUpdate;
if (resetLastSave) {
aobj[camera + '.up'] = scene.viewInitial.up;
aobj[camera + '.eye'] = scene.viewInitial.eye;
aobj[camera + '.center'] = scene.viewInitial.center;
didUpdate = true;
} else if (resetDefault) {
aobj[camera + '.up'] = null;
aobj[camera + '.eye'] = null;
aobj[camera + '.center'] = null;
didUpdate = true;
}
if (didUpdate) {
aobj[aspectratio + '.x'] = scene.viewInitial.aspectratio.x;
aobj[aspectratio + '.y'] = scene.viewInitial.aspectratio.y;
aobj[aspectratio + '.z'] = scene.viewInitial.aspectratio.z;
aobj[aspectmode] = scene.viewInitial.aspectmode;
}
}
Registry.call('_guiRelayout', gd, aobj);
}
modeBarButtons.hoverClosest3d = {
name: 'hoverClosest3d',
_cat: 'hoverclosest',
title: function (gd) {
return _(gd, 'Toggle show closest data on hover');
},
attr: 'hovermode',
val: null,
toggle: true,
icon: Icons.tooltip_basic,
gravity: 'ne',
click: handleHover3d
};
function getNextHover3d(gd, ev) {
var button = ev.currentTarget;
var val = button._previousVal;
var fullLayout = gd._fullLayout;
var sceneIds = fullLayout._subplots.gl3d || [];
var axes = ['xaxis', 'yaxis', 'zaxis'];
// initialize 'current spike' object to be stored in the DOM
var currentSpikes = {};
var layoutUpdate = {};
if (val) {
layoutUpdate = val;
button._previousVal = null;
} else {
for (var i = 0; i < sceneIds.length; i++) {
var sceneId = sceneIds[i];
var sceneLayout = fullLayout[sceneId];
var hovermodeAStr = sceneId + '.hovermode';
currentSpikes[hovermodeAStr] = sceneLayout.hovermode;
layoutUpdate[hovermodeAStr] = false;
// copy all the current spike attrs
for (var j = 0; j < 3; j++) {
var axis = axes[j];
var spikeAStr = sceneId + '.' + axis + '.showspikes';
layoutUpdate[spikeAStr] = false;
currentSpikes[spikeAStr] = sceneLayout[axis].showspikes;
}
}
button._previousVal = currentSpikes;
}
return layoutUpdate;
}
function handleHover3d(gd, ev) {
var layoutUpdate = getNextHover3d(gd, ev);
Registry.call('_guiRelayout', gd, layoutUpdate);
}
modeBarButtons.zoomInGeo = {
name: 'zoomInGeo',
_cat: 'zoomin',
title: function (gd) {
return _(gd, 'Zoom in');
},
attr: 'zoom',
val: 'in',
icon: Icons.zoom_plus,
click: handleGeo
};
modeBarButtons.zoomOutGeo = {
name: 'zoomOutGeo',
_cat: 'zoomout',
title: function (gd) {
return _(gd, 'Zoom out');
},
attr: 'zoom',
val: 'out',
icon: Icons.zoom_minus,
click: handleGeo
};
modeBarButtons.resetGeo = {
name: 'resetGeo',
_cat: 'reset',
title: function (gd) {
return _(gd, 'Reset');
},
attr: 'reset',
val: null,
icon: Icons.autoscale,
click: handleGeo
};
modeBarButtons.hoverClosestGeo = {
name: 'hoverClosestGeo',
_cat: 'hoverclosest',
title: function (gd) {
return _(gd, 'Toggle show closest data on hover');
},
attr: 'hovermode',
val: null,
toggle: true,
icon: Icons.tooltip_basic,
gravity: 'ne',
click: toggleHover
};
function handleGeo(gd, ev) {
var button = ev.currentTarget;
var attr = button.getAttribute('data-attr');
var val = button.getAttribute('data-val') || true;
var fullLayout = gd._fullLayout;
var geoIds = fullLayout._subplots.geo || [];
for (var i = 0; i < geoIds.length; i++) {
var id = geoIds[i];
var geoLayout = fullLayout[id];
if (attr === 'zoom') {
var scale = geoLayout.projection.scale;
var newScale = val === 'in' ? 2 * scale : 0.5 * scale;
Registry.call('_guiRelayout', gd, id + '.projection.scale', newScale);
}
}
if (attr === 'reset') {
resetView(gd, 'geo');
}
}
modeBarButtons.hoverClosestGl2d = {
name: 'hoverClosestGl2d',
_cat: 'hoverclosest',
title: function (gd) {
return _(gd, 'Toggle show closest data on hover');
},
attr: 'hovermode',
val: null,
toggle: true,
icon: Icons.tooltip_basic,
gravity: 'ne',
click: toggleHover
};
modeBarButtons.hoverClosestPie = {
name: 'hoverClosestPie',
_cat: 'hoverclosest',
title: function (gd) {
return _(gd, 'Toggle show closest data on hover');
},
attr: 'hovermode',
val: 'closest',
icon: Icons.tooltip_basic,
gravity: 'ne',
click: toggleHover
};
function getNextHover(gd) {
var fullLayout = gd._fullLayout;
if (fullLayout.hovermode) return false;
if (fullLayout._has('cartesian')) {
return fullLayout._isHoriz ? 'y' : 'x';
}
return 'closest';
}
function toggleHover(gd) {
var newHover = getNextHover(gd);
Registry.call('_guiRelayout', gd, 'hovermode', newHover);
}
modeBarButtons.resetViewSankey = {
name: 'resetSankeyGroup',
title: function (gd) {
return _(gd, 'Reset view');
},
icon: Icons.home,
click: function (gd) {
var aObj = {
'node.groups': [],
'node.x': [],
'node.y': []
};
for (var i = 0; i < gd._fullData.length; i++) {
var viewInitial = gd._fullData[i]._viewInitial;
aObj['node.groups'].push(viewInitial.node.groups.slice());
aObj['node.x'].push(viewInitial.node.x.slice());
aObj['node.y'].push(viewInitial.node.y.slice());
}
Registry.call('restyle', gd, aObj);
}
};
// buttons when more then one plot types are present
modeBarButtons.toggleHover = {
name: 'toggleHover',
title: function (gd) {
return _(gd, 'Toggle show closest data on hover');
},
attr: 'hovermode',
val: null,
toggle: true,
icon: Icons.tooltip_basic,
gravity: 'ne',
click: function (gd, ev) {
var layoutUpdate = getNextHover3d(gd, ev);
layoutUpdate.hovermode = getNextHover(gd);
Registry.call('_guiRelayout', gd, layoutUpdate);
}
};
modeBarButtons.resetViews = {
name: 'resetViews',
title: function (gd) {
return _(gd, 'Reset views');
},
icon: Icons.home,
click: function (gd, ev) {
var button = ev.currentTarget;
button.setAttribute('data-attr', 'zoom');
button.setAttribute('data-val', 'reset');
handleCartesian(gd, ev);
button.setAttribute('data-attr', 'resetLastSave');
handleCamera3d(gd, ev);
resetView(gd, 'geo');
resetView(gd, 'mapbox');
}
};
modeBarButtons.toggleSpikelines = {
name: 'toggleSpikelines',
title: function (gd) {
return _(gd, 'Toggle Spike Lines');
},
icon: Icons.spikeline,
attr: '_cartesianSpikesEnabled',
val: 'on',
click: function (gd) {
var fullLayout = gd._fullLayout;
var allSpikesEnabled = fullLayout._cartesianSpikesEnabled;
fullLayout._cartesianSpikesEnabled = allSpikesEnabled === 'on' ? 'off' : 'on';
Registry.call('_guiRelayout', gd, setSpikelineVisibility(gd));
}
};
function setSpikelineVisibility(gd) {
var fullLayout = gd._fullLayout;
var areSpikesOn = fullLayout._cartesianSpikesEnabled === 'on';
var axList = axisIds.list(gd, null, true);
var aobj = {};
for (var i = 0; i < axList.length; i++) {
var ax = axList[i];
aobj[ax._name + '.showspikes'] = areSpikesOn ? true : ax._showSpikeInitial;
}
return aobj;
}
modeBarButtons.resetViewMapbox = {
name: 'resetViewMapbox',
_cat: 'resetView',
title: function (gd) {
return _(gd, 'Reset view');
},
attr: 'reset',
icon: Icons.home,
click: function (gd) {
resetView(gd, 'mapbox');
}
};
modeBarButtons.zoomInMapbox = {
name: 'zoomInMapbox',
_cat: 'zoomin',
title: function (gd) {
return _(gd, 'Zoom in');
},
attr: 'zoom',
val: 'in',
icon: Icons.zoom_plus,
click: handleMapboxZoom
};
modeBarButtons.zoomOutMapbox = {
name: 'zoomOutMapbox',
_cat: 'zoomout',
title: function (gd) {
return _(gd, 'Zoom out');
},
attr: 'zoom',
val: 'out',
icon: Icons.zoom_minus,
click: handleMapboxZoom
};
function handleMapboxZoom(gd, ev) {
var button = ev.currentTarget;
var val = button.getAttribute('data-val');
var fullLayout = gd._fullLayout;
var subplotIds = fullLayout._subplots.mapbox || [];
var scalar = 1.05;
var aObj = {};
for (var i = 0; i < subplotIds.length; i++) {
var id = subplotIds[i];
var current = fullLayout[id].zoom;
var next = val === 'in' ? scalar * current : current / scalar;
aObj[id + '.zoom'] = next;
}
Registry.call('_guiRelayout', gd, aObj);
}
function resetView(gd, subplotType) {
var fullLayout = gd._fullLayout;
var subplotIds = fullLayout._subplots[subplotType] || [];
var aObj = {};
for (var i = 0; i < subplotIds.length; i++) {
var id = subplotIds[i];
var subplotObj = fullLayout[id]._subplot;
var viewInitial = subplotObj.viewInitial;
var viewKeys = Object.keys(viewInitial);
for (var j = 0; j < viewKeys.length; j++) {
var key = viewKeys[j];
aObj[id + '.' + key] = viewInitial[key];
}
}
Registry.call('_guiRelayout', gd, aObj);
}
/***/ }),
/***/ 76052:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var modeBarButtons = __webpack_require__(44248);
var buttonList = Object.keys(modeBarButtons);
var DRAW_MODES = ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect', 'eraseshape'];
var backButtons = ['v1hovermode', 'hoverclosest', 'hovercompare', 'togglehover', 'togglespikelines'].concat(DRAW_MODES);
var foreButtons = [];
var addToForeButtons = function (b) {
if (backButtons.indexOf(b._cat || b.name) !== -1) return;
// for convenience add lowercase shotname e.g. zoomin as well fullname zoomInGeo
var name = b.name;
var _cat = (b._cat || b.name).toLowerCase();
if (foreButtons.indexOf(name) === -1) foreButtons.push(name);
if (foreButtons.indexOf(_cat) === -1) foreButtons.push(_cat);
};
buttonList.forEach(function (k) {
addToForeButtons(modeBarButtons[k]);
});
foreButtons.sort();
module.exports = {
DRAW_MODES: DRAW_MODES,
backButtons: backButtons,
foreButtons: foreButtons
};
/***/ }),
/***/ 90824:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var Template = __webpack_require__(31780);
var attributes = __webpack_require__(66540);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
var containerIn = layoutIn.modebar || {};
var containerOut = Template.newContainer(layoutOut, 'modebar');
function coerce(attr, dflt) {
return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
}
coerce('orientation');
coerce('bgcolor', Color.addOpacity(layoutOut.paper_bgcolor, 0.5));
var defaultColor = Color.contrast(Color.rgb(layoutOut.modebar.bgcolor));
coerce('color', Color.addOpacity(defaultColor, 0.3));
coerce('activecolor', Color.addOpacity(defaultColor, 0.7));
coerce('uirevision', layoutOut.uirevision);
coerce('add');
coerce('remove');
};
/***/ }),
/***/ 45460:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'component',
name: 'modebar',
layoutAttributes: __webpack_require__(66540),
supplyLayoutDefaults: __webpack_require__(90824),
manage: __webpack_require__(18816)
};
/***/ }),
/***/ 18816:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var axisIds = __webpack_require__(79811);
var scatterSubTypes = __webpack_require__(43028);
var Registry = __webpack_require__(24040);
var isUnifiedHover = (__webpack_require__(10624).isUnifiedHover);
var createModeBar = __webpack_require__(66400);
var modeBarButtons = __webpack_require__(44248);
var DRAW_MODES = (__webpack_require__(76052).DRAW_MODES);
var extendDeep = (__webpack_require__(3400).extendDeep);
/**
* ModeBar wrapper around 'create' and 'update',
* chooses buttons to pass to ModeBar constructor based on
* plot type and plot config.
*
* @param {object} gd main plot object
*
*/
module.exports = function manageModeBar(gd) {
var fullLayout = gd._fullLayout;
var context = gd._context;
var modeBar = fullLayout._modeBar;
if (!context.displayModeBar && !context.watermark) {
if (modeBar) {
modeBar.destroy();
delete fullLayout._modeBar;
}
return;
}
if (!Array.isArray(context.modeBarButtonsToRemove)) {
throw new Error(['*modeBarButtonsToRemove* configuration options', 'must be an array.'].join(' '));
}
if (!Array.isArray(context.modeBarButtonsToAdd)) {
throw new Error(['*modeBarButtonsToAdd* configuration options', 'must be an array.'].join(' '));
}
var customButtons = context.modeBarButtons;
var buttonGroups;
if (Array.isArray(customButtons) && customButtons.length) {
buttonGroups = fillCustomButton(customButtons);
} else if (!context.displayModeBar && context.watermark) {
buttonGroups = [];
} else {
buttonGroups = getButtonGroups(gd);
}
if (modeBar) modeBar.update(gd, buttonGroups);else fullLayout._modeBar = createModeBar(gd, buttonGroups);
};
// logic behind which buttons are displayed by default
function getButtonGroups(gd) {
var fullLayout = gd._fullLayout;
var fullData = gd._fullData;
var context = gd._context;
function match(name, B) {
if (typeof B === 'string') {
if (B.toLowerCase() === name.toLowerCase()) return true;
} else {
var v0 = B.name;
var v1 = B._cat || B.name;
if (v0 === name || v1 === name.toLowerCase()) return true;
}
return false;
}
var layoutAdd = fullLayout.modebar.add;
if (typeof layoutAdd === 'string') layoutAdd = [layoutAdd];
var layoutRemove = fullLayout.modebar.remove;
if (typeof layoutRemove === 'string') layoutRemove = [layoutRemove];
var buttonsToAdd = context.modeBarButtonsToAdd.concat(layoutAdd.filter(function (e) {
for (var i = 0; i < context.modeBarButtonsToRemove.length; i++) {
if (match(e, context.modeBarButtonsToRemove[i])) return false;
}
return true;
}));
var buttonsToRemove = context.modeBarButtonsToRemove.concat(layoutRemove.filter(function (e) {
for (var i = 0; i < context.modeBarButtonsToAdd.length; i++) {
if (match(e, context.modeBarButtonsToAdd[i])) return false;
}
return true;
}));
var hasCartesian = fullLayout._has('cartesian');
var hasGL3D = fullLayout._has('gl3d');
var hasGeo = fullLayout._has('geo');
var hasPie = fullLayout._has('pie');
var hasFunnelarea = fullLayout._has('funnelarea');
var hasGL2D = fullLayout._has('gl2d');
var hasTernary = fullLayout._has('ternary');
var hasMapbox = fullLayout._has('mapbox');
var hasPolar = fullLayout._has('polar');
var hasSmith = fullLayout._has('smith');
var hasSankey = fullLayout._has('sankey');
var allAxesFixed = areAllAxesFixed(fullLayout);
var hasUnifiedHoverLabel = isUnifiedHover(fullLayout.hovermode);
var groups = [];
function addGroup(newGroup) {
if (!newGroup.length) return;
var out = [];
for (var i = 0; i < newGroup.length; i++) {
var name = newGroup[i];
var B = modeBarButtons[name];
var v0 = B.name.toLowerCase();
var v1 = (B._cat || B.name).toLowerCase();
var found = false;
for (var q = 0; q < buttonsToRemove.length; q++) {
var t = buttonsToRemove[q].toLowerCase();
if (t === v0 || t === v1) {
found = true;
break;
}
}
if (found) continue;
out.push(modeBarButtons[name]);
}
groups.push(out);
}
// buttons common to all plot types
var commonGroup = ['toImage'];
if (context.showEditInChartStudio) commonGroup.push('editInChartStudio');else if (context.showSendToCloud) commonGroup.push('sendDataToCloud');
addGroup(commonGroup);
var zoomGroup = [];
var hoverGroup = [];
var resetGroup = [];
var dragModeGroup = [];
if ((hasCartesian || hasGL2D || hasPie || hasFunnelarea || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar + hasSmith > 1) {
// graphs with more than one plot types get 'union buttons'
// which reset the view or toggle hover labels across all subplots.
hoverGroup = ['toggleHover'];
resetGroup = ['resetViews'];
} else if (hasGeo) {
zoomGroup = ['zoomInGeo', 'zoomOutGeo'];
hoverGroup = ['hoverClosestGeo'];
resetGroup = ['resetGeo'];
} else if (hasGL3D) {
hoverGroup = ['hoverClosest3d'];
resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d'];
} else if (hasMapbox) {
zoomGroup = ['zoomInMapbox', 'zoomOutMapbox'];
hoverGroup = ['toggleHover'];
resetGroup = ['resetViewMapbox'];
} else if (hasGL2D) {
hoverGroup = ['hoverClosestGl2d'];
} else if (hasPie) {
hoverGroup = ['hoverClosestPie'];
} else if (hasSankey) {
hoverGroup = ['hoverClosestCartesian', 'hoverCompareCartesian'];
resetGroup = ['resetViewSankey'];
} else {
// hasPolar, hasSmith, hasTernary
// always show at least one hover icon.
hoverGroup = ['toggleHover'];
}
// if we have cartesian, allow switching between closest and compare
// regardless of what other types are on the plot, since they'll all
// just treat any truthy hovermode as 'closest'
if (hasCartesian) {
hoverGroup.push('toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian');
}
if (hasNoHover(fullData) || hasUnifiedHoverLabel) {
hoverGroup = [];
}
if ((hasCartesian || hasGL2D) && !allAxesFixed) {
zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d'];
if (resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d'];
}
if (hasGL3D) {
dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation'];
} else if ((hasCartesian || hasGL2D) && !allAxesFixed || hasTernary) {
dragModeGroup = ['zoom2d', 'pan2d'];
} else if (hasMapbox || hasGeo) {
dragModeGroup = ['pan2d'];
} else if (hasPolar) {
dragModeGroup = ['zoom2d'];
}
if (isSelectable(fullData)) {
dragModeGroup.push('select2d', 'lasso2d');
}
var enabledHoverGroup = [];
var enableHover = function (a) {
// return if already added
if (enabledHoverGroup.indexOf(a) !== -1) return;
// should be in hoverGroup
if (hoverGroup.indexOf(a) !== -1) {
enabledHoverGroup.push(a);
}
};
if (Array.isArray(buttonsToAdd)) {
var newList = [];
for (var i = 0; i < buttonsToAdd.length; i++) {
var b = buttonsToAdd[i];
if (typeof b === 'string') {
b = b.toLowerCase();
if (DRAW_MODES.indexOf(b) !== -1) {
// accept pre-defined drag modes i.e. shape drawing features as string
if (fullLayout._has('mapbox') ||
// draw shapes in paper coordinate (could be improved in future to support data coordinate, when there is no pitch)
fullLayout._has('cartesian') // draw shapes in data coordinate
) {
dragModeGroup.push(b);
}
} else if (b === 'togglespikelines') {
enableHover('toggleSpikelines');
} else if (b === 'togglehover') {
enableHover('toggleHover');
} else if (b === 'hovercompare') {
enableHover('hoverCompareCartesian');
} else if (b === 'hoverclosest') {
enableHover('hoverClosestCartesian');
enableHover('hoverClosestGeo');
enableHover('hoverClosest3d');
enableHover('hoverClosestGl2d');
enableHover('hoverClosestPie');
} else if (b === 'v1hovermode') {
enableHover('hoverClosestCartesian');
enableHover('hoverCompareCartesian');
enableHover('hoverClosestGeo');
enableHover('hoverClosest3d');
enableHover('hoverClosestGl2d');
enableHover('hoverClosestPie');
}
} else newList.push(b);
}
buttonsToAdd = newList;
}
addGroup(dragModeGroup);
addGroup(zoomGroup.concat(resetGroup));
addGroup(enabledHoverGroup);
return appendButtonsToGroups(groups, buttonsToAdd);
}
function areAllAxesFixed(fullLayout) {
var axList = axisIds.list({
_fullLayout: fullLayout
}, null, true);
for (var i = 0; i < axList.length; i++) {
if (!axList[i].fixedrange) {
return false;
}
}
return true;
}
// look for traces that support selection
// to be updated as we add more selectPoints handlers
function isSelectable(fullData) {
var selectable = false;
for (var i = 0; i < fullData.length; i++) {
if (selectable) break;
var trace = fullData[i];
if (!trace._module || !trace._module.selectPoints) continue;
if (Registry.traceIs(trace, 'scatter-like')) {
if (scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) {
selectable = true;
}
} else if (Registry.traceIs(trace, 'box-violin')) {
if (trace.boxpoints === 'all' || trace.points === 'all') {
selectable = true;
}
} else {
// assume that in general if the trace module has selectPoints,
// then it's selectable. Scatter is an exception to this because it must
// have markers or text, not just be a scatter type.
selectable = true;
}
}
return selectable;
}
// check whether all trace are 'noHover'
function hasNoHover(fullData) {
for (var i = 0; i < fullData.length; i++) {
if (!Registry.traceIs(fullData[i], 'noHover')) return false;
}
return true;
}
function appendButtonsToGroups(groups, buttons) {
if (buttons.length) {
if (Array.isArray(buttons[0])) {
for (var i = 0; i < buttons.length; i++) {
groups.push(buttons[i]);
}
} else groups.push(buttons);
}
return groups;
}
// fill in custom buttons referring to default mode bar buttons
function fillCustomButton(originalModeBarButtons) {
var customButtons = extendDeep([], originalModeBarButtons);
for (var i = 0; i < customButtons.length; i++) {
var buttonGroup = customButtons[i];
for (var j = 0; j < buttonGroup.length; j++) {
var button = buttonGroup[j];
if (typeof button === 'string') {
if (modeBarButtons[button] !== undefined) {
customButtons[i][j] = modeBarButtons[button];
} else {
throw new Error(['*modeBarButtons* configuration options', 'invalid button name'].join(' '));
}
}
}
}
return customButtons;
}
/***/ }),
/***/ 66400:
/***/ (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 Icons = __webpack_require__(9224);
var version = (__webpack_require__(25788).version);
var Parser = new DOMParser();
/**
* UI controller for interactive plots
* @Class
* @Param {object} opts
* @Param {object} opts.buttons nested arrays of grouped buttons config objects
* @Param {object} opts.container container div to append modeBar
* @Param {object} opts.graphInfo primary plot object containing data and layout
*/
function ModeBar(opts) {
this.container = opts.container;
this.element = document.createElement('div');
this.update(opts.graphInfo, opts.buttons);
this.container.appendChild(this.element);
}
var proto = ModeBar.prototype;
/**
* Update modeBar (buttons and logo)
*
* @param {object} graphInfo primary plot object containing data and layout
* @param {array of arrays} buttons nested arrays of grouped buttons to initialize
*
*/
proto.update = function (graphInfo, buttons) {
this.graphInfo = graphInfo;
var context = this.graphInfo._context;
var fullLayout = this.graphInfo._fullLayout;
var modeBarId = 'modebar-' + fullLayout._uid;
this.element.setAttribute('id', modeBarId);
this._uid = modeBarId;
this.element.className = 'modebar';
if (context.displayModeBar === 'hover') this.element.className += ' modebar--hover ease-bg';
if (fullLayout.modebar.orientation === 'v') {
this.element.className += ' vertical';
buttons = buttons.reverse();
}
var style = fullLayout.modebar;
var bgSelector = context.displayModeBar === 'hover' ? '.js-plotly-plot .plotly:hover ' : '';
Lib.deleteRelatedStyleRule(modeBarId);
Lib.addRelatedStyleRule(modeBarId, bgSelector + '#' + modeBarId + ' .modebar-group', 'background-color: ' + style.bgcolor);
Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn .icon path', 'fill: ' + style.color);
Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn:hover .icon path', 'fill: ' + style.activecolor);
Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn.active .icon path', 'fill: ' + style.activecolor);
// if buttons or logo have changed, redraw modebar interior
var needsNewButtons = !this.hasButtons(buttons);
var needsNewLogo = this.hasLogo !== context.displaylogo;
var needsNewLocale = this.locale !== context.locale;
this.locale = context.locale;
if (needsNewButtons || needsNewLogo || needsNewLocale) {
this.removeAllButtons();
this.updateButtons(buttons);
if (context.watermark || context.displaylogo) {
var logoGroup = this.getLogo();
if (context.watermark) {
logoGroup.className = logoGroup.className + ' watermark';
}
if (fullLayout.modebar.orientation === 'v') {
this.element.insertBefore(logoGroup, this.element.childNodes[0]);
} else {
this.element.appendChild(logoGroup);
}
this.hasLogo = true;
}
}
this.updateActiveButton();
};
proto.updateButtons = function (buttons) {
var _this = this;
this.buttons = buttons;
this.buttonElements = [];
this.buttonsNames = [];
this.buttons.forEach(function (buttonGroup) {
var group = _this.createGroup();
buttonGroup.forEach(function (buttonConfig) {
var buttonName = buttonConfig.name;
if (!buttonName) {
throw new Error('must provide button \'name\' in button config');
}
if (_this.buttonsNames.indexOf(buttonName) !== -1) {
throw new Error('button name \'' + buttonName + '\' is taken');
}
_this.buttonsNames.push(buttonName);
var button = _this.createButton(buttonConfig);
_this.buttonElements.push(button);
group.appendChild(button);
});
_this.element.appendChild(group);
});
};
/**
* Empty div for containing a group of buttons
* @Return {HTMLelement}
*/
proto.createGroup = function () {
var group = document.createElement('div');
group.className = 'modebar-group';
return group;
};
/**
* Create a new button div and set constant and configurable attributes
* @Param {object} config (see ./buttons.js for more info)
* @Return {HTMLelement}
*/
proto.createButton = function (config) {
var _this = this;
var button = document.createElement('a');
button.setAttribute('rel', 'tooltip');
button.className = 'modebar-btn';
var title = config.title;
if (title === undefined) title = config.name;
// for localization: allow title to be a callable that takes gd as arg
else if (typeof title === 'function') title = title(this.graphInfo);
if (title || title === 0) button.setAttribute('data-title', title);
if (config.attr !== undefined) button.setAttribute('data-attr', config.attr);
var val = config.val;
if (val !== undefined) {
if (typeof val === 'function') val = val(this.graphInfo);
button.setAttribute('data-val', val);
}
var click = config.click;
if (typeof click !== 'function') {
throw new Error('must provide button \'click\' function in button config');
} else {
button.addEventListener('click', function (ev) {
config.click(_this.graphInfo, ev);
// only needed for 'hoverClosestGeo' which does not call relayout
_this.updateActiveButton(ev.currentTarget);
});
}
button.setAttribute('data-toggle', config.toggle || false);
if (config.toggle) d3.select(button).classed('active', true);
var icon = config.icon;
if (typeof icon === 'function') {
button.appendChild(icon());
} else {
button.appendChild(this.createIcon(icon || Icons.question));
}
button.setAttribute('data-gravity', config.gravity || 'n');
return button;
};
/**
* Add an icon to a button
* @Param {object} thisIcon
* @Param {number} thisIcon.width
* @Param {string} thisIcon.path
* @Param {string} thisIcon.color
* @Return {HTMLelement}
*/
proto.createIcon = function (thisIcon) {
var iconHeight = isNumeric(thisIcon.height) ? Number(thisIcon.height) : thisIcon.ascent - thisIcon.descent;
var svgNS = 'http://www.w3.org/2000/svg';
var icon;
if (thisIcon.path) {
icon = document.createElementNS(svgNS, 'svg');
icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' '));
icon.setAttribute('class', 'icon');
var path = document.createElementNS(svgNS, 'path');
path.setAttribute('d', thisIcon.path);
if (thisIcon.transform) {
path.setAttribute('transform', thisIcon.transform);
} else if (thisIcon.ascent !== undefined) {
// Legacy icon transform calculation
path.setAttribute('transform', 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')');
}
icon.appendChild(path);
}
if (thisIcon.svg) {
var svgDoc = Parser.parseFromString(thisIcon.svg, 'application/xml');
icon = svgDoc.childNodes[0];
}
icon.setAttribute('height', '1em');
icon.setAttribute('width', '1em');
return icon;
};
/**
* Updates active button with attribute specified in layout
* @Param {object} graphInfo plot object containing data and layout
* @Return {HTMLelement}
*/
proto.updateActiveButton = function (buttonClicked) {
var fullLayout = this.graphInfo._fullLayout;
var dataAttrClicked = buttonClicked !== undefined ? buttonClicked.getAttribute('data-attr') : null;
this.buttonElements.forEach(function (button) {
var thisval = button.getAttribute('data-val') || true;
var dataAttr = button.getAttribute('data-attr');
var isToggleButton = button.getAttribute('data-toggle') === 'true';
var button3 = d3.select(button);
// Use 'data-toggle' and 'buttonClicked' to toggle buttons
// that have no one-to-one equivalent in fullLayout
if (isToggleButton) {
if (dataAttr === dataAttrClicked) {
button3.classed('active', !button3.classed('active'));
}
} else {
var val = dataAttr === null ? dataAttr : Lib.nestedProperty(fullLayout, dataAttr).get();
button3.classed('active', val === thisval);
}
});
};
/**
* Check if modeBar is configured as button configuration argument
*
* @Param {object} buttons 2d array of grouped button config objects
* @Return {boolean}
*/
proto.hasButtons = function (buttons) {
var currentButtons = this.buttons;
if (!currentButtons) return false;
if (buttons.length !== currentButtons.length) return false;
for (var i = 0; i < buttons.length; ++i) {
if (buttons[i].length !== currentButtons[i].length) return false;
for (var j = 0; j < buttons[i].length; j++) {
if (buttons[i][j].name !== currentButtons[i][j].name) return false;
}
}
return true;
};
function jsVersion(str) {
return str + ' (v' + version + ')';
}
/**
* @return {HTMLDivElement} The logo image wrapped in a group
*/
proto.getLogo = function () {
var group = this.createGroup();
var a = document.createElement('a');
a.href = 'https://plotly.com/';
a.target = '_blank';
a.setAttribute('data-title', jsVersion(Lib._(this.graphInfo, 'Produced with Plotly.js')));
a.className = 'modebar-btn plotlyjsicon modebar-btn--logo';
a.appendChild(this.createIcon(Icons.newplotlylogo));
group.appendChild(a);
return group;
};
proto.removeAllButtons = function () {
while (this.element.firstChild) {
this.element.removeChild(this.element.firstChild);
}
this.hasLogo = false;
};
proto.destroy = function () {
Lib.removeElement(this.container.querySelector('.modebar'));
Lib.deleteRelatedStyleRule(this._uid);
};
function createModeBar(gd, buttons) {
var fullLayout = gd._fullLayout;
var modeBar = new ModeBar({
graphInfo: gd,
container: fullLayout._modebardiv.node(),
buttons: buttons
});
if (fullLayout._privateplot) {
d3.select(modeBar.element).append('span').classed('badge-private float--left', true).text('PRIVATE');
}
return modeBar;
}
module.exports = createModeBar;
/***/ }),
/***/ 26680:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var colorAttrs = __webpack_require__(22548);
var templatedArray = (__webpack_require__(31780).templatedArray);
var buttonAttrs = templatedArray('button', {
visible: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
step: {
valType: 'enumerated',
values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'],
dflt: 'month',
editType: 'plot'
},
stepmode: {
valType: 'enumerated',
values: ['backward', 'todate'],
dflt: 'backward',
editType: 'plot'
},
count: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'plot'
},
label: {
valType: 'string',
editType: 'plot'
},
editType: 'plot'
});
module.exports = {
visible: {
valType: 'boolean',
editType: 'plot'
},
buttons: buttonAttrs,
x: {
valType: 'number',
min: -2,
max: 3,
editType: 'plot'
},
xanchor: {
valType: 'enumerated',
values: ['auto', 'left', 'center', 'right'],
dflt: 'left',
editType: 'plot'
},
y: {
valType: 'number',
min: -2,
max: 3,
editType: 'plot'
},
yanchor: {
valType: 'enumerated',
values: ['auto', 'top', 'middle', 'bottom'],
dflt: 'bottom',
editType: 'plot'
},
font: fontAttrs({
editType: 'plot'
}),
bgcolor: {
valType: 'color',
dflt: colorAttrs.lightLine,
editType: 'plot'
},
activecolor: {
valType: 'color',
editType: 'plot'
},
bordercolor: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'plot'
},
borderwidth: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'plot'
},
editType: 'plot'
};
/***/ }),
/***/ 85984:
/***/ (function(module) {
"use strict";
module.exports = {
// 'y' position pad above counter axis domain
yPad: 0.02,
// minimum button width (regardless of text size)
minButtonWidth: 30,
// buttons rect radii
rx: 3,
ry: 3,
// light fraction used to compute the 'activecolor' default
lightAmount: 25,
darkAmount: 10
};
/***/ }),
/***/ 22148:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var Template = __webpack_require__(31780);
var handleArrayContainerDefaults = __webpack_require__(51272);
var attributes = __webpack_require__(26680);
var constants = __webpack_require__(85984);
module.exports = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) {
var selectorIn = containerIn.rangeselector || {};
var selectorOut = Template.newContainer(containerOut, 'rangeselector');
function coerce(attr, dflt) {
return Lib.coerce(selectorIn, selectorOut, attributes, attr, dflt);
}
var buttons = handleArrayContainerDefaults(selectorIn, selectorOut, {
name: 'buttons',
handleItemDefaults: buttonDefaults,
calendar: calendar
});
var visible = coerce('visible', buttons.length > 0);
if (visible) {
var posDflt = getPosDflt(containerOut, layout, counterAxes);
coerce('x', posDflt[0]);
coerce('y', posDflt[1]);
Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
coerce('xanchor');
coerce('yanchor');
Lib.coerceFont(coerce, 'font', layout.font);
var bgColor = coerce('bgcolor');
coerce('activecolor', Color.contrast(bgColor, constants.lightAmount, constants.darkAmount));
coerce('bordercolor');
coerce('borderwidth');
}
};
function buttonDefaults(buttonIn, buttonOut, selectorOut, opts) {
var calendar = opts.calendar;
function coerce(attr, dflt) {
return Lib.coerce(buttonIn, buttonOut, attributes.buttons, attr, dflt);
}
var visible = coerce('visible');
if (visible) {
var step = coerce('step');
if (step !== 'all') {
if (calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) {
buttonOut.stepmode = 'backward';
} else {
coerce('stepmode');
}
coerce('count');
}
coerce('label');
}
}
function getPosDflt(containerOut, layout, counterAxes) {
var anchoredList = counterAxes.filter(function (ax) {
return layout[ax].anchor === containerOut._id;
});
var posY = 0;
for (var i = 0; i < anchoredList.length; i++) {
var domain = layout[anchoredList[i]].domain;
if (domain) posY = Math.max(domain[1], posY);
}
return [containerOut.domain[0], posY + constants.yPad];
}
/***/ }),
/***/ 50216:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Registry = __webpack_require__(24040);
var Plots = __webpack_require__(7316);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var svgTextUtils = __webpack_require__(72736);
var axisIds = __webpack_require__(79811);
var alignmentConstants = __webpack_require__(84284);
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;
var constants = __webpack_require__(85984);
var getUpdateObject = __webpack_require__(48040);
module.exports = function draw(gd) {
var fullLayout = gd._fullLayout;
var selectors = fullLayout._infolayer.selectAll('.rangeselector').data(makeSelectorData(gd), selectorKeyFunc);
selectors.enter().append('g').classed('rangeselector', true);
selectors.exit().remove();
selectors.style({
cursor: 'pointer',
'pointer-events': 'all'
});
selectors.each(function (d) {
var selector = d3.select(this);
var axisLayout = d;
var selectorLayout = axisLayout.rangeselector;
var buttons = selector.selectAll('g.button').data(Lib.filterVisible(selectorLayout.buttons));
buttons.enter().append('g').classed('button', true);
buttons.exit().remove();
buttons.each(function (d) {
var button = d3.select(this);
var update = getUpdateObject(axisLayout, d);
d._isActive = isActive(axisLayout, d, update);
button.call(drawButtonRect, selectorLayout, d);
button.call(drawButtonText, selectorLayout, d, gd);
button.on('click', function () {
if (gd._dragged) return;
Registry.call('_guiRelayout', gd, update);
});
button.on('mouseover', function () {
d._isHovered = true;
button.call(drawButtonRect, selectorLayout, d);
});
button.on('mouseout', function () {
d._isHovered = false;
button.call(drawButtonRect, selectorLayout, d);
});
});
reposition(gd, buttons, selectorLayout, axisLayout._name, selector);
});
};
function makeSelectorData(gd) {
var axes = axisIds.list(gd, 'x', true);
var data = [];
for (var i = 0; i < axes.length; i++) {
var axis = axes[i];
if (axis.rangeselector && axis.rangeselector.visible) {
data.push(axis);
}
}
return data;
}
function selectorKeyFunc(d) {
return d._id;
}
function isActive(axisLayout, opts, update) {
if (opts.step === 'all') {
return axisLayout.autorange === true;
} else {
var keys = Object.keys(update);
return axisLayout.range[0] === update[keys[0]] && axisLayout.range[1] === update[keys[1]];
}
}
function drawButtonRect(button, selectorLayout, d) {
var rect = Lib.ensureSingle(button, 'rect', 'selector-rect', function (s) {
s.attr('shape-rendering', 'crispEdges');
});
rect.attr({
rx: constants.rx,
ry: constants.ry
});
rect.call(Color.stroke, selectorLayout.bordercolor).call(Color.fill, getFillColor(selectorLayout, d)).style('stroke-width', selectorLayout.borderwidth + 'px');
}
function getFillColor(selectorLayout, d) {
return d._isActive || d._isHovered ? selectorLayout.activecolor : selectorLayout.bgcolor;
}
function drawButtonText(button, selectorLayout, d, gd) {
function textLayout(s) {
svgTextUtils.convertToTspans(s, gd);
}
var text = Lib.ensureSingle(button, 'text', 'selector-text', function (s) {
s.attr('text-anchor', 'middle');
});
text.call(Drawing.font, selectorLayout.font).text(getLabel(d, gd._fullLayout._meta)).call(textLayout);
}
function getLabel(opts, _meta) {
if (opts.label) {
return _meta ? Lib.templateString(opts.label, _meta) : opts.label;
}
if (opts.step === 'all') return 'all';
return opts.count + opts.step.charAt(0);
}
function reposition(gd, buttons, opts, axName, selector) {
var width = 0;
var height = 0;
var borderWidth = opts.borderwidth;
buttons.each(function () {
var button = d3.select(this);
var text = button.select('.selector-text');
var tHeight = opts.font.size * LINE_SPACING;
var hEff = Math.max(tHeight * svgTextUtils.lineCount(text), 16) + 3;
height = Math.max(height, hEff);
});
buttons.each(function () {
var button = d3.select(this);
var rect = button.select('.selector-rect');
var text = button.select('.selector-text');
var tWidth = text.node() && Drawing.bBox(text.node()).width;
var tHeight = opts.font.size * LINE_SPACING;
var tLines = svgTextUtils.lineCount(text);
var wEff = Math.max(tWidth + 10, constants.minButtonWidth);
// TODO add MathJax support
// TODO add buttongap attribute
button.attr('transform', strTranslate(borderWidth + width, borderWidth));
rect.attr({
x: 0,
y: 0,
width: wEff,
height: height
});
svgTextUtils.positionText(text, wEff / 2, height / 2 - (tLines - 1) * tHeight / 2 + 3);
width += wEff + 5;
});
var graphSize = gd._fullLayout._size;
var lx = graphSize.l + graphSize.w * opts.x;
var ly = graphSize.t + graphSize.h * (1 - opts.y);
var xanchor = 'left';
if (Lib.isRightAnchor(opts)) {
lx -= width;
xanchor = 'right';
}
if (Lib.isCenterAnchor(opts)) {
lx -= width / 2;
xanchor = 'center';
}
var yanchor = 'top';
if (Lib.isBottomAnchor(opts)) {
ly -= height;
yanchor = 'bottom';
}
if (Lib.isMiddleAnchor(opts)) {
ly -= height / 2;
yanchor = 'middle';
}
width = Math.ceil(width);
height = Math.ceil(height);
lx = Math.round(lx);
ly = Math.round(ly);
Plots.autoMargin(gd, axName + '-range-selector', {
x: opts.x,
y: opts.y,
l: width * FROM_TL[xanchor],
r: width * FROM_BR[xanchor],
b: height * FROM_BR[yanchor],
t: height * FROM_TL[yanchor]
});
selector.attr('transform', strTranslate(lx, ly));
}
/***/ }),
/***/ 48040:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3Time = __webpack_require__(73220);
var titleCase = (__webpack_require__(3400).titleCase);
module.exports = function getUpdateObject(axisLayout, buttonLayout) {
var axName = axisLayout._name;
var update = {};
if (buttonLayout.step === 'all') {
update[axName + '.autorange'] = true;
} else {
var xrange = getXRange(axisLayout, buttonLayout);
update[axName + '.range[0]'] = xrange[0];
update[axName + '.range[1]'] = xrange[1];
}
return update;
};
function getXRange(axisLayout, buttonLayout) {
var currentRange = axisLayout.range;
var base = new Date(axisLayout.r2l(currentRange[1]));
var step = buttonLayout.step;
var utcStep = d3Time['utc' + titleCase(step)];
var count = buttonLayout.count;
var range0;
switch (buttonLayout.stepmode) {
case 'backward':
range0 = axisLayout.l2r(+utcStep.offset(base, -count));
break;
case 'todate':
var base2 = utcStep.offset(base, -count);
range0 = axisLayout.l2r(+utcStep.ceil(base2));
break;
}
var range1 = currentRange[1];
return [range0, range1];
}
/***/ }),
/***/ 41152:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'component',
name: 'rangeselector',
schema: {
subplots: {
xaxis: {
rangeselector: __webpack_require__(26680)
}
}
},
layoutAttributes: __webpack_require__(26680),
handleDefaults: __webpack_require__(22148),
draw: __webpack_require__(50216)
};
/***/ }),
/***/ 11200:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorAttributes = __webpack_require__(22548);
module.exports = {
bgcolor: {
valType: 'color',
dflt: colorAttributes.background,
editType: 'plot'
},
bordercolor: {
valType: 'color',
dflt: colorAttributes.defaultLine,
editType: 'plot'
},
borderwidth: {
valType: 'integer',
dflt: 0,
min: 0,
editType: 'plot'
},
autorange: {
valType: 'boolean',
dflt: true,
editType: 'calc',
impliedEdits: {
'range[0]': undefined,
'range[1]': undefined
}
},
range: {
valType: 'info_array',
items: [{
valType: 'any',
editType: 'calc',
impliedEdits: {
'^autorange': false
}
}, {
valType: 'any',
editType: 'calc',
impliedEdits: {
'^autorange': false
}
}],
editType: 'calc',
impliedEdits: {
autorange: false
}
},
thickness: {
valType: 'number',
dflt: 0.15,
min: 0,
max: 1,
editType: 'plot'
},
visible: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
editType: 'calc'
};
/***/ }),
/***/ 26652:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var listAxes = (__webpack_require__(79811).list);
var getAutoRange = (__webpack_require__(19280).getAutoRange);
var constants = __webpack_require__(74636);
module.exports = function calcAutorange(gd) {
var axes = listAxes(gd, 'x', true);
// Compute new slider range using axis autorange if necessary.
//
// Copy back range to input range slider container to skip
// this step in subsequent draw calls.
for (var i = 0; i < axes.length; i++) {
var ax = axes[i];
var opts = ax[constants.name];
if (opts && opts.visible && opts.autorange) {
opts._input.autorange = true;
opts._input.range = opts.range = getAutoRange(gd, ax);
}
}
};
/***/ }),
/***/ 74636:
/***/ (function(module) {
"use strict";
module.exports = {
// attribute container name
name: 'rangeslider',
// class names
containerClassName: 'rangeslider-container',
bgClassName: 'rangeslider-bg',
rangePlotClassName: 'rangeslider-rangeplot',
maskMinClassName: 'rangeslider-mask-min',
maskMaxClassName: 'rangeslider-mask-max',
slideBoxClassName: 'rangeslider-slidebox',
grabberMinClassName: 'rangeslider-grabber-min',
grabAreaMinClassName: 'rangeslider-grabarea-min',
handleMinClassName: 'rangeslider-handle-min',
grabberMaxClassName: 'rangeslider-grabber-max',
grabAreaMaxClassName: 'rangeslider-grabarea-max',
handleMaxClassName: 'rangeslider-handle-max',
maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis',
maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis',
// style constants
maskColor: 'rgba(0,0,0,0.4)',
maskOppAxisColor: 'rgba(0,0,0,0.2)',
slideBoxFill: 'transparent',
slideBoxCursor: 'ew-resize',
grabAreaFill: 'transparent',
grabAreaCursor: 'col-resize',
grabAreaWidth: 10,
handleWidth: 4,
handleRadius: 1,
handleStrokeWidth: 1,
extraPad: 15
};
/***/ }),
/***/ 94040:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
var axisIds = __webpack_require__(79811);
var attributes = __webpack_require__(11200);
var oppAxisAttrs = __webpack_require__(10936);
module.exports = function handleDefaults(layoutIn, layoutOut, axName) {
var axIn = layoutIn[axName];
var axOut = layoutOut[axName];
if (!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return;
// not super proud of this (maybe store _ in axis object instead
if (!Lib.isPlainObject(axIn.rangeslider)) {
axIn.rangeslider = {};
}
var containerIn = axIn.rangeslider;
var containerOut = Template.newContainer(axOut, 'rangeslider');
function coerce(attr, dflt) {
return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
}
var rangeContainerIn, rangeContainerOut;
function coerceRange(attr, dflt) {
return Lib.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs, attr, dflt);
}
var visible = coerce('visible');
if (!visible) return;
coerce('bgcolor', layoutOut.plot_bgcolor);
coerce('bordercolor');
coerce('borderwidth');
coerce('thickness');
coerce('autorange', !axOut.isValidRange(containerIn.range));
coerce('range');
var subplots = layoutOut._subplots;
if (subplots) {
var yIds = subplots.cartesian.filter(function (subplotId) {
return subplotId.substr(0, subplotId.indexOf('y')) === axisIds.name2id(axName);
}).map(function (subplotId) {
return subplotId.substr(subplotId.indexOf('y'), subplotId.length);
});
var yNames = Lib.simpleMap(yIds, axisIds.id2name);
for (var i = 0; i < yNames.length; i++) {
var yName = yNames[i];
rangeContainerIn = containerIn[yName] || {};
rangeContainerOut = Template.newContainer(containerOut, yName, 'yaxis');
var yAxOut = layoutOut[yName];
var rangemodeDflt;
if (rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) {
rangemodeDflt = 'fixed';
}
var rangeMode = coerceRange('rangemode', rangemodeDflt);
if (rangeMode !== 'match') {
coerceRange('range', yAxOut.range.slice());
}
}
}
// to map back range slider (auto) range
containerOut._input = containerIn;
};
/***/ }),
/***/ 20060:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Registry = __webpack_require__(24040);
var Plots = __webpack_require__(7316);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var Titles = __webpack_require__(81668);
var Cartesian = __webpack_require__(57952);
var axisIDs = __webpack_require__(79811);
var dragElement = __webpack_require__(86476);
var setCursor = __webpack_require__(93972);
var constants = __webpack_require__(74636);
module.exports = function (gd) {
var fullLayout = gd._fullLayout;
var rangeSliderData = fullLayout._rangeSliderData;
for (var i = 0; i < rangeSliderData.length; i++) {
var opts = rangeSliderData[i][constants.name];
// fullLayout._uid may not exist when we call makeData
opts._clipId = opts._id + '-' + fullLayout._uid;
}
/*
*
*
* < .... range plot />
*
*
*
*
*
*
*
*
*
*
* ...
*/
function keyFunction(axisOpts) {
return axisOpts._name;
}
var rangeSliders = fullLayout._infolayer.selectAll('g.' + constants.containerClassName).data(rangeSliderData, keyFunction);
// remove exiting sliders and their corresponding clip paths
rangeSliders.exit().each(function (axisOpts) {
var opts = axisOpts[constants.name];
fullLayout._topdefs.select('#' + opts._clipId).remove();
}).remove();
// return early if no range slider is visible
if (rangeSliderData.length === 0) return;
rangeSliders.enter().append('g').classed(constants.containerClassName, true).attr('pointer-events', 'all');
// for all present range sliders
rangeSliders.each(function (axisOpts) {
var rangeSlider = d3.select(this);
var opts = axisOpts[constants.name];
var oppAxisOpts = fullLayout[axisIDs.id2name(axisOpts.anchor)];
var oppAxisRangeOpts = opts[axisIDs.id2name(axisOpts.anchor)];
// update range
// Expand slider range to the axis range
if (opts.range) {
var rng = Lib.simpleMap(opts.range, axisOpts.r2l);
var axRng = Lib.simpleMap(axisOpts.range, axisOpts.r2l);
var newRng;
if (axRng[0] < axRng[1]) {
newRng = [Math.min(rng[0], axRng[0]), Math.max(rng[1], axRng[1])];
} else {
newRng = [Math.max(rng[0], axRng[0]), Math.min(rng[1], axRng[1])];
}
opts.range = opts._input.range = Lib.simpleMap(newRng, axisOpts.l2r);
}
axisOpts.cleanRange('rangeslider.range');
// update range slider dimensions
var gs = fullLayout._size;
var domain = axisOpts.domain;
opts._width = gs.w * (domain[1] - domain[0]);
var x = Math.round(gs.l + gs.w * domain[0]);
var y = Math.round(gs.t + gs.h * (1 - axisOpts._counterDomainMin) + (axisOpts.side === 'bottom' ? axisOpts._depth : 0) + opts._offsetShift + constants.extraPad);
rangeSlider.attr('transform', strTranslate(x, y));
// update data <--> pixel coordinate conversion methods
opts._rl = Lib.simpleMap(opts.range, axisOpts.r2l);
var rl0 = opts._rl[0];
var rl1 = opts._rl[1];
var drl = rl1 - rl0;
opts.p2d = function (v) {
return v / opts._width * drl + rl0;
};
opts.d2p = function (v) {
return (v - rl0) / drl * opts._width;
};
if (axisOpts.rangebreaks) {
var rsBreaks = axisOpts.locateBreaks(rl0, rl1);
if (rsBreaks.length) {
var j, brk;
var lBreaks = 0;
for (j = 0; j < rsBreaks.length; j++) {
brk = rsBreaks[j];
lBreaks += brk.max - brk.min;
}
// TODO fix for reversed-range axes !!!
// compute slope and piecewise offsets
var m2 = opts._width / (rl1 - rl0 - lBreaks);
var _B = [-m2 * rl0];
for (j = 0; j < rsBreaks.length; j++) {
brk = rsBreaks[j];
_B.push(_B[_B.length - 1] - m2 * (brk.max - brk.min));
}
opts.d2p = function (v) {
var b = _B[0];
for (var j = 0; j < rsBreaks.length; j++) {
var brk = rsBreaks[j];
if (v >= brk.max) b = _B[j + 1];else if (v < brk.min) break;
}
return b + m2 * v;
};
// fill pixel (i.e. 'p') min/max here,
// to not have to loop through the _rangebreaks twice during `p2d`
for (j = 0; j < rsBreaks.length; j++) {
brk = rsBreaks[j];
brk.pmin = opts.d2p(brk.min);
brk.pmax = opts.d2p(brk.max);
}
opts.p2d = function (v) {
var b = _B[0];
for (var j = 0; j < rsBreaks.length; j++) {
var brk = rsBreaks[j];
if (v >= brk.pmax) b = _B[j + 1];else if (v < brk.pmin) break;
}
return (v - b) / m2;
};
}
}
if (oppAxisRangeOpts.rangemode !== 'match') {
var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]);
var range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]);
var distOppAxis = range1OppAxis - range0OppAxis;
opts.d2pOppAxis = function (v) {
return (v - range0OppAxis) / distOppAxis * opts._height;
};
}
// update inner nodes
rangeSlider.call(drawBg, gd, axisOpts, opts).call(addClipPath, gd, axisOpts, opts).call(drawRangePlot, gd, axisOpts, opts).call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts).call(drawSlideBox, gd, axisOpts, opts).call(drawGrabbers, gd, axisOpts, opts);
// setup drag element
setupDragElement(rangeSlider, gd, axisOpts, opts);
// update current range
setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts);
// title goes next to range slider instead of tick labels, so
// just take it over and draw it from here
if (axisOpts.side === 'bottom') {
Titles.draw(gd, axisOpts._id + 'title', {
propContainer: axisOpts,
propName: axisOpts._name + '.title',
placeholder: fullLayout._dfltTitle.x,
attributes: {
x: axisOpts._offset + axisOpts._length / 2,
y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.title.font.size,
'text-anchor': 'middle'
}
});
}
});
};
function eventX(event) {
if (typeof event.clientX === 'number') {
return event.clientX;
}
if (event.touches && event.touches.length > 0) {
return event.touches[0].clientX;
}
return 0;
}
function setupDragElement(rangeSlider, gd, axisOpts, opts) {
if (gd._context.staticPlot) return;
var slideBox = rangeSlider.select('rect.' + constants.slideBoxClassName).node();
var grabAreaMin = rangeSlider.select('rect.' + constants.grabAreaMinClassName).node();
var grabAreaMax = rangeSlider.select('rect.' + constants.grabAreaMaxClassName).node();
function mouseDownHandler() {
var event = d3.event;
var target = event.target;
var startX = eventX(event);
var offsetX = startX - rangeSlider.node().getBoundingClientRect().left;
var minVal = opts.d2p(axisOpts._rl[0]);
var maxVal = opts.d2p(axisOpts._rl[1]);
var dragCover = dragElement.coverSlip();
this.addEventListener('touchmove', mouseMove);
this.addEventListener('touchend', mouseUp);
dragCover.addEventListener('mousemove', mouseMove);
dragCover.addEventListener('mouseup', mouseUp);
function mouseMove(e) {
var clientX = eventX(e);
var delta = +clientX - startX;
var pixelMin, pixelMax, cursor;
switch (target) {
case slideBox:
cursor = 'ew-resize';
if (minVal + delta > axisOpts._length || maxVal + delta < 0) {
return;
}
pixelMin = minVal + delta;
pixelMax = maxVal + delta;
break;
case grabAreaMin:
cursor = 'col-resize';
if (minVal + delta > axisOpts._length) {
return;
}
pixelMin = minVal + delta;
pixelMax = maxVal;
break;
case grabAreaMax:
cursor = 'col-resize';
if (maxVal + delta < 0) {
return;
}
pixelMin = minVal;
pixelMax = maxVal + delta;
break;
default:
cursor = 'ew-resize';
pixelMin = offsetX;
pixelMax = offsetX + delta;
break;
}
if (pixelMax < pixelMin) {
var tmp = pixelMax;
pixelMax = pixelMin;
pixelMin = tmp;
}
opts._pixelMin = pixelMin;
opts._pixelMax = pixelMax;
setCursor(d3.select(dragCover), cursor);
setDataRange(rangeSlider, gd, axisOpts, opts);
}
function mouseUp() {
dragCover.removeEventListener('mousemove', mouseMove);
dragCover.removeEventListener('mouseup', mouseUp);
this.removeEventListener('touchmove', mouseMove);
this.removeEventListener('touchend', mouseUp);
Lib.removeElement(dragCover);
}
}
rangeSlider.on('mousedown', mouseDownHandler);
rangeSlider.on('touchstart', mouseDownHandler);
}
function setDataRange(rangeSlider, gd, axisOpts, opts) {
function clamp(v) {
return axisOpts.l2r(Lib.constrain(v, opts._rl[0], opts._rl[1]));
}
var dataMin = clamp(opts.p2d(opts._pixelMin));
var dataMax = clamp(opts.p2d(opts._pixelMax));
window.requestAnimationFrame(function () {
Registry.call('_guiRelayout', gd, axisOpts._name + '.range', [dataMin, dataMax]);
});
}
function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) {
var hw2 = constants.handleWidth / 2;
function clamp(v) {
return Lib.constrain(v, 0, opts._width);
}
function clampOppAxis(v) {
return Lib.constrain(v, 0, opts._height);
}
function clampHandle(v) {
return Lib.constrain(v, -hw2, opts._width + hw2);
}
var pixelMin = clamp(opts.d2p(axisOpts._rl[0]));
var pixelMax = clamp(opts.d2p(axisOpts._rl[1]));
rangeSlider.select('rect.' + constants.slideBoxClassName).attr('x', pixelMin).attr('width', pixelMax - pixelMin);
rangeSlider.select('rect.' + constants.maskMinClassName).attr('width', pixelMin);
rangeSlider.select('rect.' + constants.maskMaxClassName).attr('x', pixelMax).attr('width', opts._width - pixelMax);
if (oppAxisRangeOpts.rangemode !== 'match') {
var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1]));
var pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0]));
rangeSlider.select('rect.' + constants.maskMinOppAxisClassName).attr('x', pixelMin).attr('height', pixelMinOppAxis).attr('width', pixelMax - pixelMin);
rangeSlider.select('rect.' + constants.maskMaxOppAxisClassName).attr('x', pixelMin).attr('y', pixelMaxOppAxis).attr('height', opts._height - pixelMaxOppAxis).attr('width', pixelMax - pixelMin);
rangeSlider.select('rect.' + constants.slideBoxClassName).attr('y', pixelMinOppAxis).attr('height', pixelMaxOppAxis - pixelMinOppAxis);
}
// add offset for crispier corners
// https://github.com/plotly/plotly.js/pull/1409
var offset = 0.5;
var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset;
var xMax = Math.round(clampHandle(pixelMax - hw2)) + offset;
rangeSlider.select('g.' + constants.grabberMinClassName).attr('transform', strTranslate(xMin, offset));
rangeSlider.select('g.' + constants.grabberMaxClassName).attr('transform', strTranslate(xMax, offset));
}
function drawBg(rangeSlider, gd, axisOpts, opts) {
var bg = Lib.ensureSingle(rangeSlider, 'rect', constants.bgClassName, function (s) {
s.attr({
x: 0,
y: 0,
'shape-rendering': 'crispEdges'
});
});
var borderCorrect = opts.borderwidth % 2 === 0 ? opts.borderwidth : opts.borderwidth - 1;
var offsetShift = -opts._offsetShift;
var lw = Drawing.crispRound(gd, opts.borderwidth);
bg.attr({
width: opts._width + borderCorrect,
height: opts._height + borderCorrect,
transform: strTranslate(offsetShift, offsetShift),
'stroke-width': lw
}).call(Color.stroke, opts.bordercolor).call(Color.fill, opts.bgcolor);
}
function addClipPath(rangeSlider, gd, axisOpts, opts) {
var fullLayout = gd._fullLayout;
var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function (s) {
s.append('rect').attr({
x: 0,
y: 0
});
});
clipPath.select('rect').attr({
width: opts._width,
height: opts._height
});
}
function drawRangePlot(rangeSlider, gd, axisOpts, opts) {
var calcData = gd.calcdata;
var rangePlots = rangeSlider.selectAll('g.' + constants.rangePlotClassName).data(axisOpts._subplotsWith, Lib.identity);
rangePlots.enter().append('g').attr('class', function (id) {
return constants.rangePlotClassName + ' ' + id;
}).call(Drawing.setClipUrl, opts._clipId, gd);
rangePlots.order();
rangePlots.exit().remove();
var mainplotinfo;
rangePlots.each(function (id, i) {
var plotgroup = d3.select(this);
var isMainPlot = i === 0;
var oppAxisOpts = axisIDs.getFromId(gd, id, 'y');
var oppAxisName = oppAxisOpts._name;
var oppAxisRangeOpts = opts[oppAxisName];
var mockFigure = {
data: [],
layout: {
xaxis: {
type: axisOpts.type,
domain: [0, 1],
range: opts.range.slice(),
calendar: axisOpts.calendar
},
width: opts._width,
height: opts._height,
margin: {
t: 0,
b: 0,
l: 0,
r: 0
}
},
_context: gd._context
};
if (axisOpts.rangebreaks) {
mockFigure.layout.xaxis.rangebreaks = axisOpts.rangebreaks;
}
mockFigure.layout[oppAxisName] = {
type: oppAxisOpts.type,
domain: [0, 1],
range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(),
calendar: oppAxisOpts.calendar
};
if (oppAxisOpts.rangebreaks) {
mockFigure.layout[oppAxisName].rangebreaks = oppAxisOpts.rangebreaks;
}
Plots.supplyDefaults(mockFigure);
var xa = mockFigure._fullLayout.xaxis;
var ya = mockFigure._fullLayout[oppAxisName];
xa.clearCalc();
xa.setScale();
ya.clearCalc();
ya.setScale();
var plotinfo = {
id: id,
plotgroup: plotgroup,
xaxis: xa,
yaxis: ya,
isRangePlot: true
};
if (isMainPlot) mainplotinfo = plotinfo;else {
plotinfo.mainplot = 'xy';
plotinfo.mainplotinfo = mainplotinfo;
}
Cartesian.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id));
});
}
function filterRangePlotCalcData(calcData, subplotId) {
var out = [];
for (var i = 0; i < calcData.length; i++) {
var calcTrace = calcData[i];
var trace = calcTrace[0].trace;
if (trace.xaxis + trace.yaxis === subplotId) {
out.push(calcTrace);
}
}
return out;
}
function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) {
var maskMin = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinClassName, function (s) {
s.attr({
x: 0,
y: 0,
'shape-rendering': 'crispEdges'
});
});
maskMin.attr('height', opts._height).call(Color.fill, constants.maskColor);
var maskMax = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxClassName, function (s) {
s.attr({
y: 0,
'shape-rendering': 'crispEdges'
});
});
maskMax.attr('height', opts._height).call(Color.fill, constants.maskColor);
// masks used for oppAxis zoom
if (oppAxisRangeOpts.rangemode !== 'match') {
var maskMinOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinOppAxisClassName, function (s) {
s.attr({
y: 0,
'shape-rendering': 'crispEdges'
});
});
maskMinOppAxis.attr('width', opts._width).call(Color.fill, constants.maskOppAxisColor);
var maskMaxOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxOppAxisClassName, function (s) {
s.attr({
y: 0,
'shape-rendering': 'crispEdges'
});
});
maskMaxOppAxis.attr('width', opts._width).style('border-top', constants.maskOppBorder).call(Color.fill, constants.maskOppAxisColor);
}
}
function drawSlideBox(rangeSlider, gd, axisOpts, opts) {
if (gd._context.staticPlot) return;
var slideBox = Lib.ensureSingle(rangeSlider, 'rect', constants.slideBoxClassName, function (s) {
s.attr({
y: 0,
cursor: constants.slideBoxCursor,
'shape-rendering': 'crispEdges'
});
});
slideBox.attr({
height: opts._height,
fill: constants.slideBoxFill
});
}
function drawGrabbers(rangeSlider, gd, axisOpts, opts) {
//
var grabberMin = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMinClassName);
var grabberMax = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMaxClassName);
//
var handleFixAttrs = {
x: 0,
width: constants.handleWidth,
rx: constants.handleRadius,
fill: Color.background,
stroke: Color.defaultLine,
'stroke-width': constants.handleStrokeWidth,
'shape-rendering': 'crispEdges'
};
var handleDynamicAttrs = {
y: Math.round(opts._height / 4),
height: Math.round(opts._height / 2)
};
var handleMin = Lib.ensureSingle(grabberMin, 'rect', constants.handleMinClassName, function (s) {
s.attr(handleFixAttrs);
});
handleMin.attr(handleDynamicAttrs);
var handleMax = Lib.ensureSingle(grabberMax, 'rect', constants.handleMaxClassName, function (s) {
s.attr(handleFixAttrs);
});
handleMax.attr(handleDynamicAttrs);
//
var grabAreaFixAttrs = {
width: constants.grabAreaWidth,
x: 0,
y: 0,
fill: constants.grabAreaFill,
cursor: !gd._context.staticPlot ? constants.grabAreaCursor : undefined
};
var grabAreaMin = Lib.ensureSingle(grabberMin, 'rect', constants.grabAreaMinClassName, function (s) {
s.attr(grabAreaFixAttrs);
});
grabAreaMin.attr('height', opts._height);
var grabAreaMax = Lib.ensureSingle(grabberMax, 'rect', constants.grabAreaMaxClassName, function (s) {
s.attr(grabAreaFixAttrs);
});
grabAreaMax.attr('height', opts._height);
}
/***/ }),
/***/ 97944:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var axisIDs = __webpack_require__(79811);
var svgTextUtils = __webpack_require__(72736);
var constants = __webpack_require__(74636);
var LINE_SPACING = (__webpack_require__(84284).LINE_SPACING);
var name = constants.name;
function isVisible(ax) {
var rangeSlider = ax && ax[name];
return rangeSlider && rangeSlider.visible;
}
exports.isVisible = isVisible;
exports.makeData = function (fullLayout) {
var axes = axisIDs.list({
_fullLayout: fullLayout
}, 'x', true);
var margin = fullLayout.margin;
var rangeSliderData = [];
if (!fullLayout._has('gl2d')) {
for (var i = 0; i < axes.length; i++) {
var ax = axes[i];
if (isVisible(ax)) {
rangeSliderData.push(ax);
var opts = ax[name];
opts._id = name + ax._id;
opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness;
opts._offsetShift = Math.floor(opts.borderwidth / 2);
}
}
}
fullLayout._rangeSliderData = rangeSliderData;
};
exports.autoMarginOpts = function (gd, ax) {
var fullLayout = gd._fullLayout;
var opts = ax[name];
var axLetter = ax._id.charAt(0);
var bottomDepth = 0;
var titleHeight = 0;
if (ax.side === 'bottom') {
bottomDepth = ax._depth;
if (ax.title.text !== fullLayout._dfltTitle[axLetter]) {
// as in rangeslider/draw.js
titleHeight = 1.5 * ax.title.font.size + 10 + opts._offsetShift;
// multi-line extra bump
var extraLines = (ax.title.text.match(svgTextUtils.BR_TAG_ALL) || []).length;
titleHeight += extraLines * ax.title.font.size * LINE_SPACING;
}
}
return {
x: 0,
y: ax._counterDomainMin,
l: 0,
r: 0,
t: 0,
b: opts._height + bottomDepth + Math.max(fullLayout.margin.b, titleHeight),
pad: constants.extraPad + opts._offsetShift * 2
};
};
/***/ }),
/***/ 49692:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attrs = __webpack_require__(11200);
var oppAxisAttrs = __webpack_require__(10936);
var helpers = __webpack_require__(97944);
module.exports = {
moduleType: 'component',
name: 'rangeslider',
schema: {
subplots: {
xaxis: {
rangeslider: Lib.extendFlat({}, attrs, {
yaxis: oppAxisAttrs
})
}
}
},
layoutAttributes: __webpack_require__(11200),
handleDefaults: __webpack_require__(94040),
calcAutorange: __webpack_require__(26652),
draw: __webpack_require__(20060),
isVisible: helpers.isVisible,
makeData: helpers.makeData,
autoMarginOpts: helpers.autoMarginOpts
};
/***/ }),
/***/ 10936:
/***/ (function(module) {
"use strict";
module.exports = {
// not really a 'subplot' attribute container,
// but this is the flag we use to denote attributes that
// support yaxis, yaxis2, yaxis3, ... counters
_isSubplotObj: true,
rangemode: {
valType: 'enumerated',
values: ['auto', 'fixed', 'match'],
dflt: 'match',
editType: 'calc'
},
range: {
valType: 'info_array',
items: [{
valType: 'any',
editType: 'plot'
}, {
valType: 'any',
editType: 'plot'
}],
editType: 'plot'
},
editType: 'calc'
};
/***/ }),
/***/ 93956:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var annAttrs = __webpack_require__(13916);
var scatterLineAttrs = (__webpack_require__(52904).line);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var templatedArray = (__webpack_require__(31780).templatedArray);
var axisPlaceableObjs = __webpack_require__(36208);
module.exports = overrideAll(templatedArray('selection', {
type: {
valType: 'enumerated',
values: ['rect', 'path']
},
xref: extendFlat({}, annAttrs.xref, {}),
yref: extendFlat({}, annAttrs.yref, {}),
x0: {
valType: 'any'
},
x1: {
valType: 'any'
},
y0: {
valType: 'any'
},
y1: {
valType: 'any'
},
path: {
valType: 'string',
editType: 'arraydraw'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.7,
editType: 'arraydraw'
},
line: {
color: scatterLineAttrs.color,
width: extendFlat({}, scatterLineAttrs.width, {
min: 1,
dflt: 1
}),
dash: extendFlat({}, dash, {
dflt: 'dot'
})
}
}), 'arraydraw', 'from-root');
/***/ }),
/***/ 83280:
/***/ (function(module) {
"use strict";
module.exports = {
// max pixels off straight before a lasso select line counts as bent
BENDPX: 1.5,
// smallest dimension allowed for a select box
MINSELECT: 12,
// throttling limit (ms) for selectPoints calls
SELECTDELAY: 100,
// cache ID suffix for throttle
SELECTID: '-select'
};
/***/ }),
/***/ 74224:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var handleArrayContainerDefaults = __webpack_require__(51272);
var attributes = __webpack_require__(93956);
var helpers = __webpack_require__(65152);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
handleArrayContainerDefaults(layoutIn, layoutOut, {
name: 'selections',
handleItemDefaults: handleSelectionDefaults
});
// Drop rect selections with undefined x0, y0, x1, x1 values.
// In future we may accept partially defined rects e.g.
// a case with only x0 and x1 may be used to define
// [-Infinity, +Infinity] range on the y axis, etc.
var selections = layoutOut.selections;
for (var i = 0; i < selections.length; i++) {
var selection = selections[i];
if (!selection) continue;
if (selection.path === undefined) {
if (selection.x0 === undefined || selection.x1 === undefined || selection.y0 === undefined || selection.y1 === undefined) {
layoutOut.selections[i] = null;
}
}
}
};
function handleSelectionDefaults(selectionIn, selectionOut, fullLayout) {
function coerce(attr, dflt) {
return Lib.coerce(selectionIn, selectionOut, attributes, attr, dflt);
}
var path = coerce('path');
var dfltType = path ? 'path' : 'rect';
var selectionType = coerce('type', dfltType);
var noPath = selectionType !== 'path';
if (noPath) delete selectionOut.path;
coerce('opacity');
coerce('line.color');
coerce('line.width');
coerce('line.dash');
// positioning
var axLetters = ['x', 'y'];
for (var i = 0; i < 2; i++) {
var axLetter = axLetters[i];
var gdMock = {
_fullLayout: fullLayout
};
var ax;
var pos2r;
var r2pos;
// xref, yref
var axRef = Axes.coerceRef(selectionIn, selectionOut, gdMock, axLetter);
// axRefType is 'range' for selections
ax = Axes.getFromId(gdMock, axRef);
ax._selectionIndices.push(selectionOut._index);
r2pos = helpers.rangeToShapePosition(ax);
pos2r = helpers.shapePositionToRange(ax);
// Coerce x0, x1, y0, y1
if (noPath) {
// hack until V3.0 when log has regular range behavior - make it look like other
// ranges to send to coerce, then put it back after
// this is all to give reasonable default position behavior on log axes, which is
// a pretty unimportant edge case so we could just ignore this.
var attr0 = axLetter + '0';
var attr1 = axLetter + '1';
var in0 = selectionIn[attr0];
var in1 = selectionIn[attr1];
selectionIn[attr0] = pos2r(selectionIn[attr0], true);
selectionIn[attr1] = pos2r(selectionIn[attr1], true);
Axes.coercePosition(selectionOut, gdMock, coerce, axRef, attr0);
Axes.coercePosition(selectionOut, gdMock, coerce, axRef, attr1);
var p0 = selectionOut[attr0];
var p1 = selectionOut[attr1];
if (p0 !== undefined && p1 !== undefined) {
// hack part 2
selectionOut[attr0] = r2pos(p0);
selectionOut[attr1] = r2pos(p1);
selectionIn[attr0] = in0;
selectionIn[attr1] = in1;
}
}
}
if (noPath) {
Lib.noneOrAll(selectionIn, selectionOut, ['x0', 'x1', 'y0', 'y1']);
}
}
/***/ }),
/***/ 23640:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var readPaths = (__webpack_require__(9856).readPaths);
var displayOutlines = __webpack_require__(55496);
var clearOutlineControllers = (__webpack_require__(1936).clearOutlineControllers);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var arrayEditor = (__webpack_require__(31780).arrayEditor);
var helpers = __webpack_require__(65152);
var getPathString = helpers.getPathString;
// Selections are stored in gd.layout.selections, an array of objects
// index can point to one item in this array,
// or non-numeric to simply add a new one
// or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
// or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
// annotation at that point in the array, or 'remove' to delete this one
module.exports = {
draw: draw,
drawOne: drawOne,
activateLastSelection: activateLastSelection
};
function draw(gd) {
var fullLayout = gd._fullLayout;
clearOutlineControllers(gd);
// Remove previous selections before drawing new selections in fullLayout.selections
fullLayout._selectionLayer.selectAll('path').remove();
for (var k in fullLayout._plots) {
var selectionLayer = fullLayout._plots[k].selectionLayer;
if (selectionLayer) selectionLayer.selectAll('path').remove();
}
for (var i = 0; i < fullLayout.selections.length; i++) {
drawOne(gd, i);
}
}
function couldHaveActiveSelection(gd) {
return gd._context.editSelection;
}
function drawOne(gd, index) {
// remove the existing selection if there is one.
// because indices can change, we need to look in all selection layers
gd._fullLayout._paperdiv.selectAll('.selectionlayer [data-index="' + index + '"]').remove();
var o = helpers.makeSelectionsOptionsAndPlotinfo(gd, index);
var options = o.options;
var plotinfo = o.plotinfo;
// this selection is gone - quit now after deleting it
// TODO: use d3 idioms instead of deleting and redrawing every time
if (!options._input) return;
drawSelection(gd._fullLayout._selectionLayer);
function drawSelection(selectionLayer) {
var d = getPathString(gd, options);
var attrs = {
'data-index': index,
'fill-rule': 'evenodd',
d: d
};
var opacity = options.opacity;
var fillColor = 'rgba(0,0,0,0)';
var lineColor = options.line.color || Color.contrast(gd._fullLayout.plot_bgcolor);
var lineWidth = options.line.width;
var lineDash = options.line.dash;
if (!lineWidth) {
// ensure invisible border to activate the selection
lineWidth = 5;
lineDash = 'solid';
}
var isActiveSelection = couldHaveActiveSelection(gd) && gd._fullLayout._activeSelectionIndex === index;
if (isActiveSelection) {
fillColor = gd._fullLayout.activeselection.fillcolor;
opacity = gd._fullLayout.activeselection.opacity;
}
var allPaths = [];
for (var sensory = 1; sensory >= 0; sensory--) {
var path = selectionLayer.append('path').attr(attrs).style('opacity', sensory ? 0.1 : opacity).call(Color.stroke, lineColor).call(Color.fill, fillColor)
// make it easier to select senory background path
.call(Drawing.dashLine, sensory ? 'solid' : lineDash, sensory ? 4 + lineWidth : lineWidth);
setClipPath(path, gd, options);
if (isActiveSelection) {
var editHelpers = arrayEditor(gd.layout, 'selections', options);
path.style({
cursor: 'move'
});
var dragOptions = {
element: path.node(),
plotinfo: plotinfo,
gd: gd,
editHelpers: editHelpers,
isActiveSelection: true // i.e. to enable controllers
};
var polygons = readPaths(d, gd);
// display polygons on the screen
displayOutlines(polygons, path, dragOptions);
} else {
path.style('pointer-events', sensory ? 'all' : 'none');
}
allPaths[sensory] = path;
}
var forePath = allPaths[0];
var backPath = allPaths[1];
backPath.node().addEventListener('click', function () {
return activateSelection(gd, forePath);
});
}
}
function setClipPath(selectionPath, gd, selectionOptions) {
var clipAxes = selectionOptions.xref + selectionOptions.yref;
Drawing.setClipUrl(selectionPath, 'clip' + gd._fullLayout._uid + clipAxes, gd);
}
function activateSelection(gd, path) {
if (!couldHaveActiveSelection(gd)) return;
var element = path.node();
var id = +element.getAttribute('data-index');
if (id >= 0) {
// deactivate if already active
if (id === gd._fullLayout._activeSelectionIndex) {
deactivateSelection(gd);
return;
}
gd._fullLayout._activeSelectionIndex = id;
gd._fullLayout._deactivateSelection = deactivateSelection;
draw(gd);
}
}
function activateLastSelection(gd) {
if (!couldHaveActiveSelection(gd)) return;
var id = gd._fullLayout.selections.length - 1;
gd._fullLayout._activeSelectionIndex = id;
gd._fullLayout._deactivateSelection = deactivateSelection;
draw(gd);
}
function deactivateSelection(gd) {
if (!couldHaveActiveSelection(gd)) return;
var id = gd._fullLayout._activeSelectionIndex;
if (id >= 0) {
clearOutlineControllers(gd);
delete gd._fullLayout._activeSelectionIndex;
draw(gd);
}
}
/***/ }),
/***/ 34200:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var dash = (__webpack_require__(98192)/* .dash */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = {
newselection: {
mode: {
valType: 'enumerated',
values: ['immediate', 'gradual'],
dflt: 'immediate',
editType: 'none'
},
line: {
color: {
valType: 'color',
editType: 'none'
},
width: {
valType: 'number',
min: 1,
dflt: 1,
editType: 'none'
},
dash: extendFlat({}, dash, {
dflt: 'dot',
editType: 'none'
}),
editType: 'none'
},
// no drawdirection here noting that layout.selectdirection is used instead.
editType: 'none'
},
activeselection: {
fillcolor: {
valType: 'color',
dflt: 'rgba(0,0,0,0)',
editType: 'none'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.5,
editType: 'none'
},
editType: 'none'
}
};
/***/ }),
/***/ 81004:
/***/ (function(module) {
"use strict";
module.exports = function supplyDrawNewSelectionDefaults(layoutIn, layoutOut, coerce) {
coerce('newselection.mode');
var newselectionLineWidth = coerce('newselection.line.width');
if (newselectionLineWidth) {
coerce('newselection.line.color');
coerce('newselection.line.dash');
}
coerce('activeselection.fillcolor');
coerce('activeselection.opacity');
};
/***/ }),
/***/ 5968:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var dragHelpers = __webpack_require__(72760);
var selectMode = dragHelpers.selectMode;
var handleOutline = __webpack_require__(1936);
var clearOutline = handleOutline.clearOutline;
var helpers = __webpack_require__(9856);
var readPaths = helpers.readPaths;
var writePaths = helpers.writePaths;
var fixDatesForPaths = helpers.fixDatesForPaths;
module.exports = function newSelections(outlines, dragOptions) {
if (!outlines.length) return;
var e = outlines[0][0]; // pick first
if (!e) return;
var d = e.getAttribute('d');
var gd = dragOptions.gd;
var newStyle = gd._fullLayout.newselection;
var plotinfo = dragOptions.plotinfo;
var xaxis = plotinfo.xaxis;
var yaxis = plotinfo.yaxis;
var isActiveSelection = dragOptions.isActiveSelection;
var dragmode = dragOptions.dragmode;
var selections = (gd.layout || {}).selections || [];
if (!selectMode(dragmode) && isActiveSelection !== undefined) {
var id = gd._fullLayout._activeSelectionIndex;
if (id < selections.length) {
switch (gd._fullLayout.selections[id].type) {
case 'rect':
dragmode = 'select';
break;
case 'path':
dragmode = 'lasso';
break;
}
}
}
var polygons = readPaths(d, gd, plotinfo, isActiveSelection);
var newSelection = {
xref: xaxis._id,
yref: yaxis._id,
opacity: newStyle.opacity,
line: {
color: newStyle.line.color,
width: newStyle.line.width,
dash: newStyle.line.dash
}
};
var cell;
// rect can be in one cell
// only define cell if there is single cell
if (polygons.length === 1) cell = polygons[0];
if (cell && cell.length === 5 &&
// ensure we only have 4 corners for a rect
dragmode === 'select') {
newSelection.type = 'rect';
newSelection.x0 = cell[0][1];
newSelection.y0 = cell[0][2];
newSelection.x1 = cell[2][1];
newSelection.y1 = cell[2][2];
} else {
newSelection.type = 'path';
if (xaxis && yaxis) fixDatesForPaths(polygons, xaxis, yaxis);
newSelection.path = writePaths(polygons);
cell = null;
}
clearOutline(gd);
var editHelpers = dragOptions.editHelpers;
var modifyItem = (editHelpers || {}).modifyItem;
var allSelections = [];
for (var q = 0; q < selections.length; q++) {
var beforeEdit = gd._fullLayout.selections[q];
if (!beforeEdit) {
allSelections[q] = beforeEdit;
continue;
}
allSelections[q] = beforeEdit._input;
if (isActiveSelection !== undefined && q === gd._fullLayout._activeSelectionIndex) {
var afterEdit = newSelection;
switch (beforeEdit.type) {
case 'rect':
modifyItem('x0', afterEdit.x0);
modifyItem('x1', afterEdit.x1);
modifyItem('y0', afterEdit.y0);
modifyItem('y1', afterEdit.y1);
break;
case 'path':
modifyItem('path', afterEdit.path);
break;
}
}
}
if (isActiveSelection === undefined) {
allSelections.push(newSelection); // add new selection
return allSelections;
}
return editHelpers ? editHelpers.getUpdateObj() : {};
};
/***/ }),
/***/ 5840:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var strTranslate = (__webpack_require__(3400).strTranslate);
// in v3 (once log ranges are fixed),
// we'll be able to p2r here for all axis types
function p2r(ax, v) {
switch (ax.type) {
case 'log':
return ax.p2d(v);
case 'date':
return ax.p2r(v, 0, ax.calendar);
default:
return ax.p2r(v);
}
}
function r2p(ax, v) {
switch (ax.type) {
case 'log':
return ax.d2p(v);
case 'date':
return ax.r2p(v, 0, ax.calendar);
default:
return ax.r2p(v);
}
}
function axValue(ax) {
var index = ax._id.charAt(0) === 'y' ? 1 : 0;
return function (v) {
return p2r(ax, v[index]);
};
}
function getTransform(plotinfo) {
return strTranslate(plotinfo.xaxis._offset, plotinfo.yaxis._offset);
}
module.exports = {
p2r: p2r,
r2p: r2p,
axValue: axValue,
getTransform: getTransform
};
/***/ }),
/***/ 22676:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var drawModule = __webpack_require__(23640);
var select = __webpack_require__(43156);
module.exports = {
moduleType: 'component',
name: 'selections',
layoutAttributes: __webpack_require__(93956),
supplyLayoutDefaults: __webpack_require__(74224),
supplyDrawNewSelectionDefaults: __webpack_require__(81004),
includeBasePlot: __webpack_require__(36632)('selections'),
draw: drawModule.draw,
drawOne: drawModule.drawOne,
reselect: select.reselect,
prepSelect: select.prepSelect,
clearOutline: select.clearOutline,
clearSelectionsCache: select.clearSelectionsCache,
selectOnClick: select.selectOnClick
};
/***/ }),
/***/ 43156:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var polybool = __webpack_require__(14756);
var pointInPolygon = __webpack_require__(61456); // could we use contains lib/polygon instead?
var Registry = __webpack_require__(24040);
var dashStyle = (__webpack_require__(43616).dashStyle);
var Color = __webpack_require__(76308);
var Fx = __webpack_require__(93024);
var makeEventData = (__webpack_require__(10624).makeEventData);
var dragHelpers = __webpack_require__(72760);
var freeMode = dragHelpers.freeMode;
var rectMode = dragHelpers.rectMode;
var drawMode = dragHelpers.drawMode;
var openMode = dragHelpers.openMode;
var selectMode = dragHelpers.selectMode;
var shapeHelpers = __webpack_require__(65152);
var shapeConstants = __webpack_require__(85448);
var displayOutlines = __webpack_require__(55496);
var clearOutline = (__webpack_require__(1936).clearOutline);
var newShapeHelpers = __webpack_require__(9856);
var handleEllipse = newShapeHelpers.handleEllipse;
var readPaths = newShapeHelpers.readPaths;
var newShapes = (__webpack_require__(93940).newShapes);
var newSelections = __webpack_require__(5968);
var activateLastSelection = (__webpack_require__(23640).activateLastSelection);
var Lib = __webpack_require__(3400);
var ascending = Lib.sorterAsc;
var libPolygon = __webpack_require__(92065);
var throttle = __webpack_require__(91200);
var getFromId = (__webpack_require__(79811).getFromId);
var clearGlCanvases = __webpack_require__(73696);
var redrawReglTraces = (__webpack_require__(39172).redrawReglTraces);
var constants = __webpack_require__(83280);
var MINSELECT = constants.MINSELECT;
var filteredPolygon = libPolygon.filter;
var polygonTester = libPolygon.tester;
var helpers = __webpack_require__(5840);
var p2r = helpers.p2r;
var axValue = helpers.axValue;
var getTransform = helpers.getTransform;
function hasSubplot(dragOptions) {
// N.B. subplot may be falsy e.g zero sankey index!
return dragOptions.subplot !== undefined;
}
function prepSelect(evt, startX, startY, dragOptions, mode) {
var isCartesian = !hasSubplot(dragOptions);
var isFreeMode = freeMode(mode);
var isRectMode = rectMode(mode);
var isOpenMode = openMode(mode);
var isDrawMode = drawMode(mode);
var isSelectMode = selectMode(mode);
var isLine = mode === 'drawline';
var isEllipse = mode === 'drawcircle';
var isLineOrEllipse = isLine || isEllipse; // cases with two start & end positions
var gd = dragOptions.gd;
var fullLayout = gd._fullLayout;
var immediateSelect = isSelectMode && fullLayout.newselection.mode === 'immediate' && isCartesian; // N.B. only cartesian subplots have persistent selection
var zoomLayer = fullLayout._zoomlayer;
var dragBBox = dragOptions.element.getBoundingClientRect();
var plotinfo = dragOptions.plotinfo;
var transform = getTransform(plotinfo);
var x0 = startX - dragBBox.left;
var y0 = startY - dragBBox.top;
fullLayout._calcInverseTransform(gd);
var transformedCoords = Lib.apply3DTransform(fullLayout._invTransform)(x0, y0);
x0 = transformedCoords[0];
y0 = transformedCoords[1];
var scaleX = fullLayout._invScaleX;
var scaleY = fullLayout._invScaleY;
var x1 = x0;
var y1 = y0;
var path0 = 'M' + x0 + ',' + y0;
var xAxis = dragOptions.xaxes[0];
var yAxis = dragOptions.yaxes[0];
var pw = xAxis._length;
var ph = yAxis._length;
var subtract = evt.altKey && !(drawMode(mode) && isOpenMode);
var filterPoly, selectionTesters, mergedPolygons, currentPolygon;
var i, searchInfo, eventData;
coerceSelectionsCache(evt, gd, dragOptions);
if (isFreeMode) {
filterPoly = filteredPolygon([[x0, y0]], constants.BENDPX);
}
var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1]);
var newStyle = isDrawMode ? fullLayout.newshape : fullLayout.newselection;
if (isDrawMode) {
dragOptions.hasText = newStyle.label.text || newStyle.label.texttemplate;
}
var fillC = isDrawMode && !isOpenMode ? newStyle.fillcolor : 'rgba(0,0,0,0)';
var strokeC = newStyle.line.color || (isCartesian ? Color.contrast(gd._fullLayout.plot_bgcolor) : '#7f7f7f' // non-cartesian subplot
);
outlines.enter().append('path').attr('class', 'select-outline select-outline-' + plotinfo.id).style({
opacity: isDrawMode ? newStyle.opacity / 2 : 1,
'stroke-dasharray': dashStyle(newStyle.line.dash, newStyle.line.width),
'stroke-width': newStyle.line.width + 'px',
'shape-rendering': 'crispEdges'
}).call(Color.stroke, strokeC).call(Color.fill, fillC).attr('fill-rule', 'evenodd').classed('cursor-move', isDrawMode ? true : false).attr('transform', transform).attr('d', path0 + 'Z');
var corners = zoomLayer.append('path').attr('class', 'zoombox-corners').style({
fill: Color.background,
stroke: Color.defaultLine,
'stroke-width': 1
}).attr('transform', transform).attr('d', 'M0,0Z');
// create & style group for text label
if (isDrawMode && dragOptions.hasText) {
var shapeGroup = zoomLayer.select('.label-temp');
if (shapeGroup.empty()) {
shapeGroup = zoomLayer.append('g').classed('label-temp', true).classed('select-outline', true).style({
opacity: 0.8
});
}
}
var throttleID = fullLayout._uid + constants.SELECTID;
var selection = [];
// find the traces to search for selection points
var searchTraces = determineSearchTraces(gd, dragOptions.xaxes, dragOptions.yaxes, dragOptions.subplot);
if (immediateSelect && !evt.shiftKey) {
dragOptions._clearSubplotSelections = function () {
if (!isCartesian) return;
var xRef = xAxis._id;
var yRef = yAxis._id;
deselectSubplot(gd, xRef, yRef, searchTraces);
var selections = (gd.layout || {}).selections || [];
var list = [];
var selectionErased = false;
for (var q = 0; q < selections.length; q++) {
var s = fullLayout.selections[q];
if (s.xref !== xRef || s.yref !== yRef) {
list.push(selections[q]);
} else {
selectionErased = true;
}
}
if (selectionErased) {
gd._fullLayout._noEmitSelectedAtStart = true;
Registry.call('_guiRelayout', gd, {
selections: list
});
}
};
}
var fillRangeItems = getFillRangeItems(dragOptions);
dragOptions.moveFn = function (dx0, dy0) {
if (dragOptions._clearSubplotSelections) {
dragOptions._clearSubplotSelections();
dragOptions._clearSubplotSelections = undefined;
}
x1 = Math.max(0, Math.min(pw, scaleX * dx0 + x0));
y1 = Math.max(0, Math.min(ph, scaleY * dy0 + y0));
var dx = Math.abs(x1 - x0);
var dy = Math.abs(y1 - y0);
if (isRectMode) {
var direction;
var start, end;
if (isSelectMode) {
var q = fullLayout.selectdirection;
if (q === 'any') {
if (dy < Math.min(dx * 0.6, MINSELECT)) {
direction = 'h';
} else if (dx < Math.min(dy * 0.6, MINSELECT)) {
direction = 'v';
} else {
direction = 'd';
}
} else {
direction = q;
}
switch (direction) {
case 'h':
start = isEllipse ? ph / 2 : 0;
end = ph;
break;
case 'v':
start = isEllipse ? pw / 2 : 0;
end = pw;
break;
}
}
if (isDrawMode) {
switch (fullLayout.newshape.drawdirection) {
case 'vertical':
direction = 'h';
start = isEllipse ? ph / 2 : 0;
end = ph;
break;
case 'horizontal':
direction = 'v';
start = isEllipse ? pw / 2 : 0;
end = pw;
break;
case 'ortho':
if (dx < dy) {
direction = 'h';
start = y0;
end = y1;
} else {
direction = 'v';
start = x0;
end = x1;
}
break;
default:
// i.e. case of 'diagonal'
direction = 'd';
}
}
if (direction === 'h') {
// horizontal motion
currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [x1, start], [x1, end]) :
// using x1 instead of x0 allows adjusting the line while drawing
[[x0, start], [x0, end], [x1, end], [x1, start]]; // make a vertical box
currentPolygon.xmin = isLineOrEllipse ? x1 : Math.min(x0, x1);
currentPolygon.xmax = isLineOrEllipse ? x1 : Math.max(x0, x1);
currentPolygon.ymin = Math.min(start, end);
currentPolygon.ymax = Math.max(start, end);
// extras to guide users in keeping a straight selection
corners.attr('d', 'M' + currentPolygon.xmin + ',' + (y0 - MINSELECT) + 'h-4v' + 2 * MINSELECT + 'h4Z' + 'M' + (currentPolygon.xmax - 1) + ',' + (y0 - MINSELECT) + 'h4v' + 2 * MINSELECT + 'h-4Z');
} else if (direction === 'v') {
// vertical motion
currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [start, y1], [end, y1]) :
// using y1 instead of y0 allows adjusting the line while drawing
[[start, y0], [start, y1], [end, y1], [end, y0]]; // make a horizontal box
currentPolygon.xmin = Math.min(start, end);
currentPolygon.xmax = Math.max(start, end);
currentPolygon.ymin = isLineOrEllipse ? y1 : Math.min(y0, y1);
currentPolygon.ymax = isLineOrEllipse ? y1 : Math.max(y0, y1);
corners.attr('d', 'M' + (x0 - MINSELECT) + ',' + currentPolygon.ymin + 'v-4h' + 2 * MINSELECT + 'v4Z' + 'M' + (x0 - MINSELECT) + ',' + (currentPolygon.ymax - 1) + 'v4h' + 2 * MINSELECT + 'v-4Z');
} else if (direction === 'd') {
// diagonal motion
currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [x0, y0], [x1, y1]) : [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
currentPolygon.xmin = Math.min(x0, x1);
currentPolygon.xmax = Math.max(x0, x1);
currentPolygon.ymin = Math.min(y0, y1);
currentPolygon.ymax = Math.max(y0, y1);
corners.attr('d', 'M0,0Z');
}
} else if (isFreeMode) {
filterPoly.addPt([x1, y1]);
currentPolygon = filterPoly.filtered;
}
// create outline & tester
if (dragOptions.selectionDefs && dragOptions.selectionDefs.length) {
mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract);
currentPolygon.subtract = subtract;
selectionTesters = multiTester(dragOptions.selectionDefs.concat([currentPolygon]));
} else {
mergedPolygons = [currentPolygon];
selectionTesters = polygonTester(currentPolygon);
}
// display polygons on the screen
displayOutlines(convertPoly(mergedPolygons, isOpenMode), outlines, dragOptions);
if (isSelectMode) {
var _res = reselect(gd, false);
var extraPoints = _res.eventData ? _res.eventData.points.slice() : [];
_res = reselect(gd, false, selectionTesters, searchTraces, dragOptions);
selectionTesters = _res.selectionTesters;
eventData = _res.eventData;
var poly;
if (filterPoly) {
poly = filterPoly.filtered;
} else {
poly = castMultiPolygon(mergedPolygons);
}
throttle.throttle(throttleID, constants.SELECTDELAY, function () {
selection = _doSelect(selectionTesters, searchTraces);
var newPoints = selection.slice();
for (var w = 0; w < extraPoints.length; w++) {
var p = extraPoints[w];
var found = false;
for (var u = 0; u < newPoints.length; u++) {
if (newPoints[u].curveNumber === p.curveNumber && newPoints[u].pointNumber === p.pointNumber) {
found = true;
break;
}
}
if (!found) newPoints.push(p);
}
if (newPoints.length) {
if (!eventData) eventData = {};
eventData.points = newPoints;
}
fillRangeItems(eventData, poly);
emitSelecting(gd, eventData);
});
}
};
dragOptions.clickFn = function (numClicks, evt) {
corners.remove();
if (gd._fullLayout._activeShapeIndex >= 0) {
gd._fullLayout._deactivateShape(gd);
return;
}
if (isDrawMode) return;
var clickmode = fullLayout.clickmode;
throttle.done(throttleID).then(function () {
throttle.clear(throttleID);
if (numClicks === 2) {
// clear selection on doubleclick
outlines.remove();
for (i = 0; i < searchTraces.length; i++) {
searchInfo = searchTraces[i];
searchInfo._module.selectPoints(searchInfo, false);
}
updateSelectedState(gd, searchTraces);
clearSelectionsCache(dragOptions);
emitDeselect(gd);
if (searchTraces.length) {
var clickedXaxis = searchTraces[0].xaxis;
var clickedYaxis = searchTraces[0].yaxis;
if (clickedXaxis && clickedYaxis) {
// drop selections in the clicked subplot
var subSelections = [];
var allSelections = gd._fullLayout.selections;
for (var k = 0; k < allSelections.length; k++) {
var s = allSelections[k];
if (!s) continue; // also drop null selections if any
if (s.xref !== clickedXaxis._id || s.yref !== clickedYaxis._id) {
subSelections.push(s);
}
}
if (subSelections.length < allSelections.length) {
gd._fullLayout._noEmitSelectedAtStart = true;
Registry.call('_guiRelayout', gd, {
selections: subSelections
});
}
}
}
} else {
if (clickmode.indexOf('select') > -1) {
selectOnClick(evt, gd, dragOptions.xaxes, dragOptions.yaxes, dragOptions.subplot, dragOptions, outlines);
}
if (clickmode === 'event') {
// TODO: remove in v3 - this was probably never intended to work as it does,
// but in case anyone depends on it we don't want to break it now.
// Note that click-to-select introduced pre v3 also emitts proper
// event data when clickmode is having 'select' in its flag list.
emitSelected(gd, undefined);
}
}
Fx.click(gd, evt, plotinfo.id);
}).catch(Lib.error);
};
dragOptions.doneFn = function () {
corners.remove();
throttle.done(throttleID).then(function () {
throttle.clear(throttleID);
if (!immediateSelect && currentPolygon && dragOptions.selectionDefs) {
// save last polygons
currentPolygon.subtract = subtract;
dragOptions.selectionDefs.push(currentPolygon);
// we have to keep reference to arrays container
dragOptions.mergedPolygons.length = 0;
[].push.apply(dragOptions.mergedPolygons, mergedPolygons);
}
if (immediateSelect || isDrawMode) {
clearSelectionsCache(dragOptions, immediateSelect);
}
if (dragOptions.doneFnCompleted) {
dragOptions.doneFnCompleted(selection);
}
if (isSelectMode) {
emitSelected(gd, eventData);
}
}).catch(Lib.error);
};
}
function selectOnClick(evt, gd, xAxes, yAxes, subplot, dragOptions, polygonOutlines) {
var hoverData = gd._hoverdata;
var fullLayout = gd._fullLayout;
var clickmode = fullLayout.clickmode;
var sendEvents = clickmode.indexOf('event') > -1;
var selection = [];
var searchTraces, searchInfo, currentSelectionDef, selectionTesters, traceSelection;
var thisTracesSelection, pointOrBinSelected, subtract, eventData, i;
if (isHoverDataSet(hoverData)) {
coerceSelectionsCache(evt, gd, dragOptions);
searchTraces = determineSearchTraces(gd, xAxes, yAxes, subplot);
var clickedPtInfo = extractClickedPtInfo(hoverData, searchTraces);
var isBinnedTrace = clickedPtInfo.pointNumbers.length > 0;
// Note: potentially costly operation isPointOrBinSelected is
// called as late as possible through the use of an assignment
// in an if condition.
if (isBinnedTrace ? isOnlyThisBinSelected(searchTraces, clickedPtInfo) : isOnlyOnePointSelected(searchTraces) && (pointOrBinSelected = isPointOrBinSelected(clickedPtInfo))) {
if (polygonOutlines) polygonOutlines.remove();
for (i = 0; i < searchTraces.length; i++) {
searchInfo = searchTraces[i];
searchInfo._module.selectPoints(searchInfo, false);
}
updateSelectedState(gd, searchTraces);
clearSelectionsCache(dragOptions);
if (sendEvents) {
emitDeselect(gd);
}
} else {
subtract = evt.shiftKey && (pointOrBinSelected !== undefined ? pointOrBinSelected : isPointOrBinSelected(clickedPtInfo));
currentSelectionDef = newPointSelectionDef(clickedPtInfo.pointNumber, clickedPtInfo.searchInfo, subtract);
var allSelectionDefs = dragOptions.selectionDefs.concat([currentSelectionDef]);
selectionTesters = multiTester(allSelectionDefs, selectionTesters);
for (i = 0; i < searchTraces.length; i++) {
traceSelection = searchTraces[i]._module.selectPoints(searchTraces[i], selectionTesters);
thisTracesSelection = fillSelectionItem(traceSelection, searchTraces[i]);
if (selection.length) {
for (var j = 0; j < thisTracesSelection.length; j++) {
selection.push(thisTracesSelection[j]);
}
} else selection = thisTracesSelection;
}
eventData = {
points: selection
};
updateSelectedState(gd, searchTraces, eventData);
if (currentSelectionDef && dragOptions) {
dragOptions.selectionDefs.push(currentSelectionDef);
}
if (polygonOutlines) {
var polygons = dragOptions.mergedPolygons;
var isOpenMode = openMode(dragOptions.dragmode);
// display polygons on the screen
displayOutlines(convertPoly(polygons, isOpenMode), polygonOutlines, dragOptions);
}
if (sendEvents) {
emitSelected(gd, eventData);
}
}
}
}
/**
* Constructs a new point selection definition object.
*/
function newPointSelectionDef(pointNumber, searchInfo, subtract) {
return {
pointNumber: pointNumber,
searchInfo: searchInfo,
subtract: !!subtract
};
}
function isPointSelectionDef(o) {
return 'pointNumber' in o && 'searchInfo' in o;
}
/*
* Constructs a new point number tester.
*/
function newPointNumTester(pointSelectionDef) {
return {
xmin: 0,
xmax: 0,
ymin: 0,
ymax: 0,
pts: [],
contains: function (pt, omitFirstEdge, pointNumber, searchInfo) {
var idxWantedTrace = pointSelectionDef.searchInfo.cd[0].trace._expandedIndex;
var idxActualTrace = searchInfo.cd[0].trace._expandedIndex;
return idxActualTrace === idxWantedTrace && pointNumber === pointSelectionDef.pointNumber;
},
isRect: false,
degenerate: false,
subtract: !!pointSelectionDef.subtract
};
}
/**
* Wraps multiple selection testers.
*
* @param {Array} list - An array of selection testers.
*
* @return a selection tester object with a contains function
* that can be called to evaluate a point against all wrapped
* selection testers that were passed in list.
*/
function multiTester(list) {
if (!list.length) return;
var testers = [];
var xmin = isPointSelectionDef(list[0]) ? 0 : list[0][0][0];
var xmax = xmin;
var ymin = isPointSelectionDef(list[0]) ? 0 : list[0][0][1];
var ymax = ymin;
for (var i = 0; i < list.length; i++) {
if (isPointSelectionDef(list[i])) {
testers.push(newPointNumTester(list[i]));
} else {
var tester = polygonTester(list[i]);
tester.subtract = !!list[i].subtract;
testers.push(tester);
xmin = Math.min(xmin, tester.xmin);
xmax = Math.max(xmax, tester.xmax);
ymin = Math.min(ymin, tester.ymin);
ymax = Math.max(ymax, tester.ymax);
}
}
/**
* Tests if the given point is within this tester.
*
* @param {Array} pt - [0] is the x coordinate, [1] is the y coordinate of the point.
* @param {*} arg - An optional parameter to pass down to wrapped testers.
* @param {number} pointNumber - The point number of the point within the underlying data array.
* @param {number} searchInfo - An object identifying the trace the point is contained in.
*
* @return {boolean} true if point is considered to be selected, false otherwise.
*/
function contains(pt, arg, pointNumber, searchInfo) {
var contained = false;
for (var i = 0; i < testers.length; i++) {
if (testers[i].contains(pt, arg, pointNumber, searchInfo)) {
// if contained by subtract tester - exclude the point
contained = !testers[i].subtract;
}
}
return contained;
}
return {
xmin: xmin,
xmax: xmax,
ymin: ymin,
ymax: ymax,
pts: [],
contains: contains,
isRect: false,
degenerate: false
};
}
function coerceSelectionsCache(evt, gd, dragOptions) {
var fullLayout = gd._fullLayout;
var plotinfo = dragOptions.plotinfo;
var dragmode = dragOptions.dragmode;
var selectingOnSameSubplot = fullLayout._lastSelectedSubplot && fullLayout._lastSelectedSubplot === plotinfo.id;
var hasModifierKey = (evt.shiftKey || evt.altKey) && !(drawMode(dragmode) && openMode(dragmode));
if (selectingOnSameSubplot && hasModifierKey && plotinfo.selection && plotinfo.selection.selectionDefs && !dragOptions.selectionDefs) {
// take over selection definitions from prev mode, if any
dragOptions.selectionDefs = plotinfo.selection.selectionDefs;
dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons;
} else if (!hasModifierKey || !plotinfo.selection) {
clearSelectionsCache(dragOptions);
}
// clear selection outline when selecting a different subplot
if (!selectingOnSameSubplot) {
clearOutline(gd);
fullLayout._lastSelectedSubplot = plotinfo.id;
}
}
function hasActiveShape(gd) {
return gd._fullLayout._activeShapeIndex >= 0;
}
function hasActiveSelection(gd) {
return gd._fullLayout._activeSelectionIndex >= 0;
}
function clearSelectionsCache(dragOptions, immediateSelect) {
var dragmode = dragOptions.dragmode;
var plotinfo = dragOptions.plotinfo;
var gd = dragOptions.gd;
if (hasActiveShape(gd)) {
gd._fullLayout._deactivateShape(gd);
}
if (hasActiveSelection(gd)) {
gd._fullLayout._deactivateSelection(gd);
}
var fullLayout = gd._fullLayout;
var zoomLayer = fullLayout._zoomlayer;
var isDrawMode = drawMode(dragmode);
var isSelectMode = selectMode(dragmode);
if (isDrawMode || isSelectMode) {
var outlines = zoomLayer.selectAll('.select-outline-' + plotinfo.id);
if (outlines && gd._fullLayout._outlining) {
// add shape
var shapes;
if (isDrawMode) {
shapes = newShapes(outlines, dragOptions);
}
if (shapes) {
Registry.call('_guiRelayout', gd, {
shapes: shapes
});
}
// add selection
var selections;
if (isSelectMode && !hasSubplot(dragOptions) // only allow cartesian - no mapbox for now
) {
selections = newSelections(outlines, dragOptions);
}
if (selections) {
gd._fullLayout._noEmitSelectedAtStart = true;
Registry.call('_guiRelayout', gd, {
selections: selections
}).then(function () {
if (immediateSelect) {
activateLastSelection(gd);
}
});
}
gd._fullLayout._outlining = false;
}
}
plotinfo.selection = {};
plotinfo.selection.selectionDefs = dragOptions.selectionDefs = [];
plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = [];
}
function getAxId(ax) {
return ax._id;
}
function determineSearchTraces(gd, xAxes, yAxes, subplot) {
if (!gd.calcdata) return [];
var searchTraces = [];
var xAxisIds = xAxes.map(getAxId);
var yAxisIds = yAxes.map(getAxId);
var cd, trace, i;
for (i = 0; i < gd.calcdata.length; i++) {
cd = gd.calcdata[i];
trace = cd[0].trace;
if (trace.visible !== true || !trace._module || !trace._module.selectPoints) continue;
if (hasSubplot({
subplot: subplot
}) && (trace.subplot === subplot || trace.geo === subplot)) {
searchTraces.push(createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]));
} else if (trace.type === 'splom') {
// FIXME: make sure we don't have more than single axis for splom
if (trace._xaxes[xAxisIds[0]] && trace._yaxes[yAxisIds[0]]) {
var info = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
info.scene = gd._fullLayout._splomScenes[trace.uid];
searchTraces.push(info);
}
} else if (trace.type === 'sankey') {
var sankeyInfo = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
searchTraces.push(sankeyInfo);
} else {
if (xAxisIds.indexOf(trace.xaxis) === -1 && (!trace._xA || !trace._xA.overlaying)) continue;
if (yAxisIds.indexOf(trace.yaxis) === -1 && (!trace._yA || !trace._yA.overlaying)) continue;
searchTraces.push(createSearchInfo(trace._module, cd, getFromId(gd, trace.xaxis), getFromId(gd, trace.yaxis)));
}
}
return searchTraces;
}
function createSearchInfo(module, calcData, xaxis, yaxis) {
return {
_module: module,
cd: calcData,
xaxis: xaxis,
yaxis: yaxis
};
}
function isHoverDataSet(hoverData) {
return hoverData && Array.isArray(hoverData) && hoverData[0].hoverOnBox !== true;
}
function extractClickedPtInfo(hoverData, searchTraces) {
var hoverDatum = hoverData[0];
var pointNumber = -1;
var pointNumbers = [];
var searchInfo, i;
for (i = 0; i < searchTraces.length; i++) {
searchInfo = searchTraces[i];
if (hoverDatum.fullData._expandedIndex === searchInfo.cd[0].trace._expandedIndex) {
// Special case for box (and violin)
if (hoverDatum.hoverOnBox === true) {
break;
}
// Hint: in some traces like histogram, one graphical element
// doesn't correspond to one particular data point, but to
// bins of data points. Thus, hoverDatum can have a binNumber
// property instead of pointNumber.
if (hoverDatum.pointNumber !== undefined) {
pointNumber = hoverDatum.pointNumber;
} else if (hoverDatum.binNumber !== undefined) {
pointNumber = hoverDatum.binNumber;
pointNumbers = hoverDatum.pointNumbers;
}
break;
}
}
return {
pointNumber: pointNumber,
pointNumbers: pointNumbers,
searchInfo: searchInfo
};
}
function isPointOrBinSelected(clickedPtInfo) {
var trace = clickedPtInfo.searchInfo.cd[0].trace;
var ptNum = clickedPtInfo.pointNumber;
var ptNums = clickedPtInfo.pointNumbers;
var ptNumsSet = ptNums.length > 0;
// When pointsNumbers is set (e.g. histogram's binning),
// it is assumed that when the first point of
// a bin is selected, all others are as well
var ptNumToTest = ptNumsSet ? ptNums[0] : ptNum;
// TODO potential performance improvement
// Primarily we need this function to determine if a click adds
// or subtracts from a selection.
// In cases `trace.selectedpoints` is a huge array, indexOf
// might be slow. One remedy would be to introduce a hash somewhere.
return trace.selectedpoints ? trace.selectedpoints.indexOf(ptNumToTest) > -1 : false;
}
function isOnlyThisBinSelected(searchTraces, clickedPtInfo) {
var tracesWithSelectedPts = [];
var searchInfo, trace, isSameTrace, i;
for (i = 0; i < searchTraces.length; i++) {
searchInfo = searchTraces[i];
if (searchInfo.cd[0].trace.selectedpoints && searchInfo.cd[0].trace.selectedpoints.length > 0) {
tracesWithSelectedPts.push(searchInfo);
}
}
if (tracesWithSelectedPts.length === 1) {
isSameTrace = tracesWithSelectedPts[0] === clickedPtInfo.searchInfo;
if (isSameTrace) {
trace = clickedPtInfo.searchInfo.cd[0].trace;
if (trace.selectedpoints.length === clickedPtInfo.pointNumbers.length) {
for (i = 0; i < clickedPtInfo.pointNumbers.length; i++) {
if (trace.selectedpoints.indexOf(clickedPtInfo.pointNumbers[i]) < 0) {
return false;
}
}
return true;
}
}
}
return false;
}
function isOnlyOnePointSelected(searchTraces) {
var len = 0;
var searchInfo, trace, i;
for (i = 0; i < searchTraces.length; i++) {
searchInfo = searchTraces[i];
trace = searchInfo.cd[0].trace;
if (trace.selectedpoints) {
if (trace.selectedpoints.length > 1) return false;
len += trace.selectedpoints.length;
if (len > 1) return false;
}
}
return len === 1;
}
function updateSelectedState(gd, searchTraces, eventData) {
var i;
// before anything else, update preGUI if necessary
for (i = 0; i < searchTraces.length; i++) {
var fullInputTrace = searchTraces[i].cd[0].trace._fullInput;
var tracePreGUI = gd._fullLayout._tracePreGUI[fullInputTrace.uid] || {};
if (tracePreGUI.selectedpoints === undefined) {
tracePreGUI.selectedpoints = fullInputTrace._input.selectedpoints || null;
}
}
var trace;
if (eventData) {
var pts = eventData.points || [];
for (i = 0; i < searchTraces.length; i++) {
trace = searchTraces[i].cd[0].trace;
trace._input.selectedpoints = trace._fullInput.selectedpoints = [];
if (trace._fullInput !== trace) trace.selectedpoints = [];
}
for (var k = 0; k < pts.length; k++) {
var pt = pts[k];
var data = pt.data;
var fullData = pt.fullData;
var pointIndex = pt.pointIndex;
var pointIndices = pt.pointIndices;
if (pointIndices) {
[].push.apply(data.selectedpoints, pointIndices);
if (trace._fullInput !== trace) {
[].push.apply(fullData.selectedpoints, pointIndices);
}
} else {
data.selectedpoints.push(pointIndex);
if (trace._fullInput !== trace) {
fullData.selectedpoints.push(pointIndex);
}
}
}
} else {
for (i = 0; i < searchTraces.length; i++) {
trace = searchTraces[i].cd[0].trace;
delete trace.selectedpoints;
delete trace._input.selectedpoints;
if (trace._fullInput !== trace) {
delete trace._fullInput.selectedpoints;
}
}
}
updateReglSelectedState(gd, searchTraces);
}
function updateReglSelectedState(gd, searchTraces) {
var hasRegl = false;
for (var i = 0; i < searchTraces.length; i++) {
var searchInfo = searchTraces[i];
var cd = searchInfo.cd;
if (Registry.traceIs(cd[0].trace, 'regl')) {
hasRegl = true;
}
var _module = searchInfo._module;
var fn = _module.styleOnSelect || _module.style;
if (fn) {
fn(gd, cd, cd[0].node3);
if (cd[0].nodeRangePlot3) fn(gd, cd, cd[0].nodeRangePlot3);
}
}
if (hasRegl) {
clearGlCanvases(gd);
redrawReglTraces(gd);
}
}
function mergePolygons(list, poly, subtract) {
var fn = subtract ? polybool.difference : polybool.union;
var res = fn({
regions: list
}, {
regions: [poly]
});
var allPolygons = res.regions.reverse();
for (var i = 0; i < allPolygons.length; i++) {
var polygon = allPolygons[i];
polygon.subtract = getSubtract(polygon, allPolygons.slice(0, i));
}
return allPolygons;
}
function fillSelectionItem(selection, searchInfo) {
if (Array.isArray(selection)) {
var cd = searchInfo.cd;
var trace = searchInfo.cd[0].trace;
for (var i = 0; i < selection.length; i++) {
selection[i] = makeEventData(selection[i], trace, cd);
}
}
return selection;
}
function convertPoly(polygonsIn, isOpenMode) {
// add M and L command to draft positions
var polygonsOut = [];
for (var i = 0; i < polygonsIn.length; i++) {
polygonsOut[i] = [];
for (var j = 0; j < polygonsIn[i].length; j++) {
polygonsOut[i][j] = [];
polygonsOut[i][j][0] = j ? 'L' : 'M';
for (var k = 0; k < polygonsIn[i][j].length; k++) {
polygonsOut[i][j].push(polygonsIn[i][j][k]);
}
}
if (!isOpenMode) {
polygonsOut[i].push(['Z', polygonsOut[i][0][1],
// initial x
polygonsOut[i][0][2] // initial y
]);
}
}
return polygonsOut;
}
function _doSelect(selectionTesters, searchTraces) {
var allSelections = [];
var thisSelection;
var traceSelections = [];
var traceSelection;
for (var i = 0; i < searchTraces.length; i++) {
var searchInfo = searchTraces[i];
traceSelection = searchInfo._module.selectPoints(searchInfo, selectionTesters);
traceSelections.push(traceSelection);
thisSelection = fillSelectionItem(traceSelection, searchInfo);
allSelections = allSelections.concat(thisSelection);
}
return allSelections;
}
function reselect(gd, mayEmitSelected, selectionTesters, searchTraces, dragOptions) {
var hadSearchTraces = !!searchTraces;
var plotinfo, xRef, yRef;
if (dragOptions) {
plotinfo = dragOptions.plotinfo;
xRef = dragOptions.xaxes[0]._id;
yRef = dragOptions.yaxes[0]._id;
}
var allSelections = [];
var allSearchTraces = [];
// select layout.selection polygons
var layoutPolygons = getLayoutPolygons(gd);
// add draft outline polygons to layoutPolygons
var fullLayout = gd._fullLayout;
if (plotinfo) {
var zoomLayer = fullLayout._zoomlayer;
var mode = fullLayout.dragmode;
var isDrawMode = drawMode(mode);
var isSelectMode = selectMode(mode);
if (isDrawMode || isSelectMode) {
var xaxis = getFromId(gd, xRef, 'x');
var yaxis = getFromId(gd, yRef, 'y');
if (xaxis && yaxis) {
var outlines = zoomLayer.selectAll('.select-outline-' + plotinfo.id);
if (outlines && gd._fullLayout._outlining) {
if (outlines.length) {
var e = outlines[0][0]; // pick first
var d = e.getAttribute('d');
var outlinePolys = readPaths(d, gd, plotinfo);
var draftPolygons = [];
for (var u = 0; u < outlinePolys.length; u++) {
var p = outlinePolys[u];
var polygon = [];
for (var t = 0; t < p.length; t++) {
polygon.push([convert(xaxis, p[t][1]), convert(yaxis, p[t][2])]);
}
polygon.xref = xRef;
polygon.yref = yRef;
polygon.subtract = getSubtract(polygon, draftPolygons);
draftPolygons.push(polygon);
}
layoutPolygons = layoutPolygons.concat(draftPolygons);
}
}
}
}
}
var subplots = xRef && yRef ? [xRef + yRef] : fullLayout._subplots.cartesian;
epmtySplomSelectionBatch(gd);
var seenSplom = {};
for (var i = 0; i < subplots.length; i++) {
var subplot = subplots[i];
var yAt = subplot.indexOf('y');
var _xRef = subplot.slice(0, yAt);
var _yRef = subplot.slice(yAt);
var _selectionTesters = xRef && yRef ? selectionTesters : undefined;
_selectionTesters = addTester(layoutPolygons, _xRef, _yRef, _selectionTesters);
if (_selectionTesters) {
var _searchTraces = searchTraces;
if (!hadSearchTraces) {
var _xA = getFromId(gd, _xRef, 'x');
var _yA = getFromId(gd, _yRef, 'y');
_searchTraces = determineSearchTraces(gd, [_xA], [_yA], subplot);
for (var w = 0; w < _searchTraces.length; w++) {
var s = _searchTraces[w];
var cd0 = s.cd[0];
var trace = cd0.trace;
if (s._module.name === 'scattergl' && !cd0.t.xpx) {
var x = trace.x;
var y = trace.y;
var len = trace._length;
// generate stash for scattergl
cd0.t.xpx = [];
cd0.t.ypx = [];
for (var j = 0; j < len; j++) {
cd0.t.xpx[j] = _xA.c2p(x[j]);
cd0.t.ypx[j] = _yA.c2p(y[j]);
}
}
if (s._module.name === 'splom') {
if (!seenSplom[trace.uid]) {
seenSplom[trace.uid] = true;
}
}
}
}
var selection = _doSelect(_selectionTesters, _searchTraces);
allSelections = allSelections.concat(selection);
allSearchTraces = allSearchTraces.concat(_searchTraces);
}
}
var eventData = {
points: allSelections
};
updateSelectedState(gd, allSearchTraces, eventData);
var clickmode = fullLayout.clickmode;
var sendEvents = clickmode.indexOf('event') > -1 && mayEmitSelected;
if (!plotinfo &&
// get called from plot_api & plots
mayEmitSelected) {
var activePolygons = getLayoutPolygons(gd, true);
if (activePolygons.length) {
var xref = activePolygons[0].xref;
var yref = activePolygons[0].yref;
if (xref && yref) {
var poly = castMultiPolygon(activePolygons);
var fillRangeItems = makeFillRangeItems([getFromId(gd, xref, 'x'), getFromId(gd, yref, 'y')]);
fillRangeItems(eventData, poly);
}
}
if (gd._fullLayout._noEmitSelectedAtStart) {
gd._fullLayout._noEmitSelectedAtStart = false;
} else {
if (sendEvents) emitSelected(gd, eventData);
}
fullLayout._reselect = false;
}
if (!plotinfo &&
// get called from plot_api & plots
fullLayout._deselect) {
var deselect = fullLayout._deselect;
xRef = deselect.xref;
yRef = deselect.yref;
if (!subplotSelected(xRef, yRef, allSearchTraces)) {
deselectSubplot(gd, xRef, yRef, searchTraces);
}
if (sendEvents) {
if (eventData.points.length) {
emitSelected(gd, eventData);
} else {
emitDeselect(gd);
}
}
fullLayout._deselect = false;
}
return {
eventData: eventData,
selectionTesters: selectionTesters
};
}
function epmtySplomSelectionBatch(gd) {
var cd = gd.calcdata;
if (!cd) return;
for (var i = 0; i < cd.length; i++) {
var cd0 = cd[i][0];
var trace = cd0.trace;
var splomScenes = gd._fullLayout._splomScenes;
if (splomScenes) {
var scene = splomScenes[trace.uid];
if (scene) {
scene.selectBatch = [];
}
}
}
}
function subplotSelected(xRef, yRef, searchTraces) {
for (var i = 0; i < searchTraces.length; i++) {
var s = searchTraces[i];
if (s.xaxis && s.xaxis._id === xRef && s.yaxis && s.yaxis._id === yRef) {
return true;
}
}
return false;
}
function deselectSubplot(gd, xRef, yRef, searchTraces) {
searchTraces = determineSearchTraces(gd, [getFromId(gd, xRef, 'x')], [getFromId(gd, yRef, 'y')], xRef + yRef);
for (var k = 0; k < searchTraces.length; k++) {
var searchInfo = searchTraces[k];
searchInfo._module.selectPoints(searchInfo, false);
}
updateSelectedState(gd, searchTraces);
}
function addTester(layoutPolygons, xRef, yRef, selectionTesters) {
var mergedPolygons;
for (var i = 0; i < layoutPolygons.length; i++) {
var currentPolygon = layoutPolygons[i];
if (xRef !== currentPolygon.xref || yRef !== currentPolygon.yref) continue;
if (mergedPolygons) {
var subtract = !!currentPolygon.subtract;
mergedPolygons = mergePolygons(mergedPolygons, currentPolygon, subtract);
selectionTesters = multiTester(mergedPolygons);
} else {
mergedPolygons = [currentPolygon];
selectionTesters = polygonTester(currentPolygon);
}
}
return selectionTesters;
}
function getLayoutPolygons(gd, onlyActiveOnes) {
var allPolygons = [];
var fullLayout = gd._fullLayout;
var allSelections = fullLayout.selections;
var len = allSelections.length;
for (var i = 0; i < len; i++) {
if (onlyActiveOnes && i !== fullLayout._activeSelectionIndex) continue;
var selection = allSelections[i];
if (!selection) continue;
var xref = selection.xref;
var yref = selection.yref;
var xaxis = getFromId(gd, xref, 'x');
var yaxis = getFromId(gd, yref, 'y');
var xmin, xmax, ymin, ymax;
var polygon;
if (selection.type === 'rect') {
polygon = [];
var x0 = convert(xaxis, selection.x0);
var x1 = convert(xaxis, selection.x1);
var y0 = convert(yaxis, selection.y0);
var y1 = convert(yaxis, selection.y1);
polygon = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
xmin = Math.min(x0, x1);
xmax = Math.max(x0, x1);
ymin = Math.min(y0, y1);
ymax = Math.max(y0, y1);
polygon.xmin = xmin;
polygon.xmax = xmax;
polygon.ymin = ymin;
polygon.ymax = ymax;
polygon.xref = xref;
polygon.yref = yref;
polygon.subtract = false;
polygon.isRect = true;
allPolygons.push(polygon);
} else if (selection.type === 'path') {
var segments = selection.path.split('Z');
var multiPolygons = [];
for (var j = 0; j < segments.length; j++) {
var path = segments[j];
if (!path) continue;
path += 'Z';
var allX = shapeHelpers.extractPathCoords(path, shapeConstants.paramIsX, 'raw');
var allY = shapeHelpers.extractPathCoords(path, shapeConstants.paramIsY, 'raw');
xmin = Infinity;
xmax = -Infinity;
ymin = Infinity;
ymax = -Infinity;
polygon = [];
for (var k = 0; k < allX.length; k++) {
var x = convert(xaxis, allX[k]);
var y = convert(yaxis, allY[k]);
polygon.push([x, y]);
xmin = Math.min(x, xmin);
xmax = Math.max(x, xmax);
ymin = Math.min(y, ymin);
ymax = Math.max(y, ymax);
}
polygon.xmin = xmin;
polygon.xmax = xmax;
polygon.ymin = ymin;
polygon.ymax = ymax;
polygon.xref = xref;
polygon.yref = yref;
polygon.subtract = getSubtract(polygon, multiPolygons);
multiPolygons.push(polygon);
allPolygons.push(polygon);
}
}
}
return allPolygons;
}
function getSubtract(polygon, previousPolygons) {
var subtract = false;
for (var i = 0; i < previousPolygons.length; i++) {
var previousPolygon = previousPolygons[i];
// find out if a point of polygon is inside previous polygons
for (var k = 0; k < polygon.length; k++) {
if (pointInPolygon(polygon[k], previousPolygon)) {
subtract = !subtract;
break;
}
}
}
return subtract;
}
function convert(ax, d) {
if (ax.type === 'date') d = d.replace('_', ' ');
return ax.type === 'log' ? ax.c2p(d) : ax.r2p(d, null, ax.calendar);
}
function castMultiPolygon(allPolygons) {
var len = allPolygons.length;
// descibe multi polygons in one polygon
var p = [];
for (var i = 0; i < len; i++) {
var polygon = allPolygons[i];
p = p.concat(polygon);
// add starting vertex to close
// which indicates next polygon
p = p.concat([polygon[0]]);
}
return computeRectAndRanges(p);
}
function computeRectAndRanges(poly) {
poly.isRect = poly.length === 5 && poly[0][0] === poly[4][0] && poly[0][1] === poly[4][1] && poly[0][0] === poly[1][0] && poly[2][0] === poly[3][0] && poly[0][1] === poly[3][1] && poly[1][1] === poly[2][1] || poly[0][1] === poly[1][1] && poly[2][1] === poly[3][1] && poly[0][0] === poly[3][0] && poly[1][0] === poly[2][0];
if (poly.isRect) {
poly.xmin = Math.min(poly[0][0], poly[2][0]);
poly.xmax = Math.max(poly[0][0], poly[2][0]);
poly.ymin = Math.min(poly[0][1], poly[2][1]);
poly.ymax = Math.max(poly[0][1], poly[2][1]);
}
return poly;
}
function makeFillRangeItems(allAxes) {
return function (eventData, poly) {
var range;
var lassoPoints;
for (var i = 0; i < allAxes.length; i++) {
var ax = allAxes[i];
var id = ax._id;
var axLetter = id.charAt(0);
if (poly.isRect) {
if (!range) range = {};
var min = poly[axLetter + 'min'];
var max = poly[axLetter + 'max'];
if (min !== undefined && max !== undefined) {
range[id] = [p2r(ax, min), p2r(ax, max)].sort(ascending);
}
} else {
if (!lassoPoints) lassoPoints = {};
lassoPoints[id] = poly.map(axValue(ax));
}
}
if (range) {
eventData.range = range;
}
if (lassoPoints) {
eventData.lassoPoints = lassoPoints;
}
};
}
function getFillRangeItems(dragOptions) {
var plotinfo = dragOptions.plotinfo;
return plotinfo.fillRangeItems ||
// allow subplots (i.e. geo, mapbox, sankey) to override fillRangeItems routine
makeFillRangeItems(dragOptions.xaxes.concat(dragOptions.yaxes));
}
function emitSelecting(gd, eventData) {
gd.emit('plotly_selecting', eventData);
}
function emitSelected(gd, eventData) {
if (eventData) {
eventData.selections = (gd.layout || {}).selections || [];
}
gd.emit('plotly_selected', eventData);
}
function emitDeselect(gd) {
gd.emit('plotly_deselect', null);
}
module.exports = {
reselect: reselect,
prepSelect: prepSelect,
clearOutline: clearOutline,
clearSelectionsCache: clearSelectionsCache,
selectOnClick: selectOnClick
};
/***/ }),
/***/ 46056:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var annAttrs = __webpack_require__(13916);
var fontAttrs = __webpack_require__(25376);
var scatterLineAttrs = (__webpack_require__(52904).line);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
var templatedArray = (__webpack_require__(31780).templatedArray);
var axisPlaceableObjs = __webpack_require__(36208);
var basePlotAttributes = __webpack_require__(45464);
var shapeTexttemplateAttrs = (__webpack_require__(21776)/* .shapeTexttemplateAttrs */ .ye);
var shapeLabelTexttemplateVars = __webpack_require__(97728);
module.exports = templatedArray('shape', {
visible: extendFlat({}, basePlotAttributes.visible, {
editType: 'calc+arraydraw'
}),
showlegend: {
valType: 'boolean',
dflt: false,
editType: 'calc+arraydraw'
},
legend: extendFlat({}, basePlotAttributes.legend, {
editType: 'calc+arraydraw'
}),
legendgroup: extendFlat({}, basePlotAttributes.legendgroup, {
editType: 'calc+arraydraw'
}),
legendgrouptitle: {
text: extendFlat({}, basePlotAttributes.legendgrouptitle.text, {
editType: 'calc+arraydraw'
}),
font: fontAttrs({
editType: 'calc+arraydraw'
}),
editType: 'calc+arraydraw'
},
legendrank: extendFlat({}, basePlotAttributes.legendrank, {
editType: 'calc+arraydraw'
}),
legendwidth: extendFlat({}, basePlotAttributes.legendwidth, {
editType: 'calc+arraydraw'
}),
type: {
valType: 'enumerated',
values: ['circle', 'rect', 'path', 'line'],
editType: 'calc+arraydraw'
},
layer: {
valType: 'enumerated',
values: ['below', 'above', 'between'],
dflt: 'above',
editType: 'arraydraw'
},
xref: extendFlat({}, annAttrs.xref, {}),
xsizemode: {
valType: 'enumerated',
values: ['scaled', 'pixel'],
dflt: 'scaled',
editType: 'calc+arraydraw'
},
xanchor: {
valType: 'any',
editType: 'calc+arraydraw'
},
x0: {
valType: 'any',
editType: 'calc+arraydraw'
},
x1: {
valType: 'any',
editType: 'calc+arraydraw'
},
x0shift: {
valType: 'number',
dflt: 0,
min: -1,
max: 1,
editType: 'calc'
},
x1shift: {
valType: 'number',
dflt: 0,
min: -1,
max: 1,
editType: 'calc'
},
yref: extendFlat({}, annAttrs.yref, {}),
ysizemode: {
valType: 'enumerated',
values: ['scaled', 'pixel'],
dflt: 'scaled',
editType: 'calc+arraydraw'
},
yanchor: {
valType: 'any',
editType: 'calc+arraydraw'
},
y0: {
valType: 'any',
editType: 'calc+arraydraw'
},
y1: {
valType: 'any',
editType: 'calc+arraydraw'
},
y0shift: {
valType: 'number',
dflt: 0,
min: -1,
max: 1,
editType: 'calc'
},
y1shift: {
valType: 'number',
dflt: 0,
min: -1,
max: 1,
editType: 'calc'
},
path: {
valType: 'string',
editType: 'calc+arraydraw'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1,
editType: 'arraydraw'
},
line: {
color: extendFlat({}, scatterLineAttrs.color, {
editType: 'arraydraw'
}),
width: extendFlat({}, scatterLineAttrs.width, {
editType: 'calc+arraydraw'
}),
dash: extendFlat({}, dash, {
editType: 'arraydraw'
}),
editType: 'calc+arraydraw'
},
fillcolor: {
valType: 'color',
dflt: 'rgba(0,0,0,0)',
editType: 'arraydraw'
},
fillrule: {
valType: 'enumerated',
values: ['evenodd', 'nonzero'],
dflt: 'evenodd',
editType: 'arraydraw'
},
editable: {
valType: 'boolean',
dflt: false,
editType: 'calc+arraydraw'
},
label: {
text: {
valType: 'string',
dflt: '',
editType: 'arraydraw'
},
texttemplate: shapeTexttemplateAttrs({}, {
keys: Object.keys(shapeLabelTexttemplateVars)
}),
font: fontAttrs({
editType: 'calc+arraydraw',
colorEditType: 'arraydraw'
}),
textposition: {
valType: 'enumerated',
values: ['top left', 'top center', 'top right', 'middle left', 'middle center', 'middle right', 'bottom left', 'bottom center', 'bottom right', 'start', 'middle', 'end'],
editType: 'arraydraw'
},
textangle: {
valType: 'angle',
dflt: 'auto',
editType: 'calc+arraydraw'
},
xanchor: {
valType: 'enumerated',
values: ['auto', 'left', 'center', 'right'],
dflt: 'auto',
editType: 'calc+arraydraw'
},
yanchor: {
valType: 'enumerated',
values: ['top', 'middle', 'bottom'],
editType: 'calc+arraydraw'
},
padding: {
valType: 'number',
dflt: 3,
min: 0,
editType: 'arraydraw'
},
editType: 'arraydraw'
},
editType: 'arraydraw'
});
/***/ }),
/***/ 96084:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var constants = __webpack_require__(85448);
var helpers = __webpack_require__(65152);
module.exports = function calcAutorange(gd) {
var fullLayout = gd._fullLayout;
var shapeList = Lib.filterVisible(fullLayout.shapes);
if (!shapeList.length || !gd._fullData.length) return;
for (var i = 0; i < shapeList.length; i++) {
var shape = shapeList[i];
shape._extremes = {};
var ax;
var bounds;
var xRefType = Axes.getRefType(shape.xref);
var yRefType = Axes.getRefType(shape.yref);
// paper and axis domain referenced shapes don't affect autorange
if (shape.xref !== 'paper' && xRefType !== 'domain') {
ax = Axes.getFromId(gd, shape.xref);
bounds = shapeBounds(ax, shape, constants.paramIsX);
if (bounds) {
shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcXPaddingOptions(shape));
}
}
if (shape.yref !== 'paper' && yRefType !== 'domain') {
ax = Axes.getFromId(gd, shape.yref);
bounds = shapeBounds(ax, shape, constants.paramIsY);
if (bounds) {
shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcYPaddingOptions(shape));
}
}
}
};
function calcXPaddingOptions(shape) {
return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false);
}
function calcYPaddingOptions(shape) {
return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true);
}
function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) {
var ppad = lineWidth / 2;
var axisDirectionReverted = isYAxis;
if (sizeMode === 'pixel') {
var coords = path ? helpers.extractPathCoords(path, isYAxis ? constants.paramIsY : constants.paramIsX) : [v0, v1];
var maxValue = Lib.aggNums(Math.max, null, coords);
var minValue = Lib.aggNums(Math.min, null, coords);
var beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad;
var afterPad = maxValue > 0 ? maxValue + ppad : ppad;
return {
ppad: ppad,
ppadplus: axisDirectionReverted ? beforePad : afterPad,
ppadminus: axisDirectionReverted ? afterPad : beforePad
};
} else {
return {
ppad: ppad
};
}
}
function shapeBounds(ax, shape, paramsToUse) {
var dim = ax._id.charAt(0) === 'x' ? 'x' : 'y';
var isCategory = ax.type === 'category' || ax.type === 'multicategory';
var v0;
var v1;
var shiftStart = 0;
var shiftEnd = 0;
var convertVal = isCategory ? ax.r2c : ax.d2c;
var isSizeModeScale = shape[dim + 'sizemode'] === 'scaled';
if (isSizeModeScale) {
v0 = shape[dim + '0'];
v1 = shape[dim + '1'];
if (isCategory) {
shiftStart = shape[dim + '0shift'];
shiftEnd = shape[dim + '1shift'];
}
} else {
v0 = shape[dim + 'anchor'];
v1 = shape[dim + 'anchor'];
}
if (v0 !== undefined) return [convertVal(v0) + shiftStart, convertVal(v1) + shiftEnd];
if (!shape.path) return;
var min = Infinity;
var max = -Infinity;
var segments = shape.path.match(constants.segmentRE);
var i;
var segment;
var drawnParam;
var params;
var val;
if (ax.type === 'date') convertVal = helpers.decodeDate(convertVal);
for (i = 0; i < segments.length; i++) {
segment = segments[i];
drawnParam = paramsToUse[segment.charAt(0)].drawn;
if (drawnParam === undefined) continue;
params = segments[i].substr(1).match(constants.paramRE);
if (!params || params.length < drawnParam) continue;
val = convertVal(params[drawnParam]);
if (val < min) min = val;
if (val > max) max = val;
}
if (max >= min) return [min, max];
}
/***/ }),
/***/ 85448:
/***/ (function(module) {
"use strict";
module.exports = {
segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g,
paramRE: /[^\s,]+/g,
// which numbers in each path segment are x (or y) values
// drawn is which param is a drawn point, as opposed to a
// control point (which doesn't count toward autorange.
// TODO: this means curved paths could extend beyond the
// autorange bounds. This is a bit tricky to get right
// unless we revert to bounding boxes, but perhaps there's
// a calculation we could do...)
paramIsX: {
M: {
0: true,
drawn: 0
},
L: {
0: true,
drawn: 0
},
H: {
0: true,
drawn: 0
},
V: {},
Q: {
0: true,
2: true,
drawn: 2
},
C: {
0: true,
2: true,
4: true,
drawn: 4
},
T: {
0: true,
drawn: 0
},
S: {
0: true,
2: true,
drawn: 2
},
// A: {0: true, 5: true},
Z: {}
},
paramIsY: {
M: {
1: true,
drawn: 1
},
L: {
1: true,
drawn: 1
},
H: {},
V: {
0: true,
drawn: 0
},
Q: {
1: true,
3: true,
drawn: 3
},
C: {
1: true,
3: true,
5: true,
drawn: 5
},
T: {
1: true,
drawn: 1
},
S: {
1: true,
3: true,
drawn: 5
},
// A: {1: true, 6: true},
Z: {}
},
numParams: {
M: 2,
L: 2,
H: 1,
V: 1,
Q: 4,
C: 6,
T: 2,
S: 4,
// A: 7,
Z: 0
}
};
/***/ }),
/***/ 43712:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var handleArrayContainerDefaults = __webpack_require__(51272);
var attributes = __webpack_require__(46056);
var helpers = __webpack_require__(65152);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
handleArrayContainerDefaults(layoutIn, layoutOut, {
name: 'shapes',
handleItemDefaults: handleShapeDefaults
});
};
function dfltLabelYanchor(isLine, labelTextPosition) {
// If shape is a line, default y-anchor is 'bottom' (so that text is above line by default)
// Otherwise, default y-anchor is equal to y-component of `textposition`
// (so that text is positioned inside shape bounding box by default)
return isLine ? 'bottom' : labelTextPosition.indexOf('top') !== -1 ? 'top' : labelTextPosition.indexOf('bottom') !== -1 ? 'bottom' : 'middle';
}
function handleShapeDefaults(shapeIn, shapeOut, fullLayout) {
function coerce(attr, dflt) {
return Lib.coerce(shapeIn, shapeOut, attributes, attr, dflt);
}
shapeOut._isShape = true;
var visible = coerce('visible');
if (!visible) return;
var showlegend = coerce('showlegend');
if (showlegend) {
coerce('legend');
coerce('legendwidth');
coerce('legendgroup');
coerce('legendgrouptitle.text');
Lib.coerceFont(coerce, 'legendgrouptitle.font');
coerce('legendrank');
}
var path = coerce('path');
var dfltType = path ? 'path' : 'rect';
var shapeType = coerce('type', dfltType);
var noPath = shapeType !== 'path';
if (noPath) delete shapeOut.path;
coerce('editable');
coerce('layer');
coerce('opacity');
coerce('fillcolor');
coerce('fillrule');
var lineWidth = coerce('line.width');
if (lineWidth) {
coerce('line.color');
coerce('line.dash');
}
var xSizeMode = coerce('xsizemode');
var ySizeMode = coerce('ysizemode');
// positioning
var axLetters = ['x', 'y'];
for (var i = 0; i < 2; i++) {
var axLetter = axLetters[i];
var attrAnchor = axLetter + 'anchor';
var sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode;
var gdMock = {
_fullLayout: fullLayout
};
var ax;
var pos2r;
var r2pos;
// xref, yref
var axRef = Axes.coerceRef(shapeIn, shapeOut, gdMock, axLetter, undefined, 'paper');
var axRefType = Axes.getRefType(axRef);
if (axRefType === 'range') {
ax = Axes.getFromId(gdMock, axRef);
ax._shapeIndices.push(shapeOut._index);
r2pos = helpers.rangeToShapePosition(ax);
pos2r = helpers.shapePositionToRange(ax);
if (ax.type === 'category' || ax.type === 'multicategory') {
coerce(axLetter + '0shift');
coerce(axLetter + '1shift');
}
} else {
pos2r = r2pos = Lib.identity;
}
// Coerce x0, x1, y0, y1
if (noPath) {
var dflt0 = 0.25;
var dflt1 = 0.75;
// hack until V3.0 when log has regular range behavior - make it look like other
// ranges to send to coerce, then put it back after
// this is all to give reasonable default position behavior on log axes, which is
// a pretty unimportant edge case so we could just ignore this.
var attr0 = axLetter + '0';
var attr1 = axLetter + '1';
var in0 = shapeIn[attr0];
var in1 = shapeIn[attr1];
shapeIn[attr0] = pos2r(shapeIn[attr0], true);
shapeIn[attr1] = pos2r(shapeIn[attr1], true);
if (sizeMode === 'pixel') {
coerce(attr0, 0);
coerce(attr1, 10);
} else {
Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0);
Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1);
}
// hack part 2
shapeOut[attr0] = r2pos(shapeOut[attr0]);
shapeOut[attr1] = r2pos(shapeOut[attr1]);
shapeIn[attr0] = in0;
shapeIn[attr1] = in1;
}
// Coerce xanchor and yanchor
if (sizeMode === 'pixel') {
// Hack for log axis described above
var inAnchor = shapeIn[attrAnchor];
shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true);
Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25);
// Hack part 2
shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]);
shapeIn[attrAnchor] = inAnchor;
}
}
if (noPath) {
Lib.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']);
}
// Label options
var isLine = shapeType === 'line';
var labelTextTemplate, labelText;
if (noPath) {
labelTextTemplate = coerce('label.texttemplate');
}
if (!labelTextTemplate) {
labelText = coerce('label.text');
}
if (labelText || labelTextTemplate) {
coerce('label.textangle');
var labelTextPosition = coerce('label.textposition', isLine ? 'middle' : 'middle center');
coerce('label.xanchor');
coerce('label.yanchor', dfltLabelYanchor(isLine, labelTextPosition));
coerce('label.padding');
Lib.coerceFont(coerce, 'label.font', fullLayout.font);
}
}
/***/ }),
/***/ 60728:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var svgTextUtils = __webpack_require__(72736);
var Drawing = __webpack_require__(43616);
var readPaths = (__webpack_require__(9856).readPaths);
var helpers = __webpack_require__(65152);
var getPathString = helpers.getPathString;
var shapeLabelTexttemplateVars = __webpack_require__(97728);
var FROM_TL = (__webpack_require__(84284).FROM_TL);
module.exports = function drawLabel(gd, index, options, shapeGroup) {
// Remove existing label
shapeGroup.selectAll('.shape-label').remove();
// If no label text or texttemplate, return
if (!(options.label.text || options.label.texttemplate)) return;
// Text template overrides text
var text;
if (options.label.texttemplate) {
var templateValues = {};
if (options.type !== 'path') {
var _xa = Axes.getFromId(gd, options.xref);
var _ya = Axes.getFromId(gd, options.yref);
for (var key in shapeLabelTexttemplateVars) {
var val = shapeLabelTexttemplateVars[key](options, _xa, _ya);
if (val !== undefined) templateValues[key] = val;
}
}
text = Lib.texttemplateStringForShapes(options.label.texttemplate, {}, gd._fullLayout._d3locale, templateValues);
} else {
text = options.label.text;
}
var labelGroupAttrs = {
'data-index': index
};
var font = options.label.font;
var labelTextAttrs = {
'data-notex': 1
};
var labelGroup = shapeGroup.append('g').attr(labelGroupAttrs).classed('shape-label', true);
var labelText = labelGroup.append('text').attr(labelTextAttrs).classed('shape-label-text', true).text(text);
// Get x and y bounds of shape
var shapex0, shapex1, shapey0, shapey1;
if (options.path) {
// If shape is defined as a path, get the
// min and max bounds across all polygons in path
var d = getPathString(gd, options);
var polygons = readPaths(d, gd);
shapex0 = Infinity;
shapey0 = Infinity;
shapex1 = -Infinity;
shapey1 = -Infinity;
for (var i = 0; i < polygons.length; i++) {
for (var j = 0; j < polygons[i].length; j++) {
var p = polygons[i][j];
for (var k = 1; k < p.length; k += 2) {
var _x = p[k];
var _y = p[k + 1];
shapex0 = Math.min(shapex0, _x);
shapex1 = Math.max(shapex1, _x);
shapey0 = Math.min(shapey0, _y);
shapey1 = Math.max(shapey1, _y);
}
}
}
} else {
// Otherwise, we use the x and y bounds defined in the shape options
// and convert them to pixel coordinates
// Setup conversion functions
var xa = Axes.getFromId(gd, options.xref);
var xShiftStart = options.x0shift;
var xShiftEnd = options.x1shift;
var xRefType = Axes.getRefType(options.xref);
var ya = Axes.getFromId(gd, options.yref);
var yShiftStart = options.y0shift;
var yShiftEnd = options.y1shift;
var yRefType = Axes.getRefType(options.yref);
var x2p = function (v, shift) {
var dataToPixel = helpers.getDataToPixel(gd, xa, shift, false, xRefType);
return dataToPixel(v);
};
var y2p = function (v, shift) {
var dataToPixel = helpers.getDataToPixel(gd, ya, shift, true, yRefType);
return dataToPixel(v);
};
shapex0 = x2p(options.x0, xShiftStart);
shapex1 = x2p(options.x1, xShiftEnd);
shapey0 = y2p(options.y0, yShiftStart);
shapey1 = y2p(options.y1, yShiftEnd);
}
// Handle `auto` angle
var textangle = options.label.textangle;
if (textangle === 'auto') {
if (options.type === 'line') {
// Auto angle for line is same angle as line
textangle = calcTextAngle(shapex0, shapey0, shapex1, shapey1);
} else {
// Auto angle for all other shapes is 0
textangle = 0;
}
}
// Do an initial render so we can get the text bounding box height
labelText.call(function (s) {
s.call(Drawing.font, font).attr({});
svgTextUtils.convertToTspans(s, gd);
return s;
});
var textBB = Drawing.bBox(labelText.node());
// Calculate correct (x,y) for text
// We also determine true xanchor since xanchor depends on position when set to 'auto'
var textPos = calcTextPosition(shapex0, shapey0, shapex1, shapey1, options, textangle, textBB);
var textx = textPos.textx;
var texty = textPos.texty;
var xanchor = textPos.xanchor;
// Update (x,y) position, xanchor, and angle
labelText.attr({
'text-anchor': {
left: 'start',
center: 'middle',
right: 'end'
}[xanchor],
y: texty,
x: textx,
transform: 'rotate(' + textangle + ',' + textx + ',' + texty + ')'
}).call(svgTextUtils.positionText, textx, texty);
};
function calcTextAngle(shapex0, shapey0, shapex1, shapey1) {
var dy, dx;
dx = Math.abs(shapex1 - shapex0);
if (shapex1 >= shapex0) {
dy = shapey0 - shapey1;
} else {
dy = shapey1 - shapey0;
}
return -180 / Math.PI * Math.atan2(dy, dx);
}
function calcTextPosition(shapex0, shapey0, shapex1, shapey1, shapeOptions, actualTextAngle, textBB) {
var textPosition = shapeOptions.label.textposition;
var textAngle = shapeOptions.label.textangle;
var textPadding = shapeOptions.label.padding;
var shapeType = shapeOptions.type;
var textAngleRad = Math.PI / 180 * actualTextAngle;
var sinA = Math.sin(textAngleRad);
var cosA = Math.cos(textAngleRad);
var xanchor = shapeOptions.label.xanchor;
var yanchor = shapeOptions.label.yanchor;
var textx, texty, paddingX, paddingY;
// Text position functions differently for lines vs. other shapes
if (shapeType === 'line') {
// Set base position for start vs. center vs. end of line (default is 'center')
if (textPosition === 'start') {
textx = shapex0;
texty = shapey0;
} else if (textPosition === 'end') {
textx = shapex1;
texty = shapey1;
} else {
// Default: center
textx = (shapex0 + shapex1) / 2;
texty = (shapey0 + shapey1) / 2;
}
// Set xanchor if xanchor is 'auto'
if (xanchor === 'auto') {
if (textPosition === 'start') {
if (textAngle === 'auto') {
if (shapex1 > shapex0) xanchor = 'left';else if (shapex1 < shapex0) xanchor = 'right';else xanchor = 'center';
} else {
if (shapex1 > shapex0) xanchor = 'right';else if (shapex1 < shapex0) xanchor = 'left';else xanchor = 'center';
}
} else if (textPosition === 'end') {
if (textAngle === 'auto') {
if (shapex1 > shapex0) xanchor = 'right';else if (shapex1 < shapex0) xanchor = 'left';else xanchor = 'center';
} else {
if (shapex1 > shapex0) xanchor = 'left';else if (shapex1 < shapex0) xanchor = 'right';else xanchor = 'center';
}
} else {
xanchor = 'center';
}
}
// Special case for padding when angle is 'auto' for lines
// Padding should be treated as an orthogonal offset in this case
// Otherwise, padding is just a simple x and y offset
var paddingConstantsX = {
left: 1,
center: 0,
right: -1
};
var paddingConstantsY = {
bottom: -1,
middle: 0,
top: 1
};
if (textAngle === 'auto') {
// Set direction to apply padding (based on `yanchor` only)
var paddingDirection = paddingConstantsY[yanchor];
paddingX = -textPadding * sinA * paddingDirection;
paddingY = textPadding * cosA * paddingDirection;
} else {
// Set direction to apply padding (based on `xanchor` and `yanchor`)
var paddingDirectionX = paddingConstantsX[xanchor];
var paddingDirectionY = paddingConstantsY[yanchor];
paddingX = textPadding * paddingDirectionX;
paddingY = textPadding * paddingDirectionY;
}
textx = textx + paddingX;
texty = texty + paddingY;
} else {
// Text position for shapes that are not lines
// calc horizontal position
// Horizontal needs a little extra padding to look balanced
paddingX = textPadding + 3;
if (textPosition.indexOf('right') !== -1) {
textx = Math.max(shapex0, shapex1) - paddingX;
if (xanchor === 'auto') xanchor = 'right';
} else if (textPosition.indexOf('left') !== -1) {
textx = Math.min(shapex0, shapex1) + paddingX;
if (xanchor === 'auto') xanchor = 'left';
} else {
// Default: center
textx = (shapex0 + shapex1) / 2;
if (xanchor === 'auto') xanchor = 'center';
}
// calc vertical position
if (textPosition.indexOf('top') !== -1) {
texty = Math.min(shapey0, shapey1);
} else if (textPosition.indexOf('bottom') !== -1) {
texty = Math.max(shapey0, shapey1);
} else {
texty = (shapey0 + shapey1) / 2;
}
// Apply padding
paddingY = textPadding;
if (yanchor === 'bottom') {
texty = texty - paddingY;
} else if (yanchor === 'top') {
texty = texty + paddingY;
}
}
// Shift vertical (& horizontal) position according to `yanchor`
var shiftFraction = FROM_TL[yanchor];
// Adjust so that text is anchored at top of first line rather than at baseline of first line
var baselineAdjust = shapeOptions.label.font.size;
var textHeight = textBB.height;
var xshift = (textHeight * shiftFraction - baselineAdjust) * sinA;
var yshift = -(textHeight * shiftFraction - baselineAdjust) * cosA;
return {
textx: textx + xshift,
texty: texty + yshift,
xanchor: xanchor
};
}
/***/ }),
/***/ 55496:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var dragElement = __webpack_require__(86476);
var dragHelpers = __webpack_require__(72760);
var drawMode = dragHelpers.drawMode;
var selectMode = dragHelpers.selectMode;
var Registry = __webpack_require__(24040);
var Color = __webpack_require__(76308);
var constants = __webpack_require__(7000);
var i000 = constants.i000;
var i090 = constants.i090;
var i180 = constants.i180;
var i270 = constants.i270;
var handleOutline = __webpack_require__(1936);
var clearOutlineControllers = handleOutline.clearOutlineControllers;
var helpers = __webpack_require__(9856);
var pointsOnRectangle = helpers.pointsOnRectangle;
var pointsOnEllipse = helpers.pointsOnEllipse;
var writePaths = helpers.writePaths;
var newShapes = (__webpack_require__(93940).newShapes);
var createShapeObj = (__webpack_require__(93940).createShapeObj);
var newSelections = __webpack_require__(5968);
var drawLabel = __webpack_require__(60728);
module.exports = function displayOutlines(polygons, outlines, dragOptions, nCalls) {
if (!nCalls) nCalls = 0;
var gd = dragOptions.gd;
function redraw() {
// recursive call
displayOutlines(polygons, outlines, dragOptions, nCalls++);
if (pointsOnEllipse(polygons[0]) || dragOptions.hasText) {
update({
redrawing: true
});
}
}
function update(opts) {
var updateObject = {};
if (dragOptions.isActiveShape !== undefined) {
dragOptions.isActiveShape = false; // i.e. to disable shape controllers
updateObject = newShapes(outlines, dragOptions);
}
if (dragOptions.isActiveSelection !== undefined) {
dragOptions.isActiveSelection = false; // i.e. to disable selection controllers
updateObject = newSelections(outlines, dragOptions);
gd._fullLayout._reselect = true;
}
if (Object.keys(updateObject).length) {
Registry.call((opts || {}).redrawing ? 'relayout' : '_guiRelayout', gd, updateObject);
}
}
var fullLayout = gd._fullLayout;
var zoomLayer = fullLayout._zoomlayer;
var dragmode = dragOptions.dragmode;
var isDrawMode = drawMode(dragmode);
var isSelectMode = selectMode(dragmode);
if (isDrawMode || isSelectMode) {
gd._fullLayout._outlining = true;
}
clearOutlineControllers(gd);
// make outline
outlines.attr('d', writePaths(polygons));
// add controllers
var vertexDragOptions;
var groupDragOptions;
var indexI; // cell index
var indexJ; // vertex or cell-controller index
var copyPolygons;
if (!nCalls && (dragOptions.isActiveShape || dragOptions.isActiveSelection)) {
copyPolygons = recordPositions([], polygons);
var g = zoomLayer.append('g').attr('class', 'outline-controllers');
addVertexControllers(g);
addGroupControllers();
}
// draw label
if (isDrawMode && dragOptions.hasText) {
var shapeGroup = zoomLayer.select('.label-temp');
var shapeOptions = createShapeObj(outlines, dragOptions, dragOptions.dragmode);
drawLabel(gd, 'label-temp', shapeOptions, shapeGroup);
}
function startDragVertex(evt) {
indexI = +evt.srcElement.getAttribute('data-i');
indexJ = +evt.srcElement.getAttribute('data-j');
vertexDragOptions[indexI][indexJ].moveFn = moveVertexController;
}
function moveVertexController(dx, dy) {
if (!polygons.length) return;
var x0 = copyPolygons[indexI][indexJ][1];
var y0 = copyPolygons[indexI][indexJ][2];
var cell = polygons[indexI];
var len = cell.length;
if (pointsOnRectangle(cell)) {
var _dx = dx;
var _dy = dy;
if (dragOptions.isActiveSelection) {
// handle an edge contoller for rect selections
var nextPoint = getNextPoint(cell, indexJ);
if (nextPoint[1] === cell[indexJ][1]) {
// a vertical edge
_dy = 0;
} else {
// a horizontal edge
_dx = 0;
}
}
for (var q = 0; q < len; q++) {
if (q === indexJ) continue;
// move other corners of rectangle
var pos = cell[q];
if (pos[1] === cell[indexJ][1]) {
pos[1] = x0 + _dx;
}
if (pos[2] === cell[indexJ][2]) {
pos[2] = y0 + _dy;
}
}
// move the corner
cell[indexJ][1] = x0 + _dx;
cell[indexJ][2] = y0 + _dy;
if (!pointsOnRectangle(cell)) {
// reject result to rectangles with ensure areas
for (var j = 0; j < len; j++) {
for (var k = 0; k < cell[j].length; k++) {
cell[j][k] = copyPolygons[indexI][j][k];
}
}
}
} else {
// other polylines
cell[indexJ][1] = x0 + dx;
cell[indexJ][2] = y0 + dy;
}
redraw();
}
function endDragVertexController() {
update();
}
function removeVertex() {
if (!polygons.length) return;
if (!polygons[indexI]) return;
if (!polygons[indexI].length) return;
var newPolygon = [];
for (var j = 0; j < polygons[indexI].length; j++) {
if (j !== indexJ) {
newPolygon.push(polygons[indexI][j]);
}
}
if (newPolygon.length > 1 && !(newPolygon.length === 2 && newPolygon[1][0] === 'Z')) {
if (indexJ === 0) {
newPolygon[0][0] = 'M';
}
polygons[indexI] = newPolygon;
redraw();
update();
}
}
function clickVertexController(numClicks, evt) {
if (numClicks === 2) {
indexI = +evt.srcElement.getAttribute('data-i');
indexJ = +evt.srcElement.getAttribute('data-j');
var cell = polygons[indexI];
if (!pointsOnRectangle(cell) && !pointsOnEllipse(cell)) {
removeVertex();
}
}
}
function addVertexControllers(g) {
vertexDragOptions = [];
for (var i = 0; i < polygons.length; i++) {
var cell = polygons[i];
var onRect = pointsOnRectangle(cell);
var onEllipse = !onRect && pointsOnEllipse(cell);
vertexDragOptions[i] = [];
var len = cell.length;
for (var j = 0; j < len; j++) {
if (cell[j][0] === 'Z') continue;
if (onEllipse && j !== i000 && j !== i090 && j !== i180 && j !== i270) {
continue;
}
var rectSelection = onRect && dragOptions.isActiveSelection;
var nextPoint;
if (rectSelection) nextPoint = getNextPoint(cell, j);
var x = cell[j][1];
var y = cell[j][2];
var vertex = g.append(rectSelection ? 'rect' : 'circle').attr('data-i', i).attr('data-j', j).style({
fill: Color.background,
stroke: Color.defaultLine,
'stroke-width': 1,
'shape-rendering': 'crispEdges'
});
if (rectSelection) {
// convert a vertex controller to an edge controller for rect selections
var dx = nextPoint[1] - x;
var dy = nextPoint[2] - y;
var width = dy ? 5 : Math.max(Math.min(25, Math.abs(dx) - 5), 5);
var height = dx ? 5 : Math.max(Math.min(25, Math.abs(dy) - 5), 5);
vertex.classed(dy ? 'cursor-ew-resize' : 'cursor-ns-resize', true).attr('width', width).attr('height', height).attr('x', x - width / 2).attr('y', y - height / 2).attr('transform', strTranslate(dx / 2, dy / 2));
} else {
vertex.classed('cursor-grab', true).attr('r', 5).attr('cx', x).attr('cy', y);
}
vertexDragOptions[i][j] = {
element: vertex.node(),
gd: gd,
prepFn: startDragVertex,
doneFn: endDragVertexController,
clickFn: clickVertexController
};
dragElement.init(vertexDragOptions[i][j]);
}
}
}
function moveGroup(dx, dy) {
if (!polygons.length) return;
for (var i = 0; i < polygons.length; i++) {
for (var j = 0; j < polygons[i].length; j++) {
for (var k = 0; k + 2 < polygons[i][j].length; k += 2) {
polygons[i][j][k + 1] = copyPolygons[i][j][k + 1] + dx;
polygons[i][j][k + 2] = copyPolygons[i][j][k + 2] + dy;
}
}
}
}
function moveGroupController(dx, dy) {
moveGroup(dx, dy);
redraw();
}
function startDragGroupController(evt) {
indexI = +evt.srcElement.getAttribute('data-i');
if (!indexI) indexI = 0; // ensure non-existing move button get zero index
groupDragOptions[indexI].moveFn = moveGroupController;
}
function endDragGroupController() {
update();
}
function clickGroupController(numClicks) {
if (numClicks === 2) {
eraseActiveSelection(gd);
}
}
function addGroupControllers() {
groupDragOptions = [];
if (!polygons.length) return;
var i = 0;
groupDragOptions[i] = {
element: outlines[0][0],
gd: gd,
prepFn: startDragGroupController,
doneFn: endDragGroupController,
clickFn: clickGroupController
};
dragElement.init(groupDragOptions[i]);
}
};
function recordPositions(polygonsOut, polygonsIn) {
for (var i = 0; i < polygonsIn.length; i++) {
var cell = polygonsIn[i];
polygonsOut[i] = [];
for (var j = 0; j < cell.length; j++) {
polygonsOut[i][j] = [];
for (var k = 0; k < cell[j].length; k++) {
polygonsOut[i][j][k] = cell[j][k];
}
}
}
return polygonsOut;
}
function getNextPoint(cell, j) {
var x = cell[j][1];
var y = cell[j][2];
var len = cell.length;
var nextJ, nextX, nextY;
nextJ = (j + 1) % len;
nextX = cell[nextJ][1];
nextY = cell[nextJ][2];
// avoid potential double points (closing points)
if (nextX === x && nextY === y) {
nextJ = (j + 2) % len;
nextX = cell[nextJ][1];
nextY = cell[nextJ][2];
}
return [nextJ, nextX, nextY];
}
function eraseActiveSelection(gd) {
// Do not allow removal of selections on other dragmodes.
// This ensures the user could still double click to
// deselect all trace.selectedpoints,
// if that's what they wanted.
// Also double click to zoom back won't result in
// any surprising selection removal.
if (!selectMode(gd._fullLayout.dragmode)) return;
clearOutlineControllers(gd);
var id = gd._fullLayout._activeSelectionIndex;
var selections = (gd.layout || {}).selections || [];
if (id < selections.length) {
var list = [];
for (var q = 0; q < selections.length; q++) {
if (q !== id) {
list.push(selections[q]);
}
}
delete gd._fullLayout._activeSelectionIndex;
var erasedSelection = gd._fullLayout.selections[id];
gd._fullLayout._deselect = {
xref: erasedSelection.xref,
yref: erasedSelection.yref
};
Registry.call('_guiRelayout', gd, {
selections: list
});
}
}
/***/ }),
/***/ 4016:
/***/ (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 Axes = __webpack_require__(54460);
var readPaths = (__webpack_require__(9856).readPaths);
var displayOutlines = __webpack_require__(55496);
var drawLabel = __webpack_require__(60728);
var clearOutlineControllers = (__webpack_require__(1936).clearOutlineControllers);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var arrayEditor = (__webpack_require__(31780).arrayEditor);
var dragElement = __webpack_require__(86476);
var setCursor = __webpack_require__(93972);
var constants = __webpack_require__(85448);
var helpers = __webpack_require__(65152);
var getPathString = helpers.getPathString;
// Shapes are stored in gd.layout.shapes, an array of objects
// index can point to one item in this array,
// or non-numeric to simply add a new one
// or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
// or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
// annotation at that point in the array, or 'remove' to delete this one
module.exports = {
draw: draw,
drawOne: drawOne,
eraseActiveShape: eraseActiveShape,
drawLabel: drawLabel
};
function draw(gd) {
var fullLayout = gd._fullLayout;
// Remove previous shapes before drawing new in shapes in fullLayout.shapes
fullLayout._shapeUpperLayer.selectAll('path').remove();
fullLayout._shapeLowerLayer.selectAll('path').remove();
fullLayout._shapeUpperLayer.selectAll('text').remove();
fullLayout._shapeLowerLayer.selectAll('text').remove();
for (var k in fullLayout._plots) {
var shapelayer = fullLayout._plots[k].shapelayer;
if (shapelayer) {
shapelayer.selectAll('path').remove();
shapelayer.selectAll('text').remove();
}
}
for (var i = 0; i < fullLayout.shapes.length; i++) {
if (fullLayout.shapes[i].visible === true) {
drawOne(gd, i);
}
}
// may need to resurrect this if we put text (LaTeX) in shapes
// return Plots.previousPromises(gd);
}
function shouldSkipEdits(gd) {
return !!gd._fullLayout._outlining;
}
function couldHaveActiveShape(gd) {
// for now keep config.editable: true as it was before shape-drawing PR
return !gd._context.edits.shapePosition;
}
function drawOne(gd, index) {
// remove the existing shape if there is one.
// because indices can change, we need to look in all shape layers
gd._fullLayout._paperdiv.selectAll('.shapelayer [data-index="' + index + '"]').remove();
var o = helpers.makeShapesOptionsAndPlotinfo(gd, index);
var options = o.options;
var plotinfo = o.plotinfo;
// this shape is gone - quit now after deleting it
// TODO: use d3 idioms instead of deleting and redrawing every time
if (!options._input || options.visible !== true) return;
if (options.layer === 'above') {
drawShape(gd._fullLayout._shapeUpperLayer);
} else if (options.xref === 'paper' || options.yref === 'paper') {
drawShape(gd._fullLayout._shapeLowerLayer);
} else if (options.layer === 'between') {
drawShape(plotinfo.shapelayerBetween);
} else {
if (plotinfo._hadPlotinfo) {
var mainPlot = plotinfo.mainplotinfo || plotinfo;
drawShape(mainPlot.shapelayer);
} else {
// Fall back to _shapeLowerLayer in case the requested subplot doesn't exist.
// This can happen if you reference the shape to an x / y axis combination
// that doesn't have any data on it (and layer is below)
drawShape(gd._fullLayout._shapeLowerLayer);
}
}
function drawShape(shapeLayer) {
var d = getPathString(gd, options);
var attrs = {
'data-index': index,
'fill-rule': options.fillrule,
d: d
};
var opacity = options.opacity;
var fillColor = options.fillcolor;
var lineColor = options.line.width ? options.line.color : 'rgba(0,0,0,0)';
var lineWidth = options.line.width;
var lineDash = options.line.dash;
if (!lineWidth && options.editable === true) {
// ensure invisible border to activate the shape
lineWidth = 5;
lineDash = 'solid';
}
var isOpen = d[d.length - 1] !== 'Z';
var isActiveShape = couldHaveActiveShape(gd) && options.editable && gd._fullLayout._activeShapeIndex === index;
if (isActiveShape) {
fillColor = isOpen ? 'rgba(0,0,0,0)' : gd._fullLayout.activeshape.fillcolor;
opacity = gd._fullLayout.activeshape.opacity;
}
var shapeGroup = shapeLayer.append('g').classed('shape-group', true).attr({
'data-index': index
});
var path = shapeGroup.append('path').attr(attrs).style('opacity', opacity).call(Color.stroke, lineColor).call(Color.fill, fillColor).call(Drawing.dashLine, lineDash, lineWidth);
setClipPath(shapeGroup, gd, options);
// Draw or clear the label
drawLabel(gd, index, options, shapeGroup);
var editHelpers;
if (isActiveShape || gd._context.edits.shapePosition) editHelpers = arrayEditor(gd.layout, 'shapes', options);
if (isActiveShape) {
path.style({
cursor: 'move'
});
var dragOptions = {
element: path.node(),
plotinfo: plotinfo,
gd: gd,
editHelpers: editHelpers,
hasText: options.label.text || options.label.texttemplate,
isActiveShape: true // i.e. to enable controllers
};
var polygons = readPaths(d, gd);
// display polygons on the screen
displayOutlines(polygons, path, dragOptions);
} else {
if (gd._context.edits.shapePosition) {
setupDragElement(gd, path, options, index, shapeLayer, editHelpers);
} else if (options.editable === true) {
path.style('pointer-events', isOpen || Color.opacity(fillColor) * opacity <= 0.5 ? 'stroke' : 'all');
}
}
path.node().addEventListener('click', function () {
return activateShape(gd, path);
});
}
}
function setClipPath(shapePath, gd, shapeOptions) {
// note that for layer="below" the clipAxes can be different from the
// subplot we're drawing this in. This could cause problems if the shape
// spans two subplots. See https://github.com/plotly/plotly.js/issues/1452
//
// if axis is 'paper' or an axis with " domain" appended, then there is no
// clip axis
var clipAxes = (shapeOptions.xref + shapeOptions.yref).replace(/paper/g, '').replace(/[xyz][1-9]* *domain/g, '');
Drawing.setClipUrl(shapePath, clipAxes ? 'clip' + gd._fullLayout._uid + clipAxes : null, gd);
}
function setupDragElement(gd, shapePath, shapeOptions, index, shapeLayer, editHelpers) {
var MINWIDTH = 10;
var MINHEIGHT = 10;
var xPixelSized = shapeOptions.xsizemode === 'pixel';
var yPixelSized = shapeOptions.ysizemode === 'pixel';
var isLine = shapeOptions.type === 'line';
var isPath = shapeOptions.type === 'path';
var modifyItem = editHelpers.modifyItem;
var x0, y0, x1, y1, xAnchor, yAnchor;
var n0, s0, w0, e0, optN, optS, optW, optE;
var pathIn;
var shapeGroup = d3.select(shapePath.node().parentNode);
// setup conversion functions
var xa = Axes.getFromId(gd, shapeOptions.xref);
var xRefType = Axes.getRefType(shapeOptions.xref);
var ya = Axes.getFromId(gd, shapeOptions.yref);
var yRefType = Axes.getRefType(shapeOptions.yref);
var shiftXStart = shapeOptions.x0shift;
var shiftXEnd = shapeOptions.x1shift;
var shiftYStart = shapeOptions.y0shift;
var shiftYEnd = shapeOptions.y1shift;
var x2p = function (v, shift) {
var dataToPixel = helpers.getDataToPixel(gd, xa, shift, false, xRefType);
return dataToPixel(v);
};
var y2p = function (v, shift) {
var dataToPixel = helpers.getDataToPixel(gd, ya, shift, true, yRefType);
return dataToPixel(v);
};
var p2x = helpers.getPixelToData(gd, xa, false, xRefType);
var p2y = helpers.getPixelToData(gd, ya, true, yRefType);
var sensoryElement = obtainSensoryElement();
var dragOptions = {
element: sensoryElement.node(),
gd: gd,
prepFn: startDrag,
doneFn: endDrag,
clickFn: abortDrag
};
var dragMode;
dragElement.init(dragOptions);
sensoryElement.node().onmousemove = updateDragMode;
function obtainSensoryElement() {
return isLine ? createLineDragHandles() : shapePath;
}
function createLineDragHandles() {
var minSensoryWidth = 10;
var sensoryWidth = Math.max(shapeOptions.line.width, minSensoryWidth);
// Helper shapes group
// Note that by setting the `data-index` attr, it is ensured that
// the helper group is purged in this modules `draw` function
var g = shapeLayer.append('g').attr('data-index', index).attr('drag-helper', true);
// Helper path for moving
g.append('path').attr('d', shapePath.attr('d')).style({
cursor: 'move',
'stroke-width': sensoryWidth,
'stroke-opacity': '0' // ensure not visible
});
// Helper circles for resizing
var circleStyle = {
'fill-opacity': '0' // ensure not visible
};
var circleRadius = Math.max(sensoryWidth / 2, minSensoryWidth);
g.append('circle').attr({
'data-line-point': 'start-point',
cx: xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x0 : x2p(shapeOptions.x0, shiftXStart),
cy: yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y0 : y2p(shapeOptions.y0, shiftYStart),
r: circleRadius
}).style(circleStyle).classed('cursor-grab', true);
g.append('circle').attr({
'data-line-point': 'end-point',
cx: xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x1 : x2p(shapeOptions.x1, shiftXEnd),
cy: yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y1 : y2p(shapeOptions.y1, shiftYEnd),
r: circleRadius
}).style(circleStyle).classed('cursor-grab', true);
return g;
}
function updateDragMode(evt) {
if (shouldSkipEdits(gd)) {
dragMode = null;
return;
}
if (isLine) {
if (evt.target.tagName === 'path') {
dragMode = 'move';
} else {
dragMode = evt.target.attributes['data-line-point'].value === 'start-point' ? 'resize-over-start-point' : 'resize-over-end-point';
}
} else {
// element might not be on screen at time of setup,
// so obtain bounding box here
var dragBBox = dragOptions.element.getBoundingClientRect();
// choose 'move' or 'resize'
// based on initial position of cursor within the drag element
var w = dragBBox.right - dragBBox.left;
var h = dragBBox.bottom - dragBBox.top;
var x = evt.clientX - dragBBox.left;
var y = evt.clientY - dragBBox.top;
var cursor = !isPath && w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey ? dragElement.getCursor(x / w, 1 - y / h) : 'move';
setCursor(shapePath, cursor);
// possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w'
dragMode = cursor.split('-')[0];
}
}
function startDrag(evt) {
if (shouldSkipEdits(gd)) return;
// setup update strings and initial values
if (xPixelSized) {
xAnchor = x2p(shapeOptions.xanchor);
}
if (yPixelSized) {
yAnchor = y2p(shapeOptions.yanchor);
}
if (shapeOptions.type === 'path') {
pathIn = shapeOptions.path;
} else {
x0 = xPixelSized ? shapeOptions.x0 : x2p(shapeOptions.x0);
y0 = yPixelSized ? shapeOptions.y0 : y2p(shapeOptions.y0);
x1 = xPixelSized ? shapeOptions.x1 : x2p(shapeOptions.x1);
y1 = yPixelSized ? shapeOptions.y1 : y2p(shapeOptions.y1);
}
if (x0 < x1) {
w0 = x0;
optW = 'x0';
e0 = x1;
optE = 'x1';
} else {
w0 = x1;
optW = 'x1';
e0 = x0;
optE = 'x0';
}
// For fixed size shapes take opposing direction of y-axis into account.
// Hint: For data sized shapes this is done by the y2p function.
if (!yPixelSized && y0 < y1 || yPixelSized && y0 > y1) {
n0 = y0;
optN = 'y0';
s0 = y1;
optS = 'y1';
} else {
n0 = y1;
optN = 'y1';
s0 = y0;
optS = 'y0';
}
// setup dragMode and the corresponding handler
updateDragMode(evt);
renderVisualCues(shapeLayer, shapeOptions);
deactivateClipPathTemporarily(shapePath, shapeOptions, gd);
dragOptions.moveFn = dragMode === 'move' ? moveShape : resizeShape;
dragOptions.altKey = evt.altKey;
}
function endDrag() {
if (shouldSkipEdits(gd)) return;
setCursor(shapePath);
removeVisualCues(shapeLayer);
// Don't rely on clipPath being activated during re-layout
setClipPath(shapePath, gd, shapeOptions);
Registry.call('_guiRelayout', gd, editHelpers.getUpdateObj());
}
function abortDrag() {
if (shouldSkipEdits(gd)) return;
removeVisualCues(shapeLayer);
}
function moveShape(dx, dy) {
if (shapeOptions.type === 'path') {
var noOp = function (coord) {
return coord;
};
var moveX = noOp;
var moveY = noOp;
if (xPixelSized) {
modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
} else {
moveX = function moveX(x) {
return p2x(x2p(x) + dx);
};
if (xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
}
if (yPixelSized) {
modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
} else {
moveY = function moveY(y) {
return p2y(y2p(y) + dy);
};
if (ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
}
modifyItem('path', shapeOptions.path = movePath(pathIn, moveX, moveY));
} else {
if (xPixelSized) {
modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
} else {
modifyItem('x0', shapeOptions.x0 = p2x(x0 + dx));
modifyItem('x1', shapeOptions.x1 = p2x(x1 + dx));
}
if (yPixelSized) {
modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
} else {
modifyItem('y0', shapeOptions.y0 = p2y(y0 + dy));
modifyItem('y1', shapeOptions.y1 = p2y(y1 + dy));
}
}
shapePath.attr('d', getPathString(gd, shapeOptions));
renderVisualCues(shapeLayer, shapeOptions);
drawLabel(gd, index, shapeOptions, shapeGroup);
}
function resizeShape(dx, dy) {
if (isPath) {
// TODO: implement path resize, don't forget to update dragMode code
var noOp = function (coord) {
return coord;
};
var moveX = noOp;
var moveY = noOp;
if (xPixelSized) {
modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
} else {
moveX = function moveX(x) {
return p2x(x2p(x) + dx);
};
if (xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
}
if (yPixelSized) {
modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
} else {
moveY = function moveY(y) {
return p2y(y2p(y) + dy);
};
if (ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
}
modifyItem('path', shapeOptions.path = movePath(pathIn, moveX, moveY));
} else if (isLine) {
if (dragMode === 'resize-over-start-point') {
var newX0 = x0 + dx;
var newY0 = yPixelSized ? y0 - dy : y0 + dy;
modifyItem('x0', shapeOptions.x0 = xPixelSized ? newX0 : p2x(newX0));
modifyItem('y0', shapeOptions.y0 = yPixelSized ? newY0 : p2y(newY0));
} else if (dragMode === 'resize-over-end-point') {
var newX1 = x1 + dx;
var newY1 = yPixelSized ? y1 - dy : y1 + dy;
modifyItem('x1', shapeOptions.x1 = xPixelSized ? newX1 : p2x(newX1));
modifyItem('y1', shapeOptions.y1 = yPixelSized ? newY1 : p2y(newY1));
}
} else {
var has = function (str) {
return dragMode.indexOf(str) !== -1;
};
var hasN = has('n');
var hasS = has('s');
var hasW = has('w');
var hasE = has('e');
var newN = hasN ? n0 + dy : n0;
var newS = hasS ? s0 + dy : s0;
var newW = hasW ? w0 + dx : w0;
var newE = hasE ? e0 + dx : e0;
if (yPixelSized) {
// Do things in opposing direction for y-axis.
// Hint: for data-sized shapes the reversal of axis direction is done in p2y.
if (hasN) newN = n0 - dy;
if (hasS) newS = s0 - dy;
}
// Update shape eventually. Again, be aware of the
// opposing direction of the y-axis of fixed size shapes.
if (!yPixelSized && newS - newN > MINHEIGHT || yPixelSized && newN - newS > MINHEIGHT) {
modifyItem(optN, shapeOptions[optN] = yPixelSized ? newN : p2y(newN));
modifyItem(optS, shapeOptions[optS] = yPixelSized ? newS : p2y(newS));
}
if (newE - newW > MINWIDTH) {
modifyItem(optW, shapeOptions[optW] = xPixelSized ? newW : p2x(newW));
modifyItem(optE, shapeOptions[optE] = xPixelSized ? newE : p2x(newE));
}
}
shapePath.attr('d', getPathString(gd, shapeOptions));
renderVisualCues(shapeLayer, shapeOptions);
drawLabel(gd, index, shapeOptions, shapeGroup);
}
function renderVisualCues(shapeLayer, shapeOptions) {
if (xPixelSized || yPixelSized) {
renderAnchor();
}
function renderAnchor() {
var isNotPath = shapeOptions.type !== 'path';
// d3 join with dummy data to satisfy d3 data-binding
var visualCues = shapeLayer.selectAll('.visual-cue').data([0]);
// Enter
var strokeWidth = 1;
visualCues.enter().append('path').attr({
fill: '#fff',
'fill-rule': 'evenodd',
stroke: '#000',
'stroke-width': strokeWidth
}).classed('visual-cue', true);
// Update
var posX = x2p(xPixelSized ? shapeOptions.xanchor : Lib.midRange(isNotPath ? [shapeOptions.x0, shapeOptions.x1] : helpers.extractPathCoords(shapeOptions.path, constants.paramIsX)));
var posY = y2p(yPixelSized ? shapeOptions.yanchor : Lib.midRange(isNotPath ? [shapeOptions.y0, shapeOptions.y1] : helpers.extractPathCoords(shapeOptions.path, constants.paramIsY)));
posX = helpers.roundPositionForSharpStrokeRendering(posX, strokeWidth);
posY = helpers.roundPositionForSharpStrokeRendering(posY, strokeWidth);
if (xPixelSized && yPixelSized) {
var crossPath = 'M' + (posX - 1 - strokeWidth) + ',' + (posY - 1 - strokeWidth) + 'h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z';
visualCues.attr('d', crossPath);
} else if (xPixelSized) {
var vBarPath = 'M' + (posX - 1 - strokeWidth) + ',' + (posY - 9 - strokeWidth) + 'v18 h2 v-18 Z';
visualCues.attr('d', vBarPath);
} else {
var hBarPath = 'M' + (posX - 9 - strokeWidth) + ',' + (posY - 1 - strokeWidth) + 'h18 v2 h-18 Z';
visualCues.attr('d', hBarPath);
}
}
}
function removeVisualCues(shapeLayer) {
shapeLayer.selectAll('.visual-cue').remove();
}
function deactivateClipPathTemporarily(shapePath, shapeOptions, gd) {
var xref = shapeOptions.xref;
var yref = shapeOptions.yref;
var xa = Axes.getFromId(gd, xref);
var ya = Axes.getFromId(gd, yref);
var clipAxes = '';
if (xref !== 'paper' && !xa.autorange) clipAxes += xref;
if (yref !== 'paper' && !ya.autorange) clipAxes += yref;
Drawing.setClipUrl(shapePath, clipAxes ? 'clip' + gd._fullLayout._uid + clipAxes : null, gd);
}
}
function movePath(pathIn, moveX, moveY) {
return pathIn.replace(constants.segmentRE, function (segment) {
var paramNumber = 0;
var segmentType = segment.charAt(0);
var xParams = constants.paramIsX[segmentType];
var yParams = constants.paramIsY[segmentType];
var nParams = constants.numParams[segmentType];
var paramString = segment.substr(1).replace(constants.paramRE, function (param) {
if (paramNumber >= nParams) return param;
if (xParams[paramNumber]) param = moveX(param);else if (yParams[paramNumber]) param = moveY(param);
paramNumber++;
return param;
});
return segmentType + paramString;
});
}
function activateShape(gd, path) {
if (!couldHaveActiveShape(gd)) return;
var element = path.node();
var id = +element.getAttribute('data-index');
if (id >= 0) {
// deactivate if already active
if (id === gd._fullLayout._activeShapeIndex) {
deactivateShape(gd);
return;
}
gd._fullLayout._activeShapeIndex = id;
gd._fullLayout._deactivateShape = deactivateShape;
draw(gd);
}
}
function deactivateShape(gd) {
if (!couldHaveActiveShape(gd)) return;
var id = gd._fullLayout._activeShapeIndex;
if (id >= 0) {
clearOutlineControllers(gd);
delete gd._fullLayout._activeShapeIndex;
draw(gd);
}
}
function eraseActiveShape(gd) {
if (!couldHaveActiveShape(gd)) return;
clearOutlineControllers(gd);
var id = gd._fullLayout._activeShapeIndex;
var shapes = (gd.layout || {}).shapes || [];
if (id < shapes.length) {
var list = [];
for (var q = 0; q < shapes.length; q++) {
if (q !== id) {
list.push(shapes[q]);
}
}
delete gd._fullLayout._activeShapeIndex;
return Registry.call('_guiRelayout', gd, {
shapes: list
});
}
}
/***/ }),
/***/ 92872:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var overrideAll = (__webpack_require__(67824).overrideAll);
var basePlotAttributes = __webpack_require__(45464);
var fontAttrs = __webpack_require__(25376);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
var shapeTexttemplateAttrs = (__webpack_require__(21776)/* .shapeTexttemplateAttrs */ .ye);
var shapeLabelTexttemplateVars = __webpack_require__(97728);
module.exports = overrideAll({
newshape: {
visible: extendFlat({}, basePlotAttributes.visible, {}),
showlegend: {
valType: 'boolean',
dflt: false
},
legend: extendFlat({}, basePlotAttributes.legend, {}),
legendgroup: extendFlat({}, basePlotAttributes.legendgroup, {}),
legendgrouptitle: {
text: extendFlat({}, basePlotAttributes.legendgrouptitle.text, {}),
font: fontAttrs({})
},
legendrank: extendFlat({}, basePlotAttributes.legendrank, {}),
legendwidth: extendFlat({}, basePlotAttributes.legendwidth, {}),
line: {
color: {
valType: 'color'
},
width: {
valType: 'number',
min: 0,
dflt: 4
},
dash: extendFlat({}, dash, {
dflt: 'solid'
})
},
fillcolor: {
valType: 'color',
dflt: 'rgba(0,0,0,0)'
},
fillrule: {
valType: 'enumerated',
values: ['evenodd', 'nonzero'],
dflt: 'evenodd'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1
},
layer: {
valType: 'enumerated',
values: ['below', 'above', 'between'],
dflt: 'above'
},
drawdirection: {
valType: 'enumerated',
values: ['ortho', 'horizontal', 'vertical', 'diagonal'],
dflt: 'diagonal'
},
name: extendFlat({}, basePlotAttributes.name, {}),
label: {
text: {
valType: 'string',
dflt: ''
},
texttemplate: shapeTexttemplateAttrs({
newshape: true
}, {
keys: Object.keys(shapeLabelTexttemplateVars)
}),
font: fontAttrs({}),
textposition: {
valType: 'enumerated',
values: ['top left', 'top center', 'top right', 'middle left', 'middle center', 'middle right', 'bottom left', 'bottom center', 'bottom right', 'start', 'middle', 'end']
},
textangle: {
valType: 'angle',
dflt: 'auto'
},
xanchor: {
valType: 'enumerated',
values: ['auto', 'left', 'center', 'right'],
dflt: 'auto'
},
yanchor: {
valType: 'enumerated',
values: ['top', 'middle', 'bottom']
},
padding: {
valType: 'number',
dflt: 3,
min: 0
}
}
},
activeshape: {
fillcolor: {
valType: 'color',
dflt: 'rgb(255,0,255)'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.5
}
}
}, 'none', 'from-root');
/***/ }),
/***/ 7000:
/***/ (function(module) {
"use strict";
var CIRCLE_SIDES = 32; // should be divisible by 4
module.exports = {
CIRCLE_SIDES: CIRCLE_SIDES,
i000: 0,
i090: CIRCLE_SIDES / 4,
i180: CIRCLE_SIDES / 2,
i270: CIRCLE_SIDES / 4 * 3,
cos45: Math.cos(Math.PI / 4),
sin45: Math.sin(Math.PI / 4),
SQRT2: Math.sqrt(2)
};
/***/ }),
/***/ 65144:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var Lib = __webpack_require__(3400);
function dfltLabelYanchor(isLine, labelTextPosition) {
// If shape is a line, default y-anchor is 'bottom' (so that text is above line by default)
// Otherwise, default y-anchor is equal to y-component of `textposition`
// (so that text is positioned inside shape bounding box by default)
return isLine ? 'bottom' : labelTextPosition.indexOf('top') !== -1 ? 'top' : labelTextPosition.indexOf('bottom') !== -1 ? 'bottom' : 'middle';
}
module.exports = function supplyDrawNewShapeDefaults(layoutIn, layoutOut, coerce) {
coerce('newshape.visible');
coerce('newshape.name');
coerce('newshape.showlegend');
coerce('newshape.legend');
coerce('newshape.legendwidth');
coerce('newshape.legendgroup');
coerce('newshape.legendgrouptitle.text');
Lib.coerceFont(coerce, 'newshape.legendgrouptitle.font');
coerce('newshape.legendrank');
coerce('newshape.drawdirection');
coerce('newshape.layer');
coerce('newshape.fillcolor');
coerce('newshape.fillrule');
coerce('newshape.opacity');
var newshapeLineWidth = coerce('newshape.line.width');
if (newshapeLineWidth) {
var bgcolor = (layoutIn || {}).plot_bgcolor || '#FFF';
coerce('newshape.line.color', Color.contrast(bgcolor));
coerce('newshape.line.dash');
}
var isLine = layoutIn.dragmode === 'drawline';
var labelText = coerce('newshape.label.text');
var labelTextTemplate = coerce('newshape.label.texttemplate');
if (labelText || labelTextTemplate) {
coerce('newshape.label.textangle');
var labelTextPosition = coerce('newshape.label.textposition', isLine ? 'middle' : 'middle center');
coerce('newshape.label.xanchor');
coerce('newshape.label.yanchor', dfltLabelYanchor(isLine, labelTextPosition));
coerce('newshape.label.padding');
Lib.coerceFont(coerce, 'newshape.label.font', layoutOut.font);
}
coerce('activeshape.fillcolor');
coerce('activeshape.opacity');
};
/***/ }),
/***/ 9856:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var parseSvgPath = __webpack_require__(21984);
var constants = __webpack_require__(7000);
var CIRCLE_SIDES = constants.CIRCLE_SIDES;
var SQRT2 = constants.SQRT2;
var cartesianHelpers = __webpack_require__(5840);
var p2r = cartesianHelpers.p2r;
var r2p = cartesianHelpers.r2p;
var iC = [0, 3, 4, 5, 6, 1, 2];
var iQS = [0, 3, 4, 1, 2];
exports.writePaths = function (polygons) {
var nI = polygons.length;
if (!nI) return 'M0,0Z';
var str = '';
for (var i = 0; i < nI; i++) {
var nJ = polygons[i].length;
for (var j = 0; j < nJ; j++) {
var w = polygons[i][j][0];
if (w === 'Z') {
str += 'Z';
} else {
var nK = polygons[i][j].length;
for (var k = 0; k < nK; k++) {
var realK = k;
if (w === 'Q' || w === 'S') {
realK = iQS[k];
} else if (w === 'C') {
realK = iC[k];
}
str += polygons[i][j][realK];
if (k > 0 && k < nK - 1) {
str += ',';
}
}
}
}
}
return str;
};
exports.readPaths = function (str, gd, plotinfo, isActiveShape) {
var cmd = parseSvgPath(str);
var polys = [];
var n = -1;
var newPoly = function () {
n++;
polys[n] = [];
};
var k;
var x = 0;
var y = 0;
var initX;
var initY;
var recStart = function () {
initX = x;
initY = y;
};
recStart();
for (var i = 0; i < cmd.length; i++) {
var newPos = [];
var x1, x2, y1, y2; // i.e. extra params for curves
var c = cmd[i][0];
var w = c;
switch (c) {
case 'M':
newPoly();
x = +cmd[i][1];
y = +cmd[i][2];
newPos.push([w, x, y]);
recStart();
break;
case 'Q':
case 'S':
x1 = +cmd[i][1];
y1 = +cmd[i][2];
x = +cmd[i][3];
y = +cmd[i][4];
newPos.push([w, x, y, x1, y1]); // -> iQS order
break;
case 'C':
x1 = +cmd[i][1];
y1 = +cmd[i][2];
x2 = +cmd[i][3];
y2 = +cmd[i][4];
x = +cmd[i][5];
y = +cmd[i][6];
newPos.push([w, x, y, x1, y1, x2, y2]); // -> iC order
break;
case 'T':
case 'L':
x = +cmd[i][1];
y = +cmd[i][2];
newPos.push([w, x, y]);
break;
case 'H':
w = 'L'; // convert to line (for now)
x = +cmd[i][1];
newPos.push([w, x, y]);
break;
case 'V':
w = 'L'; // convert to line (for now)
y = +cmd[i][1];
newPos.push([w, x, y]);
break;
case 'A':
w = 'L'; // convert to line to handle circle
var rx = +cmd[i][1];
var ry = +cmd[i][2];
if (!+cmd[i][4]) {
rx = -rx;
ry = -ry;
}
var cenX = x - rx;
var cenY = y;
for (k = 1; k <= CIRCLE_SIDES / 2; k++) {
var t = 2 * Math.PI * k / CIRCLE_SIDES;
newPos.push([w, cenX + rx * Math.cos(t), cenY + ry * Math.sin(t)]);
}
break;
case 'Z':
if (x !== initX || y !== initY) {
x = initX;
y = initY;
newPos.push([w, x, y]);
}
break;
}
var domain = (plotinfo || {}).domain;
var size = gd._fullLayout._size;
var xPixelSized = plotinfo && plotinfo.xsizemode === 'pixel';
var yPixelSized = plotinfo && plotinfo.ysizemode === 'pixel';
var noOffset = isActiveShape === false;
for (var j = 0; j < newPos.length; j++) {
for (k = 0; k + 2 < 7; k += 2) {
var _x = newPos[j][k + 1];
var _y = newPos[j][k + 2];
if (_x === undefined || _y === undefined) continue;
// keep track of end point for Z
x = _x;
y = _y;
if (plotinfo) {
if (plotinfo.xaxis && plotinfo.xaxis.p2r) {
if (noOffset) _x -= plotinfo.xaxis._offset;
if (xPixelSized) {
_x = r2p(plotinfo.xaxis, plotinfo.xanchor) + _x;
} else {
_x = p2r(plotinfo.xaxis, _x);
}
} else {
if (noOffset) _x -= size.l;
if (domain) _x = domain.x[0] + _x / size.w;else _x = _x / size.w;
}
if (plotinfo.yaxis && plotinfo.yaxis.p2r) {
if (noOffset) _y -= plotinfo.yaxis._offset;
if (yPixelSized) {
_y = r2p(plotinfo.yaxis, plotinfo.yanchor) - _y;
} else {
_y = p2r(plotinfo.yaxis, _y);
}
} else {
if (noOffset) _y -= size.t;
if (domain) _y = domain.y[1] - _y / size.h;else _y = 1 - _y / size.h;
}
}
newPos[j][k + 1] = _x;
newPos[j][k + 2] = _y;
}
polys[n].push(newPos[j].slice());
}
}
return polys;
};
function almostEq(a, b) {
return Math.abs(a - b) <= 1e-6;
}
function dist(a, b) {
var dx = b[1] - a[1];
var dy = b[2] - a[2];
return Math.sqrt(dx * dx + dy * dy);
}
exports.pointsOnRectangle = function (cell) {
var len = cell.length;
if (len !== 5) return false;
for (var j = 1; j < 3; j++) {
var e01 = cell[0][j] - cell[1][j];
var e32 = cell[3][j] - cell[2][j];
if (!almostEq(e01, e32)) return false;
var e03 = cell[0][j] - cell[3][j];
var e12 = cell[1][j] - cell[2][j];
if (!almostEq(e03, e12)) return false;
}
// N.B. rotated rectangles are not valid rects since rotation is not supported in shapes for now.
if (!almostEq(cell[0][1], cell[1][1]) && !almostEq(cell[0][1], cell[3][1])) return false;
// reject cases with zero area
return !!(dist(cell[0], cell[1]) * dist(cell[0], cell[3]));
};
exports.pointsOnEllipse = function (cell) {
var len = cell.length;
if (len !== CIRCLE_SIDES + 1) return false;
// opposite diagonals should be the same
len = CIRCLE_SIDES;
for (var i = 0; i < len; i++) {
var k = (len * 2 - i) % len;
var k2 = (len / 2 + k) % len;
var i2 = (len / 2 + i) % len;
if (!almostEq(dist(cell[i], cell[i2]), dist(cell[k], cell[k2]))) return false;
}
return true;
};
exports.handleEllipse = function (isEllipse, start, end) {
if (!isEllipse) return [start, end]; // i.e. case of line
var pos = exports.ellipseOver({
x0: start[0],
y0: start[1],
x1: end[0],
y1: end[1]
});
var cx = (pos.x1 + pos.x0) / 2;
var cy = (pos.y1 + pos.y0) / 2;
var rx = (pos.x1 - pos.x0) / 2;
var ry = (pos.y1 - pos.y0) / 2;
// make a circle when one dimension is zero
if (!rx) rx = ry = ry / SQRT2;
if (!ry) ry = rx = rx / SQRT2;
var cell = [];
for (var i = 0; i < CIRCLE_SIDES; i++) {
var t = i * 2 * Math.PI / CIRCLE_SIDES;
cell.push([cx + rx * Math.cos(t), cy + ry * Math.sin(t)]);
}
return cell;
};
exports.ellipseOver = function (pos) {
var x0 = pos.x0;
var y0 = pos.y0;
var x1 = pos.x1;
var y1 = pos.y1;
var dx = x1 - x0;
var dy = y1 - y0;
x0 -= dx;
y0 -= dy;
var cx = (x0 + x1) / 2;
var cy = (y0 + y1) / 2;
var scale = SQRT2;
dx *= scale;
dy *= scale;
return {
x0: cx - dx,
y0: cy - dy,
x1: cx + dx,
y1: cy + dy
};
};
exports.fixDatesForPaths = function (polygons, xaxis, yaxis) {
var xIsDate = xaxis.type === 'date';
var yIsDate = yaxis.type === 'date';
if (!xIsDate && !yIsDate) return polygons;
for (var i = 0; i < polygons.length; i++) {
for (var j = 0; j < polygons[i].length; j++) {
for (var k = 0; k + 2 < polygons[i][j].length; k += 2) {
if (xIsDate) polygons[i][j][k + 1] = polygons[i][j][k + 1].replace(' ', '_');
if (yIsDate) polygons[i][j][k + 2] = polygons[i][j][k + 2].replace(' ', '_');
}
}
}
return polygons;
};
/***/ }),
/***/ 93940:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var dragHelpers = __webpack_require__(72760);
var drawMode = dragHelpers.drawMode;
var openMode = dragHelpers.openMode;
var constants = __webpack_require__(7000);
var i000 = constants.i000;
var i090 = constants.i090;
var i180 = constants.i180;
var i270 = constants.i270;
var cos45 = constants.cos45;
var sin45 = constants.sin45;
var cartesianHelpers = __webpack_require__(5840);
var p2r = cartesianHelpers.p2r;
var r2p = cartesianHelpers.r2p;
var handleOutline = __webpack_require__(1936);
var clearOutline = handleOutline.clearOutline;
var helpers = __webpack_require__(9856);
var readPaths = helpers.readPaths;
var writePaths = helpers.writePaths;
var ellipseOver = helpers.ellipseOver;
var fixDatesForPaths = helpers.fixDatesForPaths;
function newShapes(outlines, dragOptions) {
if (!outlines.length) return;
var e = outlines[0][0]; // pick first
if (!e) return;
var gd = dragOptions.gd;
var isActiveShape = dragOptions.isActiveShape;
var dragmode = dragOptions.dragmode;
var shapes = (gd.layout || {}).shapes || [];
if (!drawMode(dragmode) && isActiveShape !== undefined) {
var id = gd._fullLayout._activeShapeIndex;
if (id < shapes.length) {
switch (gd._fullLayout.shapes[id].type) {
case 'rect':
dragmode = 'drawrect';
break;
case 'circle':
dragmode = 'drawcircle';
break;
case 'line':
dragmode = 'drawline';
break;
case 'path':
var path = shapes[id].path || '';
if (path[path.length - 1] === 'Z') {
dragmode = 'drawclosedpath';
} else {
dragmode = 'drawopenpath';
}
break;
}
}
}
var newShape = createShapeObj(outlines, dragOptions, dragmode);
clearOutline(gd);
var editHelpers = dragOptions.editHelpers;
var modifyItem = (editHelpers || {}).modifyItem;
var allShapes = [];
for (var q = 0; q < shapes.length; q++) {
var beforeEdit = gd._fullLayout.shapes[q];
allShapes[q] = beforeEdit._input;
if (isActiveShape !== undefined && q === gd._fullLayout._activeShapeIndex) {
var afterEdit = newShape;
switch (beforeEdit.type) {
case 'line':
case 'rect':
case 'circle':
modifyItem('x0', afterEdit.x0 - (beforeEdit.x0shift || 0));
modifyItem('x1', afterEdit.x1 - (beforeEdit.x1shift || 0));
modifyItem('y0', afterEdit.y0 - (beforeEdit.y0shift || 0));
modifyItem('y1', afterEdit.y1 - (beforeEdit.y1shift || 0));
break;
case 'path':
modifyItem('path', afterEdit.path);
break;
}
}
}
if (isActiveShape === undefined) {
allShapes.push(newShape); // add new shape
return allShapes;
}
return editHelpers ? editHelpers.getUpdateObj() : {};
}
function createShapeObj(outlines, dragOptions, dragmode) {
var e = outlines[0][0]; // pick first outline
var gd = dragOptions.gd;
var d = e.getAttribute('d');
var newStyle = gd._fullLayout.newshape;
var plotinfo = dragOptions.plotinfo;
var isActiveShape = dragOptions.isActiveShape;
var xaxis = plotinfo.xaxis;
var yaxis = plotinfo.yaxis;
var xPaper = !!plotinfo.domain || !plotinfo.xaxis;
var yPaper = !!plotinfo.domain || !plotinfo.yaxis;
var isOpenMode = openMode(dragmode);
var polygons = readPaths(d, gd, plotinfo, isActiveShape);
var newShape = {
editable: true,
visible: newStyle.visible,
name: newStyle.name,
showlegend: newStyle.showlegend,
legend: newStyle.legend,
legendwidth: newStyle.legendwidth,
legendgroup: newStyle.legendgroup,
legendgrouptitle: {
text: newStyle.legendgrouptitle.text,
font: newStyle.legendgrouptitle.font
},
legendrank: newStyle.legendrank,
label: newStyle.label,
xref: xPaper ? 'paper' : xaxis._id,
yref: yPaper ? 'paper' : yaxis._id,
layer: newStyle.layer,
opacity: newStyle.opacity,
line: {
color: newStyle.line.color,
width: newStyle.line.width,
dash: newStyle.line.dash
}
};
if (!isOpenMode) {
newShape.fillcolor = newStyle.fillcolor;
newShape.fillrule = newStyle.fillrule;
}
var cell;
// line, rect and circle can be in one cell
// only define cell if there is single cell
if (polygons.length === 1) cell = polygons[0];
if (cell && cell.length === 5 &&
// ensure we only have 4 corners for a rect
dragmode === 'drawrect') {
newShape.type = 'rect';
newShape.x0 = cell[0][1];
newShape.y0 = cell[0][2];
newShape.x1 = cell[2][1];
newShape.y1 = cell[2][2];
} else if (cell && dragmode === 'drawline') {
newShape.type = 'line';
newShape.x0 = cell[0][1];
newShape.y0 = cell[0][2];
newShape.x1 = cell[1][1];
newShape.y1 = cell[1][2];
} else if (cell && dragmode === 'drawcircle') {
newShape.type = 'circle'; // an ellipse!
var xA = cell[i000][1];
var xB = cell[i090][1];
var xC = cell[i180][1];
var xD = cell[i270][1];
var yA = cell[i000][2];
var yB = cell[i090][2];
var yC = cell[i180][2];
var yD = cell[i270][2];
var xDateOrLog = plotinfo.xaxis && (plotinfo.xaxis.type === 'date' || plotinfo.xaxis.type === 'log');
var yDateOrLog = plotinfo.yaxis && (plotinfo.yaxis.type === 'date' || plotinfo.yaxis.type === 'log');
if (xDateOrLog) {
xA = r2p(plotinfo.xaxis, xA);
xB = r2p(plotinfo.xaxis, xB);
xC = r2p(plotinfo.xaxis, xC);
xD = r2p(plotinfo.xaxis, xD);
}
if (yDateOrLog) {
yA = r2p(plotinfo.yaxis, yA);
yB = r2p(plotinfo.yaxis, yB);
yC = r2p(plotinfo.yaxis, yC);
yD = r2p(plotinfo.yaxis, yD);
}
var x0 = (xB + xD) / 2;
var y0 = (yA + yC) / 2;
var rx = (xD - xB + xC - xA) / 2;
var ry = (yD - yB + yC - yA) / 2;
var pos = ellipseOver({
x0: x0,
y0: y0,
x1: x0 + rx * cos45,
y1: y0 + ry * sin45
});
if (xDateOrLog) {
pos.x0 = p2r(plotinfo.xaxis, pos.x0);
pos.x1 = p2r(plotinfo.xaxis, pos.x1);
}
if (yDateOrLog) {
pos.y0 = p2r(plotinfo.yaxis, pos.y0);
pos.y1 = p2r(plotinfo.yaxis, pos.y1);
}
newShape.x0 = pos.x0;
newShape.y0 = pos.y0;
newShape.x1 = pos.x1;
newShape.y1 = pos.y1;
} else {
newShape.type = 'path';
if (xaxis && yaxis) fixDatesForPaths(polygons, xaxis, yaxis);
newShape.path = writePaths(polygons);
cell = null;
}
return newShape;
}
module.exports = {
newShapes: newShapes,
createShapeObj: createShapeObj
};
/***/ }),
/***/ 1936:
/***/ (function(module) {
"use strict";
function clearOutlineControllers(gd) {
var zoomLayer = gd._fullLayout._zoomlayer;
if (zoomLayer) {
zoomLayer.selectAll('.outline-controllers').remove();
}
}
function clearOutline(gd) {
var zoomLayer = gd._fullLayout._zoomlayer;
if (zoomLayer) {
// until we get around to persistent selections, remove the outline
// here. The selection itself will be removed when the plot redraws
// at the end.
zoomLayer.selectAll('.select-outline').remove();
}
gd._fullLayout._outlining = false;
}
module.exports = {
clearOutlineControllers: clearOutlineControllers,
clearOutline: clearOutline
};
/***/ }),
/***/ 65152:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(85448);
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
// special position conversion functions... category axis positions can't be
// specified by their data values, because they don't make a continuous mapping.
// so these have to be specified in terms of the category serial numbers,
// but can take fractional values. Other axis types we specify position based on
// the actual data values.
// TODO: in V3.0 (when log axis ranges are in data units) range and shape position
// will be identical, so rangeToShapePosition and shapePositionToRange can be
// removed entirely.
exports.rangeToShapePosition = function (ax) {
return ax.type === 'log' ? ax.r2d : function (v) {
return v;
};
};
exports.shapePositionToRange = function (ax) {
return ax.type === 'log' ? ax.d2r : function (v) {
return v;
};
};
exports.decodeDate = function (convertToPx) {
return function (v) {
if (v.replace) v = v.replace('_', ' ');
return convertToPx(v);
};
};
exports.encodeDate = function (convertToDate) {
return function (v) {
return convertToDate(v).replace(' ', '_');
};
};
exports.extractPathCoords = function (path, paramsToUse, isRaw) {
var extractedCoordinates = [];
var segments = path.match(constants.segmentRE);
segments.forEach(function (segment) {
var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn;
if (relevantParamIdx === undefined) return;
var params = segment.substr(1).match(constants.paramRE);
if (!params || params.length < relevantParamIdx) return;
var str = params[relevantParamIdx];
var pos = isRaw ? str : Lib.cleanNumber(str);
extractedCoordinates.push(pos);
});
return extractedCoordinates;
};
exports.getDataToPixel = function (gd, axis, shift, isVertical, refType) {
var gs = gd._fullLayout._size;
var dataToPixel;
if (axis) {
if (refType === 'domain') {
dataToPixel = function (v) {
return axis._length * (isVertical ? 1 - v : v) + axis._offset;
};
} else {
var d2r = exports.shapePositionToRange(axis);
dataToPixel = function (v) {
var shiftPixels = getPixelShift(axis, shift);
return axis._offset + axis.r2p(d2r(v, true)) + shiftPixels;
};
if (axis.type === 'date') dataToPixel = exports.decodeDate(dataToPixel);
}
} else if (isVertical) {
dataToPixel = function (v) {
return gs.t + gs.h * (1 - v);
};
} else {
dataToPixel = function (v) {
return gs.l + gs.w * v;
};
}
return dataToPixel;
};
exports.getPixelToData = function (gd, axis, isVertical, opt) {
var gs = gd._fullLayout._size;
var pixelToData;
if (axis) {
if (opt === 'domain') {
pixelToData = function (p) {
var q = (p - axis._offset) / axis._length;
return isVertical ? 1 - q : q;
};
} else {
var r2d = exports.rangeToShapePosition(axis);
pixelToData = function (p) {
return r2d(axis.p2r(p - axis._offset));
};
}
} else if (isVertical) {
pixelToData = function (p) {
return 1 - (p - gs.t) / gs.h;
};
} else {
pixelToData = function (p) {
return (p - gs.l) / gs.w;
};
}
return pixelToData;
};
/**
* Based on the given stroke width, rounds the passed
* position value to represent either a full or half pixel.
*
* In case of an odd stroke width (e.g. 1), this measure ensures
* that a stroke positioned at the returned position isn't rendered
* blurry due to anti-aliasing.
*
* In case of an even stroke width (e.g. 2), this measure ensures
* that the position value is transformed to a full pixel value
* so that anti-aliasing doesn't take effect either.
*
* @param {number} pos The raw position value to be transformed
* @param {number} strokeWidth The stroke width
* @returns {number} either an integer or a .5 decimal number
*/
exports.roundPositionForSharpStrokeRendering = function (pos, strokeWidth) {
var strokeWidthIsOdd = Math.round(strokeWidth % 2) === 1;
var posValAsInt = Math.round(pos);
return strokeWidthIsOdd ? posValAsInt + 0.5 : posValAsInt;
};
exports.makeShapesOptionsAndPlotinfo = function (gd, index) {
var options = gd._fullLayout.shapes[index] || {};
var plotinfo = gd._fullLayout._plots[options.xref + options.yref];
var hasPlotinfo = !!plotinfo;
if (hasPlotinfo) {
plotinfo._hadPlotinfo = true;
} else {
plotinfo = {};
if (options.xref && options.xref !== 'paper') plotinfo.xaxis = gd._fullLayout[options.xref + 'axis'];
if (options.yref && options.yref !== 'paper') plotinfo.yaxis = gd._fullLayout[options.yref + 'axis'];
}
plotinfo.xsizemode = options.xsizemode;
plotinfo.ysizemode = options.ysizemode;
plotinfo.xanchor = options.xanchor;
plotinfo.yanchor = options.yanchor;
return {
options: options,
plotinfo: plotinfo
};
};
// TODO: move to selections helpers?
exports.makeSelectionsOptionsAndPlotinfo = function (gd, index) {
var options = gd._fullLayout.selections[index] || {};
var plotinfo = gd._fullLayout._plots[options.xref + options.yref];
var hasPlotinfo = !!plotinfo;
if (hasPlotinfo) {
plotinfo._hadPlotinfo = true;
} else {
plotinfo = {};
if (options.xref) plotinfo.xaxis = gd._fullLayout[options.xref + 'axis'];
if (options.yref) plotinfo.yaxis = gd._fullLayout[options.yref + 'axis'];
}
return {
options: options,
plotinfo: plotinfo
};
};
exports.getPathString = function (gd, options) {
var type = options.type;
var xRefType = Axes.getRefType(options.xref);
var yRefType = Axes.getRefType(options.yref);
var xa = Axes.getFromId(gd, options.xref);
var ya = Axes.getFromId(gd, options.yref);
var gs = gd._fullLayout._size;
var x2r, x2p, y2r, y2p;
var xShiftStart = getPixelShift(xa, options.x0shift);
var xShiftEnd = getPixelShift(xa, options.x1shift);
var yShiftStart = getPixelShift(ya, options.y0shift);
var yShiftEnd = getPixelShift(ya, options.y1shift);
var x0, x1, y0, y1;
if (xa) {
if (xRefType === 'domain') {
x2p = function (v) {
return xa._offset + xa._length * v;
};
} else {
x2r = exports.shapePositionToRange(xa);
x2p = function (v) {
return xa._offset + xa.r2p(x2r(v, true));
};
}
} else {
x2p = function (v) {
return gs.l + gs.w * v;
};
}
if (ya) {
if (yRefType === 'domain') {
y2p = function (v) {
return ya._offset + ya._length * (1 - v);
};
} else {
y2r = exports.shapePositionToRange(ya);
y2p = function (v) {
return ya._offset + ya.r2p(y2r(v, true));
};
}
} else {
y2p = function (v) {
return gs.t + gs.h * (1 - v);
};
}
if (type === 'path') {
if (xa && xa.type === 'date') x2p = exports.decodeDate(x2p);
if (ya && ya.type === 'date') y2p = exports.decodeDate(y2p);
return convertPath(options, x2p, y2p);
}
if (options.xsizemode === 'pixel') {
var xAnchorPos = x2p(options.xanchor);
x0 = xAnchorPos + options.x0 + xShiftStart;
x1 = xAnchorPos + options.x1 + xShiftEnd;
} else {
x0 = x2p(options.x0) + xShiftStart;
x1 = x2p(options.x1) + xShiftEnd;
}
if (options.ysizemode === 'pixel') {
var yAnchorPos = y2p(options.yanchor);
y0 = yAnchorPos - options.y0 + yShiftStart;
y1 = yAnchorPos - options.y1 + yShiftEnd;
} else {
y0 = y2p(options.y0) + yShiftStart;
y1 = y2p(options.y1) + yShiftEnd;
}
if (type === 'line') return 'M' + x0 + ',' + y0 + 'L' + x1 + ',' + y1;
if (type === 'rect') return 'M' + x0 + ',' + y0 + 'H' + x1 + 'V' + y1 + 'H' + x0 + 'Z';
// circle
var cx = (x0 + x1) / 2;
var cy = (y0 + y1) / 2;
var rx = Math.abs(cx - x0);
var ry = Math.abs(cy - y0);
var rArc = 'A' + rx + ',' + ry;
var rightPt = cx + rx + ',' + cy;
var topPt = cx + ',' + (cy - ry);
return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + rArc + ' 0 0,1 ' + rightPt + 'Z';
};
function convertPath(options, x2p, y2p) {
var pathIn = options.path;
var xSizemode = options.xsizemode;
var ySizemode = options.ysizemode;
var xAnchor = options.xanchor;
var yAnchor = options.yanchor;
return pathIn.replace(constants.segmentRE, function (segment) {
var paramNumber = 0;
var segmentType = segment.charAt(0);
var xParams = constants.paramIsX[segmentType];
var yParams = constants.paramIsY[segmentType];
var nParams = constants.numParams[segmentType];
var paramString = segment.substr(1).replace(constants.paramRE, function (param) {
if (xParams[paramNumber]) {
if (xSizemode === 'pixel') param = x2p(xAnchor) + Number(param);else param = x2p(param);
} else if (yParams[paramNumber]) {
if (ySizemode === 'pixel') param = y2p(yAnchor) - Number(param);else param = y2p(param);
}
paramNumber++;
if (paramNumber > nParams) param = 'X';
return param;
});
if (paramNumber > nParams) {
paramString = paramString.replace(/[\s,]*X.*/, '');
Lib.log('Ignoring extra params in segment ' + segment);
}
return segmentType + paramString;
});
}
function getPixelShift(axis, shift) {
shift = shift || 0;
var shiftPixels = 0;
if (shift && axis && (axis.type === 'category' || axis.type === 'multicategory')) {
shiftPixels = (axis.r2p(1) - axis.r2p(0)) * shift;
}
return shiftPixels;
}
/***/ }),
/***/ 41592:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var drawModule = __webpack_require__(4016);
module.exports = {
moduleType: 'component',
name: 'shapes',
layoutAttributes: __webpack_require__(46056),
supplyLayoutDefaults: __webpack_require__(43712),
supplyDrawNewShapeDefaults: __webpack_require__(65144),
includeBasePlot: __webpack_require__(36632)('shapes'),
calcAutorange: __webpack_require__(96084),
draw: drawModule.draw,
drawOne: drawModule.drawOne
};
/***/ }),
/***/ 97728:
/***/ (function(module) {
"use strict";
// Wrapper functions to handle paper-referenced shapes, which have no axis
function d2l(v, axis) {
return axis ? axis.d2l(v) : v;
}
function l2d(v, axis) {
return axis ? axis.l2d(v) : v;
}
function x0Fn(shape) {
return shape.x0;
}
function x1Fn(shape) {
return shape.x1;
}
function y0Fn(shape) {
return shape.y0;
}
function y1Fn(shape) {
return shape.y1;
}
function x0shiftFn(shape) {
return shape.x0shift || 0;
}
function x1shiftFn(shape) {
return shape.x1shift || 0;
}
function y0shiftFn(shape) {
return shape.y0shift || 0;
}
function y1shiftFn(shape) {
return shape.y1shift || 0;
}
function dxFn(shape, xa) {
return d2l(shape.x1, xa) + x1shiftFn(shape) - d2l(shape.x0, xa) - x0shiftFn(shape);
}
function dyFn(shape, xa, ya) {
return d2l(shape.y1, ya) + y1shiftFn(shape) - d2l(shape.y0, ya) - y0shiftFn(shape);
}
function widthFn(shape, xa) {
return Math.abs(dxFn(shape, xa));
}
function heightFn(shape, xa, ya) {
return Math.abs(dyFn(shape, xa, ya));
}
function lengthFn(shape, xa, ya) {
return shape.type !== 'line' ? undefined : Math.sqrt(Math.pow(dxFn(shape, xa), 2) + Math.pow(dyFn(shape, xa, ya), 2));
}
function xcenterFn(shape, xa) {
return l2d((d2l(shape.x1, xa) + x1shiftFn(shape) + d2l(shape.x0, xa) + x0shiftFn(shape)) / 2, xa);
}
function ycenterFn(shape, xa, ya) {
return l2d((d2l(shape.y1, ya) + y1shiftFn(shape) + d2l(shape.y0, ya) + y0shiftFn(shape)) / 2, ya);
}
function slopeFn(shape, xa, ya) {
return shape.type !== 'line' ? undefined : dyFn(shape, xa, ya) / dxFn(shape, xa);
}
module.exports = {
x0: x0Fn,
x1: x1Fn,
y0: y0Fn,
y1: y1Fn,
slope: slopeFn,
dx: dxFn,
dy: dyFn,
width: widthFn,
height: heightFn,
length: lengthFn,
xcenter: xcenterFn,
ycenter: ycenterFn
};
/***/ }),
/***/ 89861:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var padAttrs = __webpack_require__(66741);
var extendDeepAll = (__webpack_require__(92880).extendDeepAll);
var overrideAll = (__webpack_require__(67824).overrideAll);
var animationAttrs = __webpack_require__(85656);
var templatedArray = (__webpack_require__(31780).templatedArray);
var constants = __webpack_require__(60876);
var stepsAttrs = templatedArray('step', {
visible: {
valType: 'boolean',
dflt: true
},
method: {
valType: 'enumerated',
values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
dflt: 'restyle'
},
args: {
valType: 'info_array',
freeLength: true,
items: [{
valType: 'any'
}, {
valType: 'any'
}, {
valType: 'any'
}]
},
label: {
valType: 'string'
},
value: {
valType: 'string'
},
execute: {
valType: 'boolean',
dflt: true
}
});
module.exports = overrideAll(templatedArray('slider', {
visible: {
valType: 'boolean',
dflt: true
},
active: {
valType: 'number',
min: 0,
dflt: 0
},
steps: stepsAttrs,
lenmode: {
valType: 'enumerated',
values: ['fraction', 'pixels'],
dflt: 'fraction'
},
len: {
valType: 'number',
min: 0,
dflt: 1
},
x: {
valType: 'number',
min: -2,
max: 3,
dflt: 0
},
pad: extendDeepAll(padAttrs({
editType: 'arraydraw'
}), {}, {
t: {
dflt: 20
}
}),
xanchor: {
valType: 'enumerated',
values: ['auto', 'left', 'center', 'right'],
dflt: 'left'
},
y: {
valType: 'number',
min: -2,
max: 3,
dflt: 0
},
yanchor: {
valType: 'enumerated',
values: ['auto', 'top', 'middle', 'bottom'],
dflt: 'top'
},
transition: {
duration: {
valType: 'number',
min: 0,
dflt: 150
},
easing: {
valType: 'enumerated',
values: animationAttrs.transition.easing.values,
dflt: 'cubic-in-out'
}
},
currentvalue: {
visible: {
valType: 'boolean',
dflt: true
},
xanchor: {
valType: 'enumerated',
values: ['left', 'center', 'right'],
dflt: 'left'
},
offset: {
valType: 'number',
dflt: 10
},
prefix: {
valType: 'string'
},
suffix: {
valType: 'string'
},
font: fontAttrs({})
},
font: fontAttrs({}),
activebgcolor: {
valType: 'color',
dflt: constants.gripBgActiveColor
},
bgcolor: {
valType: 'color',
dflt: constants.railBgColor
},
bordercolor: {
valType: 'color',
dflt: constants.railBorderColor
},
borderwidth: {
valType: 'number',
min: 0,
dflt: constants.railBorderWidth
},
ticklen: {
valType: 'number',
min: 0,
dflt: constants.tickLength
},
tickcolor: {
valType: 'color',
dflt: constants.tickColor
},
tickwidth: {
valType: 'number',
min: 0,
dflt: 1
},
minorticklen: {
valType: 'number',
min: 0,
dflt: constants.minorTickLength
}
}), 'arraydraw', 'from-root');
/***/ }),
/***/ 60876:
/***/ (function(module) {
"use strict";
module.exports = {
// layout attribute name
name: 'sliders',
// class names
containerClassName: 'slider-container',
groupClassName: 'slider-group',
inputAreaClass: 'slider-input-area',
railRectClass: 'slider-rail-rect',
railTouchRectClass: 'slider-rail-touch-rect',
gripRectClass: 'slider-grip-rect',
tickRectClass: 'slider-tick-rect',
inputProxyClass: 'slider-input-proxy',
labelsClass: 'slider-labels',
labelGroupClass: 'slider-label-group',
labelClass: 'slider-label',
currentValueClass: 'slider-current-value',
railHeight: 5,
// DOM attribute name in button group keeping track
// of active update menu
menuIndexAttrName: 'slider-active-index',
// id root pass to Plots.autoMargin
autoMarginIdRoot: 'slider-',
// min item width / height
minWidth: 30,
minHeight: 30,
// padding around item text
textPadX: 40,
// arrow offset off right edge
arrowOffsetX: 4,
railRadius: 2,
railWidth: 5,
railBorder: 4,
railBorderWidth: 1,
railBorderColor: '#bec8d9',
railBgColor: '#f8fafc',
// The distance of the rail from the edge of the touchable area
// Slightly less than the step inset because of the curved edges
// of the rail
railInset: 8,
// The distance from the extremal tick marks to the edge of the
// touchable area. This is basically the same as the grip radius,
// but for other styles it wouldn't really need to be.
stepInset: 10,
gripRadius: 10,
gripWidth: 20,
gripHeight: 20,
gripBorder: 20,
gripBorderWidth: 1,
gripBorderColor: '#bec8d9',
gripBgColor: '#f6f8fa',
gripBgActiveColor: '#dbdde0',
labelPadding: 8,
labelOffset: 0,
tickWidth: 1,
tickColor: '#333',
tickOffset: 25,
tickLength: 7,
minorTickOffset: 25,
minorTickColor: '#333',
minorTickLength: 4,
// Extra space below the current value label:
currentValuePadding: 8,
currentValueInset: 0
};
/***/ }),
/***/ 8132:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleArrayContainerDefaults = __webpack_require__(51272);
var attributes = __webpack_require__(89861);
var constants = __webpack_require__(60876);
var name = constants.name;
var stepAttrs = attributes.steps;
module.exports = function slidersDefaults(layoutIn, layoutOut) {
handleArrayContainerDefaults(layoutIn, layoutOut, {
name: name,
handleItemDefaults: sliderDefaults
});
};
function sliderDefaults(sliderIn, sliderOut, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(sliderIn, sliderOut, attributes, attr, dflt);
}
var steps = handleArrayContainerDefaults(sliderIn, sliderOut, {
name: 'steps',
handleItemDefaults: stepDefaults
});
var stepCount = 0;
for (var i = 0; i < steps.length; i++) {
if (steps[i].visible) stepCount++;
}
var visible;
// If it has fewer than two options, it's not really a slider
if (stepCount < 2) visible = sliderOut.visible = false;else visible = coerce('visible');
if (!visible) return;
sliderOut._stepCount = stepCount;
var visSteps = sliderOut._visibleSteps = Lib.filterVisible(steps);
var active = coerce('active');
if (!(steps[active] || {}).visible) sliderOut.active = visSteps[0]._index;
coerce('x');
coerce('y');
Lib.noneOrAll(sliderIn, sliderOut, ['x', 'y']);
coerce('xanchor');
coerce('yanchor');
coerce('len');
coerce('lenmode');
coerce('pad.t');
coerce('pad.r');
coerce('pad.b');
coerce('pad.l');
Lib.coerceFont(coerce, 'font', layoutOut.font);
var currentValueIsVisible = coerce('currentvalue.visible');
if (currentValueIsVisible) {
coerce('currentvalue.xanchor');
coerce('currentvalue.prefix');
coerce('currentvalue.suffix');
coerce('currentvalue.offset');
Lib.coerceFont(coerce, 'currentvalue.font', sliderOut.font);
}
coerce('transition.duration');
coerce('transition.easing');
coerce('bgcolor');
coerce('activebgcolor');
coerce('bordercolor');
coerce('borderwidth');
coerce('ticklen');
coerce('tickwidth');
coerce('tickcolor');
coerce('minorticklen');
}
function stepDefaults(valueIn, valueOut) {
function coerce(attr, dflt) {
return Lib.coerce(valueIn, valueOut, stepAttrs, attr, dflt);
}
var visible;
if (valueIn.method !== 'skip' && !Array.isArray(valueIn.args)) {
visible = valueOut.visible = false;
} else visible = coerce('visible');
if (visible) {
coerce('method');
coerce('args');
var label = coerce('label', 'step-' + valueOut._index);
coerce('value', label);
coerce('execute');
}
}
/***/ }),
/***/ 79664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Plots = __webpack_require__(7316);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var svgTextUtils = __webpack_require__(72736);
var arrayEditor = (__webpack_require__(31780).arrayEditor);
var constants = __webpack_require__(60876);
var alignmentConstants = __webpack_require__(84284);
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;
module.exports = function draw(gd) {
var staticPlot = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
var sliderData = makeSliderData(fullLayout, gd);
// draw a container for *all* sliders:
var sliders = fullLayout._infolayer.selectAll('g.' + constants.containerClassName).data(sliderData.length > 0 ? [0] : []);
sliders.enter().append('g').classed(constants.containerClassName, true).style('cursor', staticPlot ? null : 'ew-resize');
function clearSlider(sliderOpts) {
if (sliderOpts._commandObserver) {
sliderOpts._commandObserver.remove();
delete sliderOpts._commandObserver;
}
// Most components don't need to explicitly remove autoMargin, because
// marginPushers does this - but slider updates don't go through
// a full replot so we need to explicitly remove it.
Plots.autoMargin(gd, autoMarginId(sliderOpts));
}
sliders.exit().each(function () {
d3.select(this).selectAll('g.' + constants.groupClassName).each(clearSlider);
}).remove();
// Return early if no menus visible:
if (sliderData.length === 0) return;
var sliderGroups = sliders.selectAll('g.' + constants.groupClassName).data(sliderData, keyFunction);
sliderGroups.enter().append('g').classed(constants.groupClassName, true);
sliderGroups.exit().each(clearSlider).remove();
// Find the dimensions of the sliders:
for (var i = 0; i < sliderData.length; i++) {
var sliderOpts = sliderData[i];
findDimensions(gd, sliderOpts);
}
sliderGroups.each(function (sliderOpts) {
var gSlider = d3.select(this);
computeLabelSteps(sliderOpts);
Plots.manageCommandObserver(gd, sliderOpts, sliderOpts._visibleSteps, function (data) {
// NB: Same as below. This is *not* always the same as sliderOpts since
// if a new set of steps comes in, the reference in this callback would
// be invalid. We need to refetch it from the slider group, which is
// the join data that creates this slider. So if this slider still exists,
// the group should be valid, *to the best of my knowledge.* If not,
// we'd have to look it up by d3 data join index/key.
var opts = gSlider.data()[0];
if (opts.active === data.index) return;
if (opts._dragging) return;
setActive(gd, gSlider, opts, data.index, false, true);
});
drawSlider(gd, d3.select(this), sliderOpts);
});
};
function autoMarginId(sliderOpts) {
return constants.autoMarginIdRoot + sliderOpts._index;
}
// This really only just filters by visibility:
function makeSliderData(fullLayout, gd) {
var contOpts = fullLayout[constants.name];
var sliderData = [];
for (var i = 0; i < contOpts.length; i++) {
var item = contOpts[i];
if (!item.visible) continue;
item._gd = gd;
sliderData.push(item);
}
return sliderData;
}
// This is set in the defaults step:
function keyFunction(opts) {
return opts._index;
}
// Compute the dimensions (mutates sliderOpts):
function findDimensions(gd, sliderOpts) {
var sliderLabels = Drawing.tester.selectAll('g.' + constants.labelGroupClass).data(sliderOpts._visibleSteps);
sliderLabels.enter().append('g').classed(constants.labelGroupClass, true);
// loop over fake buttons to find width / height
var maxLabelWidth = 0;
var labelHeight = 0;
sliderLabels.each(function (stepOpts) {
var labelGroup = d3.select(this);
var text = drawLabel(labelGroup, {
step: stepOpts
}, sliderOpts);
var textNode = text.node();
if (textNode) {
var bBox = Drawing.bBox(textNode);
labelHeight = Math.max(labelHeight, bBox.height);
maxLabelWidth = Math.max(maxLabelWidth, bBox.width);
}
});
sliderLabels.remove();
var dims = sliderOpts._dims = {};
dims.inputAreaWidth = Math.max(constants.railWidth, constants.gripHeight);
// calculate some overall dimensions - some of these are needed for
// calculating the currentValue dimensions
var graphSize = gd._fullLayout._size;
dims.lx = graphSize.l + graphSize.w * sliderOpts.x;
dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y);
if (sliderOpts.lenmode === 'fraction') {
// fraction:
dims.outerLength = Math.round(graphSize.w * sliderOpts.len);
} else {
// pixels:
dims.outerLength = sliderOpts.len;
}
// The length of the rail, *excluding* padding on either end:
dims.inputAreaStart = 0;
dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r);
var textableInputLength = dims.inputAreaLength - 2 * constants.stepInset;
var availableSpacePerLabel = textableInputLength / (sliderOpts._stepCount - 1);
var computedSpacePerLabel = maxLabelWidth + constants.labelPadding;
dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel));
dims.labelHeight = labelHeight;
// loop over all possible values for currentValue to find the
// area we need for it
dims.currentValueMaxWidth = 0;
dims.currentValueHeight = 0;
dims.currentValueTotalHeight = 0;
dims.currentValueMaxLines = 1;
if (sliderOpts.currentvalue.visible) {
// Get the dimensions of the current value label:
var dummyGroup = Drawing.tester.append('g');
sliderLabels.each(function (stepOpts) {
var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label);
var curValSize = curValPrefix.node() && Drawing.bBox(curValPrefix.node()) || {
width: 0,
height: 0
};
var lines = svgTextUtils.lineCount(curValPrefix);
dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width));
dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height));
dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines);
});
dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset;
dummyGroup.remove();
}
dims.height = dims.currentValueTotalHeight + constants.tickOffset + sliderOpts.ticklen + constants.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b;
var xanchor = 'left';
if (Lib.isRightAnchor(sliderOpts)) {
dims.lx -= dims.outerLength;
xanchor = 'right';
}
if (Lib.isCenterAnchor(sliderOpts)) {
dims.lx -= dims.outerLength / 2;
xanchor = 'center';
}
var yanchor = 'top';
if (Lib.isBottomAnchor(sliderOpts)) {
dims.ly -= dims.height;
yanchor = 'bottom';
}
if (Lib.isMiddleAnchor(sliderOpts)) {
dims.ly -= dims.height / 2;
yanchor = 'middle';
}
dims.outerLength = Math.ceil(dims.outerLength);
dims.height = Math.ceil(dims.height);
dims.lx = Math.round(dims.lx);
dims.ly = Math.round(dims.ly);
var marginOpts = {
y: sliderOpts.y,
b: dims.height * FROM_BR[yanchor],
t: dims.height * FROM_TL[yanchor]
};
if (sliderOpts.lenmode === 'fraction') {
marginOpts.l = 0;
marginOpts.xl = sliderOpts.x - sliderOpts.len * FROM_TL[xanchor];
marginOpts.r = 0;
marginOpts.xr = sliderOpts.x + sliderOpts.len * FROM_BR[xanchor];
} else {
marginOpts.x = sliderOpts.x;
marginOpts.l = dims.outerLength * FROM_TL[xanchor];
marginOpts.r = dims.outerLength * FROM_BR[xanchor];
}
Plots.autoMargin(gd, autoMarginId(sliderOpts), marginOpts);
}
function drawSlider(gd, sliderGroup, sliderOpts) {
// This is related to the other long notes in this file regarding what happens
// when slider steps disappear. This particular fix handles what happens when
// the *current* slider step is removed. The drawing functions will error out
// when they fail to find it, so the fix for now is that it will just draw the
// slider in the first position but will not execute the command.
if (!(sliderOpts.steps[sliderOpts.active] || {}).visible) {
sliderOpts.active = sliderOpts._visibleSteps[0]._index;
}
// These are carefully ordered for proper z-ordering:
sliderGroup.call(drawCurrentValue, sliderOpts).call(drawRail, sliderOpts).call(drawLabelGroup, sliderOpts).call(drawTicks, sliderOpts).call(drawTouchRect, gd, sliderOpts).call(drawGrip, gd, sliderOpts);
var dims = sliderOpts._dims;
// Position the rectangle:
Drawing.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t);
sliderGroup.call(setGripPosition, sliderOpts, false);
sliderGroup.call(drawCurrentValue, sliderOpts);
}
function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) {
if (!sliderOpts.currentvalue.visible) return;
var dims = sliderOpts._dims;
var x0, textAnchor;
switch (sliderOpts.currentvalue.xanchor) {
case 'right':
// This is anchored left and adjusted by the width of the longest label
// so that the prefix doesn't move. The goal of this is to emphasize
// what's actually changing and make the update less distracting.
x0 = dims.inputAreaLength - constants.currentValueInset - dims.currentValueMaxWidth;
textAnchor = 'left';
break;
case 'center':
x0 = dims.inputAreaLength * 0.5;
textAnchor = 'middle';
break;
default:
x0 = constants.currentValueInset;
textAnchor = 'left';
}
var text = Lib.ensureSingle(sliderGroup, 'text', constants.labelClass, function (s) {
s.attr({
'text-anchor': textAnchor,
'data-notex': 1
});
});
var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : '';
if (typeof valueOverride === 'string') {
str += valueOverride;
} else {
var curVal = sliderOpts.steps[sliderOpts.active].label;
var _meta = sliderOpts._gd._fullLayout._meta;
if (_meta) curVal = Lib.templateString(curVal, _meta);
str += curVal;
}
if (sliderOpts.currentvalue.suffix) {
str += sliderOpts.currentvalue.suffix;
}
text.call(Drawing.font, sliderOpts.currentvalue.font).text(str).call(svgTextUtils.convertToTspans, sliderOpts._gd);
var lines = svgTextUtils.lineCount(text);
var y0 = (dims.currentValueMaxLines + 1 - lines) * sliderOpts.currentvalue.font.size * LINE_SPACING;
svgTextUtils.positionText(text, x0, y0);
return text;
}
function drawGrip(sliderGroup, gd, sliderOpts) {
var grip = Lib.ensureSingle(sliderGroup, 'rect', constants.gripRectClass, function (s) {
s.call(attachGripEvents, gd, sliderGroup, sliderOpts).style('pointer-events', 'all');
});
grip.attr({
width: constants.gripWidth,
height: constants.gripHeight,
rx: constants.gripRadius,
ry: constants.gripRadius
}).call(Color.stroke, sliderOpts.bordercolor).call(Color.fill, sliderOpts.bgcolor).style('stroke-width', sliderOpts.borderwidth + 'px');
}
function drawLabel(item, data, sliderOpts) {
var text = Lib.ensureSingle(item, 'text', constants.labelClass, function (s) {
s.attr({
'text-anchor': 'middle',
'data-notex': 1
});
});
var tx = data.step.label;
var _meta = sliderOpts._gd._fullLayout._meta;
if (_meta) tx = Lib.templateString(tx, _meta);
text.call(Drawing.font, sliderOpts.font).text(tx).call(svgTextUtils.convertToTspans, sliderOpts._gd);
return text;
}
function drawLabelGroup(sliderGroup, sliderOpts) {
var labels = Lib.ensureSingle(sliderGroup, 'g', constants.labelsClass);
var dims = sliderOpts._dims;
var labelItems = labels.selectAll('g.' + constants.labelGroupClass).data(dims.labelSteps);
labelItems.enter().append('g').classed(constants.labelGroupClass, true);
labelItems.exit().remove();
labelItems.each(function (d) {
var item = d3.select(this);
item.call(drawLabel, d, sliderOpts);
Drawing.setTranslate(item, normalizedValueToPosition(sliderOpts, d.fraction), constants.tickOffset + sliderOpts.ticklen +
// position is the baseline of the top line of text only, even
// if the label spans multiple lines
sliderOpts.font.size * LINE_SPACING + constants.labelOffset + dims.currentValueTotalHeight);
});
}
function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) {
var quantizedPosition = Math.round(normalizedPosition * (sliderOpts._stepCount - 1));
var quantizedIndex = sliderOpts._visibleSteps[quantizedPosition]._index;
if (quantizedIndex !== sliderOpts.active) {
setActive(gd, sliderGroup, sliderOpts, quantizedIndex, true, doTransition);
}
}
function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) {
var previousActive = sliderOpts.active;
sliderOpts.active = index;
// due to templating, it's possible this slider doesn't even exist yet
arrayEditor(gd.layout, constants.name, sliderOpts).applyUpdate('active', index);
var step = sliderOpts.steps[sliderOpts.active];
sliderGroup.call(setGripPosition, sliderOpts, doTransition);
sliderGroup.call(drawCurrentValue, sliderOpts);
gd.emit('plotly_sliderchange', {
slider: sliderOpts,
step: sliderOpts.steps[sliderOpts.active],
interaction: doCallback,
previousActive: previousActive
});
if (step && step.method && doCallback) {
if (sliderGroup._nextMethod) {
// If we've already queued up an update, just overwrite it with the most recent:
sliderGroup._nextMethod.step = step;
sliderGroup._nextMethod.doCallback = doCallback;
sliderGroup._nextMethod.doTransition = doTransition;
} else {
sliderGroup._nextMethod = {
step: step,
doCallback: doCallback,
doTransition: doTransition
};
sliderGroup._nextMethodRaf = window.requestAnimationFrame(function () {
var _step = sliderGroup._nextMethod.step;
if (!_step.method) return;
if (_step.execute) {
Plots.executeAPICommand(gd, _step.method, _step.args);
}
sliderGroup._nextMethod = null;
sliderGroup._nextMethodRaf = null;
});
}
}
}
function attachGripEvents(item, gd, sliderGroup) {
if (gd._context.staticPlot) return;
var node = sliderGroup.node();
var $gd = d3.select(gd);
// NB: This is *not* the same as sliderOpts itself! These callbacks
// are in a closure so this array won't actually be correct if the
// steps have changed since this was initialized. The sliderGroup,
// however, has not changed since that *is* the slider, so it must
// be present to receive mouse events.
function getSliderOpts() {
return sliderGroup.data()[0];
}
function mouseDownHandler() {
var sliderOpts = getSliderOpts();
gd.emit('plotly_sliderstart', {
slider: sliderOpts
});
var grip = sliderGroup.select('.' + constants.gripRectClass);
d3.event.stopPropagation();
d3.event.preventDefault();
grip.call(Color.fill, sliderOpts.activebgcolor);
var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true);
sliderOpts._dragging = true;
function mouseMoveHandler() {
var sliderOpts = getSliderOpts();
var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false);
}
$gd.on('mousemove', mouseMoveHandler);
$gd.on('touchmove', mouseMoveHandler);
function mouseUpHandler() {
var sliderOpts = getSliderOpts();
sliderOpts._dragging = false;
grip.call(Color.fill, sliderOpts.bgcolor);
$gd.on('mouseup', null);
$gd.on('mousemove', null);
$gd.on('touchend', null);
$gd.on('touchmove', null);
gd.emit('plotly_sliderend', {
slider: sliderOpts,
step: sliderOpts.steps[sliderOpts.active]
});
}
$gd.on('mouseup', mouseUpHandler);
$gd.on('touchend', mouseUpHandler);
}
item.on('mousedown', mouseDownHandler);
item.on('touchstart', mouseDownHandler);
}
function drawTicks(sliderGroup, sliderOpts) {
var tick = sliderGroup.selectAll('rect.' + constants.tickRectClass).data(sliderOpts._visibleSteps);
var dims = sliderOpts._dims;
tick.enter().append('rect').classed(constants.tickRectClass, true);
tick.exit().remove();
tick.attr({
width: sliderOpts.tickwidth + 'px',
'shape-rendering': 'crispEdges'
});
tick.each(function (d, i) {
var isMajor = i % dims.labelStride === 0;
var item = d3.select(this);
item.attr({
height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen
}).call(Color.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor);
Drawing.setTranslate(item, normalizedValueToPosition(sliderOpts, i / (sliderOpts._stepCount - 1)) - 0.5 * sliderOpts.tickwidth, (isMajor ? constants.tickOffset : constants.minorTickOffset) + dims.currentValueTotalHeight);
});
}
function computeLabelSteps(sliderOpts) {
var dims = sliderOpts._dims;
dims.labelSteps = [];
var nsteps = sliderOpts._stepCount;
for (var i = 0; i < nsteps; i += dims.labelStride) {
dims.labelSteps.push({
fraction: i / (nsteps - 1),
step: sliderOpts._visibleSteps[i]
});
}
}
function setGripPosition(sliderGroup, sliderOpts, doTransition) {
var grip = sliderGroup.select('rect.' + constants.gripRectClass);
var quantizedIndex = 0;
for (var i = 0; i < sliderOpts._stepCount; i++) {
if (sliderOpts._visibleSteps[i]._index === sliderOpts.active) {
quantizedIndex = i;
break;
}
}
var x = normalizedValueToPosition(sliderOpts, quantizedIndex / (sliderOpts._stepCount - 1));
// If this is true, then *this component* is already invoking its own command
// and has triggered its own animation.
if (sliderOpts._invokingCommand) return;
var el = grip;
if (doTransition && sliderOpts.transition.duration > 0) {
el = el.transition().duration(sliderOpts.transition.duration).ease(sliderOpts.transition.easing);
}
// Drawing.setTranslate doesn't work here because of the transition duck-typing.
// It's also not necessary because there are no other transitions to preserve.
el.attr('transform', strTranslate(x - constants.gripWidth * 0.5, sliderOpts._dims.currentValueTotalHeight));
}
// Convert a number from [0-1] to a pixel position relative to the slider group container:
function normalizedValueToPosition(sliderOpts, normalizedPosition) {
var dims = sliderOpts._dims;
return dims.inputAreaStart + constants.stepInset + (dims.inputAreaLength - 2 * constants.stepInset) * Math.min(1, Math.max(0, normalizedPosition));
}
// Convert a position relative to the slider group to a nubmer in [0, 1]
function positionToNormalizedValue(sliderOpts, position) {
var dims = sliderOpts._dims;
return Math.min(1, Math.max(0, (position - constants.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * constants.stepInset - 2 * dims.inputAreaStart)));
}
function drawTouchRect(sliderGroup, gd, sliderOpts) {
var dims = sliderOpts._dims;
var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railTouchRectClass, function (s) {
s.call(attachGripEvents, gd, sliderGroup, sliderOpts).style('pointer-events', 'all');
});
rect.attr({
width: dims.inputAreaLength,
height: Math.max(dims.inputAreaWidth, constants.tickOffset + sliderOpts.ticklen + dims.labelHeight)
}).call(Color.fill, sliderOpts.bgcolor).attr('opacity', 0);
Drawing.setTranslate(rect, 0, dims.currentValueTotalHeight);
}
function drawRail(sliderGroup, sliderOpts) {
var dims = sliderOpts._dims;
var computedLength = dims.inputAreaLength - constants.railInset * 2;
var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railRectClass);
rect.attr({
width: computedLength,
height: constants.railWidth,
rx: constants.railRadius,
ry: constants.railRadius,
'shape-rendering': 'crispEdges'
}).call(Color.stroke, sliderOpts.bordercolor).call(Color.fill, sliderOpts.bgcolor).style('stroke-width', sliderOpts.borderwidth + 'px');
Drawing.setTranslate(rect, constants.railInset, (dims.inputAreaWidth - constants.railWidth) * 0.5 + dims.currentValueTotalHeight);
}
/***/ }),
/***/ 97544:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(60876);
module.exports = {
moduleType: 'component',
name: constants.name,
layoutAttributes: __webpack_require__(89861),
supplyLayoutDefaults: __webpack_require__(8132),
draw: __webpack_require__(79664)
};
/***/ }),
/***/ 81668:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var isNumeric = __webpack_require__(38248);
var Plots = __webpack_require__(7316);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var svgTextUtils = __webpack_require__(72736);
var interactConstants = __webpack_require__(13448);
var OPPOSITE_SIDE = (__webpack_require__(84284).OPPOSITE_SIDE);
var numStripRE = / [XY][0-9]* /;
var SUBTITLE_PADDING_MATHJAX_EM = 1.6;
var SUBTITLE_PADDING_EM = 1.6;
/**
* Titles - (re)draw titles on the axes and plot:
* @param {DOM element} gd - the graphDiv
* @param {string} titleClass - the css class of this title
* @param {object} options - how and what to draw
* propContainer - the layout object containing `title` and `titlefont`
* attributes that apply to this title
* propName - the full name of the title property (for Plotly.relayout)
* [traceIndex] - include only if this property applies to one trace
* (such as a colorbar title) - then editing pipes to Plotly.restyle
* instead of Plotly.relayout
* placeholder - placeholder text for an empty editable title
* [avoid] {object} - include if this title should move to avoid other elements
* selection - d3 selection of elements to avoid
* side - which direction to move if there is a conflict
* [offsetLeft] - if these elements are subject to a translation
* wrt the title element
* [offsetTop]
* attributes {object} - position and alignment attributes
* x - pixels
* y - pixels
* text-anchor - start|middle|end
* transform {object} - how to transform the title after positioning
* rotate - degrees
* offset - shift up/down in the rotated frame (unused?)
* containerGroup - if an svg element already exists to hold this
* title, include here. Otherwise it will go in fullLayout._infolayer
* _meta {object (optional} - meta key-value to for title with
* Lib.templateString, default to fullLayout._meta, if not provided
*
* @return {selection} d3 selection of title container group
*/
function draw(gd, titleClass, options) {
var fullLayout = gd._fullLayout;
var cont = options.propContainer;
var prop = options.propName;
var placeholder = options.placeholder;
var traceIndex = options.traceIndex;
var avoid = options.avoid || {};
var attributes = options.attributes;
var transform = options.transform;
var group = options.containerGroup;
var opacity = 1;
var title = cont.title;
var txt = (title && title.text ? title.text : '').trim();
var titleIsPlaceholder = false;
var font = title && title.font ? title.font : {};
var fontFamily = font.family;
var fontSize = font.size;
var fontColor = font.color;
var fontWeight = font.weight;
var fontStyle = font.style;
var fontVariant = font.variant;
var fontTextcase = font.textcase;
var fontLineposition = font.lineposition;
var fontShadow = font.shadow;
// Get subtitle properties
var subtitleProp = options.subtitlePropName;
var subtitleEnabled = !!subtitleProp;
var subtitlePlaceholder = options.subtitlePlaceholder;
var subtitle = (cont.title || {}).subtitle || {
text: '',
font: {}
};
var subtitleTxt = subtitle.text.trim();
var subtitleIsPlaceholder = false;
var subtitleOpacity = 1;
var subtitleFont = subtitle.font;
var subFontFamily = subtitleFont.family;
var subFontSize = subtitleFont.size;
var subFontColor = subtitleFont.color;
var subFontWeight = subtitleFont.weight;
var subFontStyle = subtitleFont.style;
var subFontVariant = subtitleFont.variant;
var subFontTextcase = subtitleFont.textcase;
var subFontLineposition = subtitleFont.lineposition;
var subFontShadow = subtitleFont.shadow;
// only make this title editable if we positively identify its property
// as one that has editing enabled.
// Subtitle is editable if and only if title is editable
var editAttr;
if (prop === 'title.text') editAttr = 'titleText';else if (prop.indexOf('axis') !== -1) editAttr = 'axisTitleText';else if (prop.indexOf('colorbar' !== -1)) editAttr = 'colorbarTitleText';
var editable = gd._context.edits[editAttr];
function matchesPlaceholder(text, placeholder) {
if (text === undefined || placeholder === undefined) return false;
// look for placeholder text while stripping out numbers from eg X2, Y3
// this is just for backward compatibility with the old version that had
// "Click to enter X2 title" and may have gotten saved in some old plots,
// we don't want this to show up when these are displayed.
return text.replace(numStripRE, ' % ') === placeholder.replace(numStripRE, ' % ');
}
if (txt === '') opacity = 0;else if (matchesPlaceholder(txt, placeholder)) {
if (!editable) txt = '';
opacity = 0.2;
titleIsPlaceholder = true;
}
if (subtitleEnabled) {
if (subtitleTxt === '') subtitleOpacity = 0;else if (matchesPlaceholder(subtitleTxt, subtitlePlaceholder)) {
if (!editable) subtitleTxt = '';
subtitleOpacity = 0.2;
subtitleIsPlaceholder = true;
}
}
if (options._meta) {
txt = Lib.templateString(txt, options._meta);
} else if (fullLayout._meta) {
txt = Lib.templateString(txt, fullLayout._meta);
}
var elShouldExist = txt || subtitleTxt || editable;
var hColorbarMoveTitle;
if (!group) {
group = Lib.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass);
hColorbarMoveTitle = fullLayout._hColorbarMoveTitle;
}
var el = group.selectAll('text.' + titleClass).data(elShouldExist ? [0] : []);
el.enter().append('text');
el.text(txt)
// this is hacky, but convertToTspans uses the class
// to determine whether to rotate mathJax...
// so we need to clear out any old class and put the
// correct one (only relevant for colorbars, at least
// for now) - ie don't use .classed
.attr('class', titleClass);
el.exit().remove();
var subtitleEl = null;
var subtitleClass = titleClass + '-subtitle';
var subtitleElShouldExist = subtitleTxt || editable;
if (subtitleEnabled && subtitleElShouldExist) {
subtitleEl = group.selectAll('text.' + subtitleClass).data(subtitleElShouldExist ? [0] : []);
subtitleEl.enter().append('text');
subtitleEl.text(subtitleTxt).attr('class', subtitleClass);
subtitleEl.exit().remove();
}
if (!elShouldExist) return group;
function titleLayout(titleEl, subtitleEl) {
Lib.syncOrAsync([drawTitle, scootTitle], {
title: titleEl,
subtitle: subtitleEl
});
}
function drawTitle(titleAndSubtitleEls) {
var titleEl = titleAndSubtitleEls.title;
var subtitleEl = titleAndSubtitleEls.subtitle;
var transformVal;
if (!transform && hColorbarMoveTitle) {
transform = {};
}
if (transform) {
transformVal = '';
if (transform.rotate) {
transformVal += 'rotate(' + [transform.rotate, attributes.x, attributes.y] + ')';
}
if (transform.offset || hColorbarMoveTitle) {
transformVal += strTranslate(0, (transform.offset || 0) - (hColorbarMoveTitle || 0));
}
} else {
transformVal = null;
}
titleEl.attr('transform', transformVal);
// Callback to adjust the subtitle position after mathjax is rendered
// Mathjax is rendered asynchronously, which is why this step needs to be
// passed as a callback
function adjustSubtitlePosition(titleElMathGroup) {
if (!titleElMathGroup) return;
var subtitleElement = d3.select(titleElMathGroup.node().parentNode).select('.' + subtitleClass);
if (!subtitleElement.empty()) {
var titleElMathBbox = titleElMathGroup.node().getBBox();
if (titleElMathBbox.height) {
// Position subtitle based on bottom of Mathjax title
var subtitleY = titleElMathBbox.y + titleElMathBbox.height + SUBTITLE_PADDING_MATHJAX_EM * subFontSize;
subtitleElement.attr('y', subtitleY);
}
}
}
titleEl.style('opacity', opacity * Color.opacity(fontColor)).call(Drawing.font, {
color: Color.rgb(fontColor),
size: d3.round(fontSize, 2),
family: fontFamily,
weight: fontWeight,
style: fontStyle,
variant: fontVariant,
textcase: fontTextcase,
shadow: fontShadow,
lineposition: fontLineposition
}).attr(attributes).call(svgTextUtils.convertToTspans, gd, adjustSubtitlePosition);
if (subtitleEl) {
// Set subtitle y position based on bottom of title
// We need to check the Mathjax group as well, in case the Mathjax
// has already rendered
var titleElMathGroup = group.select('.' + titleClass + '-math-group');
var titleElBbox = titleEl.node().getBBox();
var titleElMathBbox = titleElMathGroup.node() ? titleElMathGroup.node().getBBox() : undefined;
var subtitleY = titleElMathBbox ? titleElMathBbox.y + titleElMathBbox.height + SUBTITLE_PADDING_MATHJAX_EM * subFontSize : titleElBbox.y + titleElBbox.height + SUBTITLE_PADDING_EM * subFontSize;
var subtitleAttributes = Lib.extendFlat({}, attributes, {
y: subtitleY
});
subtitleEl.attr('transform', transformVal);
subtitleEl.style('opacity', subtitleOpacity * Color.opacity(subFontColor)).call(Drawing.font, {
color: Color.rgb(subFontColor),
size: d3.round(subFontSize, 2),
family: subFontFamily,
weight: subFontWeight,
style: subFontStyle,
variant: subFontVariant,
textcase: subFontTextcase,
shadow: subFontShadow,
lineposition: subFontLineposition
}).attr(subtitleAttributes).call(svgTextUtils.convertToTspans, gd);
}
return Plots.previousPromises(gd);
}
function scootTitle(titleAndSubtitleEls) {
var titleElIn = titleAndSubtitleEls.title;
var titleGroup = d3.select(titleElIn.node().parentNode);
if (avoid && avoid.selection && avoid.side && txt) {
titleGroup.attr('transform', null);
// move toward avoid.side (= left, right, top, bottom) if needed
// can include pad (pixels, default 2)
var backside = OPPOSITE_SIDE[avoid.side];
var shiftSign = avoid.side === 'left' || avoid.side === 'top' ? -1 : 1;
var pad = isNumeric(avoid.pad) ? avoid.pad : 2;
var titlebb = Drawing.bBox(titleGroup.node());
// Account for reservedMargins
var reservedMargins = {
t: 0,
b: 0,
l: 0,
r: 0
};
var margins = gd._fullLayout._reservedMargin;
for (var key in margins) {
for (var side in margins[key]) {
var val = margins[key][side];
reservedMargins[side] = Math.max(reservedMargins[side], val);
}
}
var paperbb = {
left: reservedMargins.l,
top: reservedMargins.t,
right: fullLayout.width - reservedMargins.r,
bottom: fullLayout.height - reservedMargins.b
};
var maxshift = avoid.maxShift || shiftSign * (paperbb[avoid.side] - titlebb[avoid.side]);
var shift = 0;
// Prevent the title going off the paper
if (maxshift < 0) {
shift = maxshift;
} else {
// so we don't have to offset each avoided element,
// give the title the opposite offset
var offsetLeft = avoid.offsetLeft || 0;
var offsetTop = avoid.offsetTop || 0;
titlebb.left -= offsetLeft;
titlebb.right -= offsetLeft;
titlebb.top -= offsetTop;
titlebb.bottom -= offsetTop;
// iterate over a set of elements (avoid.selection)
// to avoid collisions with
avoid.selection.each(function () {
var avoidbb = Drawing.bBox(this);
if (Lib.bBoxIntersect(titlebb, avoidbb, pad)) {
shift = Math.max(shift, shiftSign * (avoidbb[avoid.side] - titlebb[backside]) + pad);
}
});
shift = Math.min(maxshift, shift);
// Keeping track of this for calculation of full axis size if needed
cont._titleScoot = Math.abs(shift);
}
if (shift > 0 || maxshift < 0) {
var shiftTemplate = {
left: [-shift, 0],
right: [shift, 0],
top: [0, -shift],
bottom: [0, shift]
}[avoid.side];
titleGroup.attr('transform', strTranslate(shiftTemplate[0], shiftTemplate[1]));
}
}
}
el.call(titleLayout, subtitleEl);
function setPlaceholder(element, placeholderText) {
element.text(placeholderText).on('mouseover.opacity', function () {
d3.select(this).transition().duration(interactConstants.SHOW_PLACEHOLDER).style('opacity', 1);
}).on('mouseout.opacity', function () {
d3.select(this).transition().duration(interactConstants.HIDE_PLACEHOLDER).style('opacity', 0);
});
}
if (editable) {
if (!txt) {
setPlaceholder(el, placeholder);
titleIsPlaceholder = true;
} else el.on('.opacity', null);
el.call(svgTextUtils.makeEditable, {
gd: gd
}).on('edit', function (text) {
if (traceIndex !== undefined) {
Registry.call('_guiRestyle', gd, prop, text, traceIndex);
} else {
Registry.call('_guiRelayout', gd, prop, text);
}
}).on('cancel', function () {
this.text(this.attr('data-unformatted')).call(titleLayout);
}).on('input', function (d) {
this.text(d || ' ').call(svgTextUtils.positionText, attributes.x, attributes.y);
});
if (subtitleEnabled) {
// Adjust subtitle position now that title placeholder has been added
// Only adjust if subtitle is enabled and title text was originally empty
if (subtitleEnabled && !txt) {
var titleElBbox = el.node().getBBox();
var subtitleY = titleElBbox.y + titleElBbox.height + SUBTITLE_PADDING_EM * subFontSize;
subtitleEl.attr('y', subtitleY);
}
if (!subtitleTxt) {
setPlaceholder(subtitleEl, subtitlePlaceholder);
subtitleIsPlaceholder = true;
} else subtitleEl.on('.opacity', null);
subtitleEl.call(svgTextUtils.makeEditable, {
gd: gd
}).on('edit', function (text) {
Registry.call('_guiRelayout', gd, 'title.subtitle.text', text);
}).on('cancel', function () {
this.text(this.attr('data-unformatted')).call(titleLayout);
}).on('input', function (d) {
this.text(d || ' ').call(svgTextUtils.positionText, subtitleEl.attr('x'), subtitleEl.attr('y'));
});
}
}
el.classed('js-placeholder', titleIsPlaceholder);
if (subtitleEl) subtitleEl.classed('js-placeholder', subtitleIsPlaceholder);
return group;
}
module.exports = {
draw: draw,
SUBTITLE_PADDING_EM: SUBTITLE_PADDING_EM,
SUBTITLE_PADDING_MATHJAX_EM: SUBTITLE_PADDING_MATHJAX_EM
};
/***/ }),
/***/ 88444:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var colorAttrs = __webpack_require__(22548);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var padAttrs = __webpack_require__(66741);
var templatedArray = (__webpack_require__(31780).templatedArray);
var buttonsAttrs = templatedArray('button', {
visible: {
valType: 'boolean'
},
method: {
valType: 'enumerated',
values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
dflt: 'restyle'
},
args: {
valType: 'info_array',
freeLength: true,
items: [{
valType: 'any'
}, {
valType: 'any'
}, {
valType: 'any'
}]
},
args2: {
valType: 'info_array',
freeLength: true,
items: [{
valType: 'any'
}, {
valType: 'any'
}, {
valType: 'any'
}]
},
label: {
valType: 'string',
dflt: ''
},
execute: {
valType: 'boolean',
dflt: true
}
});
module.exports = overrideAll(templatedArray('updatemenu', {
_arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],
visible: {
valType: 'boolean'
},
type: {
valType: 'enumerated',
values: ['dropdown', 'buttons'],
dflt: 'dropdown'
},
direction: {
valType: 'enumerated',
values: ['left', 'right', 'up', 'down'],
dflt: 'down'
},
active: {
valType: 'integer',
min: -1,
dflt: 0
},
showactive: {
valType: 'boolean',
dflt: true
},
buttons: buttonsAttrs,
x: {
valType: 'number',
min: -2,
max: 3,
dflt: -0.05
},
xanchor: {
valType: 'enumerated',
values: ['auto', 'left', 'center', 'right'],
dflt: 'right'
},
y: {
valType: 'number',
min: -2,
max: 3,
dflt: 1
},
yanchor: {
valType: 'enumerated',
values: ['auto', 'top', 'middle', 'bottom'],
dflt: 'top'
},
pad: extendFlat(padAttrs({
editType: 'arraydraw'
}), {}),
font: fontAttrs({}),
bgcolor: {
valType: 'color'
},
bordercolor: {
valType: 'color',
dflt: colorAttrs.borderLine
},
borderwidth: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'arraydraw'
}
}), 'arraydraw', 'from-root');
/***/ }),
/***/ 73712:
/***/ (function(module) {
"use strict";
module.exports = {
// layout attribute name
name: 'updatemenus',
// class names
containerClassName: 'updatemenu-container',
headerGroupClassName: 'updatemenu-header-group',
headerClassName: 'updatemenu-header',
headerArrowClassName: 'updatemenu-header-arrow',
dropdownButtonGroupClassName: 'updatemenu-dropdown-button-group',
dropdownButtonClassName: 'updatemenu-dropdown-button',
buttonClassName: 'updatemenu-button',
itemRectClassName: 'updatemenu-item-rect',
itemTextClassName: 'updatemenu-item-text',
// DOM attribute name in button group keeping track
// of active update menu
menuIndexAttrName: 'updatemenu-active-index',
// id root pass to Plots.autoMargin
autoMarginIdRoot: 'updatemenu-',
// options when 'active: -1'
blankHeaderOpts: {
label: ' '
},
// min item width / height
minWidth: 30,
minHeight: 30,
// padding around item text
textPadX: 24,
arrowPadX: 16,
// item rect radii
rx: 2,
ry: 2,
// item text x offset off left edge
textOffsetX: 12,
// item text y offset (w.r.t. middle)
textOffsetY: 3,
// arrow offset off right edge
arrowOffsetX: 4,
// gap between header and buttons
gapButtonHeader: 5,
// gap between between buttons
gapButton: 2,
// color given to active buttons
activeColor: '#F4FAFF',
// color given to hovered buttons
hoverColor: '#F4FAFF',
// symbol for menu open arrow
arrowSymbol: {
left: '◄',
right: '►',
up: '▲',
down: '▼'
}
};
/***/ }),
/***/ 91384:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleArrayContainerDefaults = __webpack_require__(51272);
var attributes = __webpack_require__(88444);
var constants = __webpack_require__(73712);
var name = constants.name;
var buttonAttrs = attributes.buttons;
module.exports = function updateMenusDefaults(layoutIn, layoutOut) {
var opts = {
name: name,
handleItemDefaults: menuDefaults
};
handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};
function menuDefaults(menuIn, menuOut, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(menuIn, menuOut, attributes, attr, dflt);
}
var buttons = handleArrayContainerDefaults(menuIn, menuOut, {
name: 'buttons',
handleItemDefaults: buttonDefaults
});
var visible = coerce('visible', buttons.length > 0);
if (!visible) return;
coerce('active');
coerce('direction');
coerce('type');
coerce('showactive');
coerce('x');
coerce('y');
Lib.noneOrAll(menuIn, menuOut, ['x', 'y']);
coerce('xanchor');
coerce('yanchor');
coerce('pad.t');
coerce('pad.r');
coerce('pad.b');
coerce('pad.l');
Lib.coerceFont(coerce, 'font', layoutOut.font);
coerce('bgcolor', layoutOut.paper_bgcolor);
coerce('bordercolor');
coerce('borderwidth');
}
function buttonDefaults(buttonIn, buttonOut) {
function coerce(attr, dflt) {
return Lib.coerce(buttonIn, buttonOut, buttonAttrs, attr, dflt);
}
var visible = coerce('visible', buttonIn.method === 'skip' || Array.isArray(buttonIn.args));
if (visible) {
coerce('method');
coerce('args');
coerce('args2');
coerce('label');
coerce('execute');
}
}
/***/ }),
/***/ 14420:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Plots = __webpack_require__(7316);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var svgTextUtils = __webpack_require__(72736);
var arrayEditor = (__webpack_require__(31780).arrayEditor);
var LINE_SPACING = (__webpack_require__(84284).LINE_SPACING);
var constants = __webpack_require__(73712);
var ScrollBox = __webpack_require__(37400);
module.exports = function draw(gd) {
var fullLayout = gd._fullLayout;
var menuData = Lib.filterVisible(fullLayout[constants.name]);
/* Update menu data is bound to the header-group.
* The items in the header group are always present.
*
* Upon clicking on a header its corresponding button
* data is bound to the button-group.
*
* We draw all headers in one group before all buttons
* so that the buttons *always* appear above the headers.
*
* Note that only one set of buttons are visible at once.
*
*
*
*
*
*
*
*
*
* ...
*
*
*
*
* ...
*/
function clearAutoMargin(menuOpts) {
Plots.autoMargin(gd, autoMarginId(menuOpts));
}
// draw update menu container
var menus = fullLayout._menulayer.selectAll('g.' + constants.containerClassName).data(menuData.length > 0 ? [0] : []);
menus.enter().append('g').classed(constants.containerClassName, true).style('cursor', 'pointer');
menus.exit().each(function () {
// Most components don't need to explicitly remove autoMargin, because
// marginPushers does this - but updatemenu updates don't go through
// a full replot so we need to explicitly remove it.
// This is for removing *all* updatemenus, removing individuals is
// handled below, in headerGroups.exit
d3.select(this).selectAll('g.' + constants.headerGroupClassName).each(clearAutoMargin);
}).remove();
// return early if no update menus are visible
if (menuData.length === 0) return;
// join header group
var headerGroups = menus.selectAll('g.' + constants.headerGroupClassName).data(menuData, keyFunction);
headerGroups.enter().append('g').classed(constants.headerGroupClassName, true);
// draw dropdown button container
var gButton = Lib.ensureSingle(menus, 'g', constants.dropdownButtonGroupClassName, function (s) {
s.style('pointer-events', 'all');
});
// find dimensions before plotting anything (this mutates menuOpts)
for (var i = 0; i < menuData.length; i++) {
var menuOpts = menuData[i];
findDimensions(gd, menuOpts);
}
// setup scrollbox
var scrollBoxId = 'updatemenus' + fullLayout._uid;
var scrollBox = new ScrollBox(gd, gButton, scrollBoxId);
// remove exiting header, remove dropped buttons and reset margins
if (headerGroups.enter().size()) {
// make sure gButton is on top of all headers
gButton.node().parentNode.appendChild(gButton.node());
gButton.call(removeAllButtons);
}
headerGroups.exit().each(function (menuOpts) {
gButton.call(removeAllButtons);
clearAutoMargin(menuOpts);
}).remove();
// draw headers!
headerGroups.each(function (menuOpts) {
var gHeader = d3.select(this);
var _gButton = menuOpts.type === 'dropdown' ? gButton : null;
Plots.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function (data) {
setActive(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true);
});
if (menuOpts.type === 'dropdown') {
drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);
// if this menu is active, update the dropdown container
if (isActive(gButton, menuOpts)) {
drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
}
} else {
drawButtons(gd, gHeader, null, null, menuOpts);
}
});
};
// Note that '_index' is set at the default step,
// it corresponds to the menu index in the user layout update menu container.
// Because a menu can be set invisible,
// this is a more 'consistent' field than the index in the menuData.
function keyFunction(menuOpts) {
return menuOpts._index;
}
function isFolded(gButton) {
return +gButton.attr(constants.menuIndexAttrName) === -1;
}
function isActive(gButton, menuOpts) {
return +gButton.attr(constants.menuIndexAttrName) === menuOpts._index;
}
function setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) {
// update 'active' attribute in menuOpts
menuOpts.active = buttonIndex;
// due to templating, it's possible this slider doesn't even exist yet
arrayEditor(gd.layout, constants.name, menuOpts).applyUpdate('active', buttonIndex);
if (menuOpts.type === 'buttons') {
drawButtons(gd, gHeader, null, null, menuOpts);
} else if (menuOpts.type === 'dropdown') {
// fold up buttons and redraw header
gButton.attr(constants.menuIndexAttrName, '-1');
drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);
if (!isSilentUpdate) {
drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
}
}
}
function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) {
var header = Lib.ensureSingle(gHeader, 'g', constants.headerClassName, function (s) {
s.style('pointer-events', 'all');
});
var dims = menuOpts._dims;
var active = menuOpts.active;
var headerOpts = menuOpts.buttons[active] || constants.blankHeaderOpts;
var posOpts = {
y: menuOpts.pad.t,
yPad: 0,
x: menuOpts.pad.l,
xPad: 0,
index: 0
};
var positionOverrides = {
width: dims.headerWidth,
height: dims.headerHeight
};
header.call(drawItem, menuOpts, headerOpts, gd).call(setItemPosition, menuOpts, posOpts, positionOverrides);
// draw drop arrow at the right edge
var arrow = Lib.ensureSingle(gHeader, 'text', constants.headerArrowClassName, function (s) {
s.attr('text-anchor', 'end').call(Drawing.font, menuOpts.font).text(constants.arrowSymbol[menuOpts.direction]);
});
arrow.attr({
x: dims.headerWidth - constants.arrowOffsetX + menuOpts.pad.l,
y: dims.headerHeight / 2 + constants.textOffsetY + menuOpts.pad.t
});
header.on('click', function () {
gButton.call(removeAllButtons, String(isActive(gButton, menuOpts) ? -1 : menuOpts._index));
drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
});
header.on('mouseover', function () {
header.call(styleOnMouseOver);
});
header.on('mouseout', function () {
header.call(styleOnMouseOut, menuOpts);
});
// translate header group
Drawing.setTranslate(gHeader, dims.lx, dims.ly);
}
function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) {
// If this is a set of buttons, set pointer events = all since we play
// some minor games with which container is which in order to simplify
// the drawing of *either* buttons or menus
if (!gButton) {
gButton = gHeader;
gButton.attr('pointer-events', 'all');
}
var buttonData = !isFolded(gButton) || menuOpts.type === 'buttons' ? menuOpts.buttons : [];
var klass = menuOpts.type === 'dropdown' ? constants.dropdownButtonClassName : constants.buttonClassName;
var buttons = gButton.selectAll('g.' + klass).data(Lib.filterVisible(buttonData));
var enter = buttons.enter().append('g').classed(klass, true);
var exit = buttons.exit();
if (menuOpts.type === 'dropdown') {
enter.attr('opacity', '0').transition().attr('opacity', '1');
exit.transition().attr('opacity', '0').remove();
} else {
exit.remove();
}
var x0 = 0;
var y0 = 0;
var dims = menuOpts._dims;
var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
if (menuOpts.type === 'dropdown') {
if (isVertical) {
y0 = dims.headerHeight + constants.gapButtonHeader;
} else {
x0 = dims.headerWidth + constants.gapButtonHeader;
}
}
if (menuOpts.type === 'dropdown' && menuOpts.direction === 'up') {
y0 = -constants.gapButtonHeader + constants.gapButton - dims.openHeight;
}
if (menuOpts.type === 'dropdown' && menuOpts.direction === 'left') {
x0 = -constants.gapButtonHeader + constants.gapButton - dims.openWidth;
}
var posOpts = {
x: dims.lx + x0 + menuOpts.pad.l,
y: dims.ly + y0 + menuOpts.pad.t,
yPad: constants.gapButton,
xPad: constants.gapButton,
index: 0
};
var scrollBoxPosition = {
l: posOpts.x + menuOpts.borderwidth,
t: posOpts.y + menuOpts.borderwidth
};
buttons.each(function (buttonOpts, buttonIndex) {
var button = d3.select(this);
button.call(drawItem, menuOpts, buttonOpts, gd).call(setItemPosition, menuOpts, posOpts);
button.on('click', function () {
// skip `dragend` events
if (d3.event.defaultPrevented) return;
if (buttonOpts.execute) {
if (buttonOpts.args2 && menuOpts.active === buttonIndex) {
setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, -1);
Plots.executeAPICommand(gd, buttonOpts.method, buttonOpts.args2);
} else {
setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex);
Plots.executeAPICommand(gd, buttonOpts.method, buttonOpts.args);
}
}
gd.emit('plotly_buttonclicked', {
menu: menuOpts,
button: buttonOpts,
active: menuOpts.active
});
});
button.on('mouseover', function () {
button.call(styleOnMouseOver);
});
button.on('mouseout', function () {
button.call(styleOnMouseOut, menuOpts);
buttons.call(styleButtons, menuOpts);
});
});
buttons.call(styleButtons, menuOpts);
if (isVertical) {
scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth);
scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t;
} else {
scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l;
scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight);
}
scrollBoxPosition.direction = menuOpts.direction;
if (scrollBox) {
if (buttons.size()) {
drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition);
} else {
hideScrollBox(scrollBox);
}
}
}
function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) {
// enable the scrollbox
var direction = menuOpts.direction;
var isVertical = direction === 'up' || direction === 'down';
var dims = menuOpts._dims;
var active = menuOpts.active;
var translateX, translateY;
var i;
if (isVertical) {
translateY = 0;
for (i = 0; i < active; i++) {
translateY += dims.heights[i] + constants.gapButton;
}
} else {
translateX = 0;
for (i = 0; i < active; i++) {
translateX += dims.widths[i] + constants.gapButton;
}
}
scrollBox.enable(position, translateX, translateY);
if (scrollBox.hbar) {
scrollBox.hbar.attr('opacity', '0').transition().attr('opacity', '1');
}
if (scrollBox.vbar) {
scrollBox.vbar.attr('opacity', '0').transition().attr('opacity', '1');
}
}
function hideScrollBox(scrollBox) {
var hasHBar = !!scrollBox.hbar;
var hasVBar = !!scrollBox.vbar;
if (hasHBar) {
scrollBox.hbar.transition().attr('opacity', '0').each('end', function () {
hasHBar = false;
if (!hasVBar) scrollBox.disable();
});
}
if (hasVBar) {
scrollBox.vbar.transition().attr('opacity', '0').each('end', function () {
hasVBar = false;
if (!hasHBar) scrollBox.disable();
});
}
}
function drawItem(item, menuOpts, itemOpts, gd) {
item.call(drawItemRect, menuOpts).call(drawItemText, menuOpts, itemOpts, gd);
}
function drawItemRect(item, menuOpts) {
var rect = Lib.ensureSingle(item, 'rect', constants.itemRectClassName, function (s) {
s.attr({
rx: constants.rx,
ry: constants.ry,
'shape-rendering': 'crispEdges'
});
});
rect.call(Color.stroke, menuOpts.bordercolor).call(Color.fill, menuOpts.bgcolor).style('stroke-width', menuOpts.borderwidth + 'px');
}
function drawItemText(item, menuOpts, itemOpts, gd) {
var text = Lib.ensureSingle(item, 'text', constants.itemTextClassName, function (s) {
s.attr({
'text-anchor': 'start',
'data-notex': 1
});
});
var tx = itemOpts.label;
var _meta = gd._fullLayout._meta;
if (_meta) tx = Lib.templateString(tx, _meta);
text.call(Drawing.font, menuOpts.font).text(tx).call(svgTextUtils.convertToTspans, gd);
}
function styleButtons(buttons, menuOpts) {
var active = menuOpts.active;
buttons.each(function (buttonOpts, i) {
var button = d3.select(this);
if (i === active && menuOpts.showactive) {
button.select('rect.' + constants.itemRectClassName).call(Color.fill, constants.activeColor);
}
});
}
function styleOnMouseOver(item) {
item.select('rect.' + constants.itemRectClassName).call(Color.fill, constants.hoverColor);
}
function styleOnMouseOut(item, menuOpts) {
item.select('rect.' + constants.itemRectClassName).call(Color.fill, menuOpts.bgcolor);
}
// find item dimensions (this mutates menuOpts)
function findDimensions(gd, menuOpts) {
var dims = menuOpts._dims = {
width1: 0,
height1: 0,
heights: [],
widths: [],
totalWidth: 0,
totalHeight: 0,
openWidth: 0,
openHeight: 0,
lx: 0,
ly: 0
};
var fakeButtons = Drawing.tester.selectAll('g.' + constants.dropdownButtonClassName).data(Lib.filterVisible(menuOpts.buttons));
fakeButtons.enter().append('g').classed(constants.dropdownButtonClassName, true);
var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
// loop over fake buttons to find width / height
fakeButtons.each(function (buttonOpts, i) {
var button = d3.select(this);
button.call(drawItem, menuOpts, buttonOpts, gd);
var text = button.select('.' + constants.itemTextClassName);
// width is given by max width of all buttons
var tWidth = text.node() && Drawing.bBox(text.node()).width;
var wEff = Math.max(tWidth + constants.textPadX, constants.minWidth);
// height is determined by item text
var tHeight = menuOpts.font.size * LINE_SPACING;
var tLines = svgTextUtils.lineCount(text);
var hEff = Math.max(tHeight * tLines, constants.minHeight) + constants.textOffsetY;
hEff = Math.ceil(hEff);
wEff = Math.ceil(wEff);
// Store per-item sizes since a row of horizontal buttons, for example,
// don't all need to be the same width:
dims.widths[i] = wEff;
dims.heights[i] = hEff;
// Height and width of individual element:
dims.height1 = Math.max(dims.height1, hEff);
dims.width1 = Math.max(dims.width1, wEff);
if (isVertical) {
dims.totalWidth = Math.max(dims.totalWidth, wEff);
dims.openWidth = dims.totalWidth;
dims.totalHeight += hEff + constants.gapButton;
dims.openHeight += hEff + constants.gapButton;
} else {
dims.totalWidth += wEff + constants.gapButton;
dims.openWidth += wEff + constants.gapButton;
dims.totalHeight = Math.max(dims.totalHeight, hEff);
dims.openHeight = dims.totalHeight;
}
});
if (isVertical) {
dims.totalHeight -= constants.gapButton;
} else {
dims.totalWidth -= constants.gapButton;
}
dims.headerWidth = dims.width1 + constants.arrowPadX;
dims.headerHeight = dims.height1;
if (menuOpts.type === 'dropdown') {
if (isVertical) {
dims.width1 += constants.arrowPadX;
dims.totalHeight = dims.height1;
} else {
dims.totalWidth = dims.width1;
}
dims.totalWidth += constants.arrowPadX;
}
fakeButtons.remove();
var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r;
var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b;
var graphSize = gd._fullLayout._size;
dims.lx = graphSize.l + graphSize.w * menuOpts.x;
dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y);
var xanchor = 'left';
if (Lib.isRightAnchor(menuOpts)) {
dims.lx -= paddedWidth;
xanchor = 'right';
}
if (Lib.isCenterAnchor(menuOpts)) {
dims.lx -= paddedWidth / 2;
xanchor = 'center';
}
var yanchor = 'top';
if (Lib.isBottomAnchor(menuOpts)) {
dims.ly -= paddedHeight;
yanchor = 'bottom';
}
if (Lib.isMiddleAnchor(menuOpts)) {
dims.ly -= paddedHeight / 2;
yanchor = 'middle';
}
dims.totalWidth = Math.ceil(dims.totalWidth);
dims.totalHeight = Math.ceil(dims.totalHeight);
dims.lx = Math.round(dims.lx);
dims.ly = Math.round(dims.ly);
Plots.autoMargin(gd, autoMarginId(menuOpts), {
x: menuOpts.x,
y: menuOpts.y,
l: paddedWidth * ({
right: 1,
center: 0.5
}[xanchor] || 0),
r: paddedWidth * ({
left: 1,
center: 0.5
}[xanchor] || 0),
b: paddedHeight * ({
top: 1,
middle: 0.5
}[yanchor] || 0),
t: paddedHeight * ({
bottom: 1,
middle: 0.5
}[yanchor] || 0)
});
}
function autoMarginId(menuOpts) {
return constants.autoMarginIdRoot + menuOpts._index;
}
// set item positions (mutates posOpts)
function setItemPosition(item, menuOpts, posOpts, overrideOpts) {
overrideOpts = overrideOpts || {};
var rect = item.select('.' + constants.itemRectClassName);
var text = item.select('.' + constants.itemTextClassName);
var borderWidth = menuOpts.borderwidth;
var index = posOpts.index;
var dims = menuOpts._dims;
Drawing.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y);
var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1);
rect.attr({
x: 0,
y: 0,
width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]),
height: finalHeight
});
var tHeight = menuOpts.font.size * LINE_SPACING;
var tLines = svgTextUtils.lineCount(text);
var spanOffset = (tLines - 1) * tHeight / 2;
svgTextUtils.positionText(text, constants.textOffsetX, finalHeight / 2 - spanOffset + constants.textOffsetY);
if (isVertical) {
posOpts.y += dims.heights[index] + posOpts.yPad;
} else {
posOpts.x += dims.widths[index] + posOpts.xPad;
}
posOpts.index++;
}
function removeAllButtons(gButton, newMenuIndexAttr) {
gButton.attr(constants.menuIndexAttrName, newMenuIndexAttr || '-1').selectAll('g.' + constants.dropdownButtonClassName).remove();
}
/***/ }),
/***/ 76908:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(73712);
module.exports = {
moduleType: 'component',
name: constants.name,
layoutAttributes: __webpack_require__(88444),
supplyLayoutDefaults: __webpack_require__(91384),
draw: __webpack_require__(14420)
};
/***/ }),
/***/ 37400:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = ScrollBox;
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
/**
* Helper class to setup a scroll box
*
* @class
* @param gd Plotly's graph div
* @param container Container to be scroll-boxed (as a D3 selection)
* @param {string} id Id for the clip path to implement the scroll box
*/
function ScrollBox(gd, container, id) {
this.gd = gd;
this.container = container;
this.id = id;
// See ScrollBox.prototype.enable for further definition
this.position = null; // scrollbox position
this.translateX = null; // scrollbox horizontal translation
this.translateY = null; // scrollbox vertical translation
this.hbar = null; // horizontal scrollbar D3 selection
this.vbar = null; // vertical scrollbar D3 selection
// element to capture pointer events
this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]);
this.bg.exit().on('.drag', null).on('wheel', null).remove();
this.bg.enter().append('rect').classed('scrollbox-bg', true).style('pointer-events', 'all').attr({
opacity: 0,
x: 0,
y: 0,
width: 0,
height: 0
});
}
// scroll bar dimensions
ScrollBox.barWidth = 2;
ScrollBox.barLength = 20;
ScrollBox.barRadius = 2;
ScrollBox.barPad = 1;
ScrollBox.barColor = '#808BA4';
/**
* If needed, setup a clip path and scrollbars
*
* @method
* @param {Object} position
* @param {number} position.l Left side position (in pixels)
* @param {number} position.t Top side (in pixels)
* @param {number} position.w Width (in pixels)
* @param {number} position.h Height (in pixels)
* @param {string} [position.direction='down']
* Either 'down', 'left', 'right' or 'up'
* @param {number} [translateX=0] Horizontal offset (in pixels)
* @param {number} [translateY=0] Vertical offset (in pixels)
*/
ScrollBox.prototype.enable = function enable(position, translateX, translateY) {
var fullLayout = this.gd._fullLayout;
var fullWidth = fullLayout.width;
var fullHeight = fullLayout.height;
// compute position of scrollbox
this.position = position;
var l = this.position.l;
var w = this.position.w;
var t = this.position.t;
var h = this.position.h;
var direction = this.position.direction;
var isDown = direction === 'down';
var isLeft = direction === 'left';
var isRight = direction === 'right';
var isUp = direction === 'up';
var boxW = w;
var boxH = h;
var boxL, boxR;
var boxT, boxB;
if (!isDown && !isLeft && !isRight && !isUp) {
this.position.direction = 'down';
isDown = true;
}
var isVertical = isDown || isUp;
if (isVertical) {
boxL = l;
boxR = boxL + boxW;
if (isDown) {
// anchor to top side
boxT = t;
boxB = Math.min(boxT + boxH, fullHeight);
boxH = boxB - boxT;
} else {
// anchor to bottom side
boxB = t + boxH;
boxT = Math.max(boxB - boxH, 0);
boxH = boxB - boxT;
}
} else {
boxT = t;
boxB = boxT + boxH;
if (isLeft) {
// anchor to right side
boxR = l + boxW;
boxL = Math.max(boxR - boxW, 0);
boxW = boxR - boxL;
} else {
// anchor to left side
boxL = l;
boxR = Math.min(boxL + boxW, fullWidth);
boxW = boxR - boxL;
}
}
this._box = {
l: boxL,
t: boxT,
w: boxW,
h: boxH
};
// compute position of horizontal scroll bar
var needsHorizontalScrollBar = w > boxW;
var hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad;
var hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad;
// draw horizontal scrollbar on the bottom side
var hbarL = l;
var hbarT = t + h;
if (hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH;
var hbar = this.container.selectAll('rect.scrollbar-horizontal').data(needsHorizontalScrollBar ? [0] : []);
hbar.exit().on('.drag', null).remove();
hbar.enter().append('rect').classed('scrollbar-horizontal', true).call(Color.fill, ScrollBox.barColor);
if (needsHorizontalScrollBar) {
this.hbar = hbar.attr({
rx: ScrollBox.barRadius,
ry: ScrollBox.barRadius,
x: hbarL,
y: hbarT,
width: hbarW,
height: hbarH
});
// hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax
this._hbarXMin = hbarL + hbarW / 2;
this._hbarTranslateMax = boxW - hbarW;
} else {
delete this.hbar;
delete this._hbarXMin;
delete this._hbarTranslateMax;
}
// compute position of vertical scroll bar
var needsVerticalScrollBar = h > boxH;
var vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad;
var vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad;
// draw vertical scrollbar on the right side
var vbarL = l + w;
var vbarT = t;
if (vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW;
var vbar = this.container.selectAll('rect.scrollbar-vertical').data(needsVerticalScrollBar ? [0] : []);
vbar.exit().on('.drag', null).remove();
vbar.enter().append('rect').classed('scrollbar-vertical', true).call(Color.fill, ScrollBox.barColor);
if (needsVerticalScrollBar) {
this.vbar = vbar.attr({
rx: ScrollBox.barRadius,
ry: ScrollBox.barRadius,
x: vbarL,
y: vbarT,
width: vbarW,
height: vbarH
});
// vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax
this._vbarYMin = vbarT + vbarH / 2;
this._vbarTranslateMax = boxH - vbarH;
} else {
delete this.vbar;
delete this._vbarYMin;
delete this._vbarTranslateMax;
}
// setup a clip path (if scroll bars are needed)
var clipId = this.id;
var clipL = boxL - 0.5;
var clipR = needsVerticalScrollBar ? boxR + vbarW + 0.5 : boxR + 0.5;
var clipT = boxT - 0.5;
var clipB = needsHorizontalScrollBar ? boxB + hbarH + 0.5 : boxB + 0.5;
var clipPath = fullLayout._topdefs.selectAll('#' + clipId).data(needsHorizontalScrollBar || needsVerticalScrollBar ? [0] : []);
clipPath.exit().remove();
clipPath.enter().append('clipPath').attr('id', clipId).append('rect');
if (needsHorizontalScrollBar || needsVerticalScrollBar) {
this._clipRect = clipPath.select('rect').attr({
x: Math.floor(clipL),
y: Math.floor(clipT),
width: Math.ceil(clipR) - Math.floor(clipL),
height: Math.ceil(clipB) - Math.floor(clipT)
});
this.container.call(Drawing.setClipUrl, clipId, this.gd);
this.bg.attr({
x: l,
y: t,
width: w,
height: h
});
} else {
this.bg.attr({
width: 0,
height: 0
});
this.container.on('wheel', null).on('.drag', null).call(Drawing.setClipUrl, null);
delete this._clipRect;
}
// set up drag listeners (if scroll bars are needed)
if (needsHorizontalScrollBar || needsVerticalScrollBar) {
var onBoxDrag = d3.behavior.drag().on('dragstart', function () {
d3.event.sourceEvent.preventDefault();
}).on('drag', this._onBoxDrag.bind(this));
this.container.on('wheel', null).on('wheel', this._onBoxWheel.bind(this)).on('.drag', null).call(onBoxDrag);
var onBarDrag = d3.behavior.drag().on('dragstart', function () {
d3.event.sourceEvent.preventDefault();
d3.event.sourceEvent.stopPropagation();
}).on('drag', this._onBarDrag.bind(this));
if (needsHorizontalScrollBar) {
this.hbar.on('.drag', null).call(onBarDrag);
}
if (needsVerticalScrollBar) {
this.vbar.on('.drag', null).call(onBarDrag);
}
}
// set scrollbox translation
this.setTranslate(translateX, translateY);
};
/**
* If present, remove clip-path and scrollbars
*
* @method
*/
ScrollBox.prototype.disable = function disable() {
if (this.hbar || this.vbar) {
this.bg.attr({
width: 0,
height: 0
});
this.container.on('wheel', null).on('.drag', null).call(Drawing.setClipUrl, null);
delete this._clipRect;
}
if (this.hbar) {
this.hbar.on('.drag', null);
this.hbar.remove();
delete this.hbar;
delete this._hbarXMin;
delete this._hbarTranslateMax;
}
if (this.vbar) {
this.vbar.on('.drag', null);
this.vbar.remove();
delete this.vbar;
delete this._vbarYMin;
delete this._vbarTranslateMax;
}
};
/**
* Handles scroll box drag events
*
* @method
*/
ScrollBox.prototype._onBoxDrag = function _onBoxDrag() {
var translateX = this.translateX;
var translateY = this.translateY;
if (this.hbar) {
translateX -= d3.event.dx;
}
if (this.vbar) {
translateY -= d3.event.dy;
}
this.setTranslate(translateX, translateY);
};
/**
* Handles scroll box wheel events
*
* @method
*/
ScrollBox.prototype._onBoxWheel = function _onBoxWheel() {
var translateX = this.translateX;
var translateY = this.translateY;
if (this.hbar) {
translateX += d3.event.deltaY;
}
if (this.vbar) {
translateY += d3.event.deltaY;
}
this.setTranslate(translateX, translateY);
};
/**
* Handles scroll bar drag events
*
* @method
*/
ScrollBox.prototype._onBarDrag = function _onBarDrag() {
var translateX = this.translateX;
var translateY = this.translateY;
if (this.hbar) {
var xMin = translateX + this._hbarXMin;
var xMax = xMin + this._hbarTranslateMax;
var x = Lib.constrain(d3.event.x, xMin, xMax);
var xf = (x - xMin) / (xMax - xMin);
var translateXMax = this.position.w - this._box.w;
translateX = xf * translateXMax;
}
if (this.vbar) {
var yMin = translateY + this._vbarYMin;
var yMax = yMin + this._vbarTranslateMax;
var y = Lib.constrain(d3.event.y, yMin, yMax);
var yf = (y - yMin) / (yMax - yMin);
var translateYMax = this.position.h - this._box.h;
translateY = yf * translateYMax;
}
this.setTranslate(translateX, translateY);
};
/**
* Set clip path and scroll bar translate transform
*
* @method
* @param {number} [translateX=0] Horizontal offset (in pixels)
* @param {number} [translateY=0] Vertical offset (in pixels)
*/
ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) {
// store translateX and translateY (needed by mouse event handlers)
var translateXMax = this.position.w - this._box.w;
var translateYMax = this.position.h - this._box.h;
translateX = Lib.constrain(translateX || 0, 0, translateXMax);
translateY = Lib.constrain(translateY || 0, 0, translateYMax);
this.translateX = translateX;
this.translateY = translateY;
this.container.call(Drawing.setTranslate, this._box.l - this.position.l - translateX, this._box.t - this.position.t - translateY);
if (this._clipRect) {
this._clipRect.attr({
x: Math.floor(this.position.l + translateX - 0.5),
y: Math.floor(this.position.t + translateY - 0.5)
});
}
if (this.hbar) {
var xf = translateX / translateXMax;
this.hbar.call(Drawing.setTranslate, translateX + xf * this._hbarTranslateMax, translateY);
}
if (this.vbar) {
var yf = translateY / translateYMax;
this.vbar.call(Drawing.setTranslate, translateX, translateY + yf * this._vbarTranslateMax);
}
};
/***/ }),
/***/ 84284:
/***/ (function(module) {
"use strict";
// fraction of some size to get to a named position
module.exports = {
// from bottom left: this is the origin of our paper-reference
// positioning system
FROM_BL: {
left: 0,
center: 0.5,
right: 1,
bottom: 0,
middle: 0.5,
top: 1
},
// from top left: this is the screen pixel positioning origin
FROM_TL: {
left: 0,
center: 0.5,
right: 1,
bottom: 1,
middle: 0.5,
top: 0
},
// from bottom right: sometimes you just need the opposite of ^^
FROM_BR: {
left: 1,
center: 0.5,
right: 0,
bottom: 0,
middle: 0.5,
top: 1
},
// multiple of fontSize to get the vertical offset between lines
LINE_SPACING: 1.3,
// multiple of fontSize to shift from the baseline
// to the cap (captical letter) line
// (to use when we don't calculate this shift from Drawing.bBox)
// This is an approximation since in reality cap height can differ
// from font to font. However, according to Wikipedia
// an "average" font might have a cap height of 70% of the em
// https://en.wikipedia.org/wiki/Em_(typography)#History
CAP_SHIFT: 0.70,
// half the cap height (distance between baseline and cap line)
// of an "average" font (for more info see above).
MID_SHIFT: 0.35,
OPPOSITE_SIDE: {
left: 'right',
right: 'left',
top: 'bottom',
bottom: 'top'
}
};
/***/ }),
/***/ 36208:
/***/ (function(module) {
"use strict";
module.exports = {
axisRefDescription: function (axisname, lower, upper) {
return ['If set to a', axisname, 'axis id (e.g. *' + axisname + '* or', '*' + axisname + '2*), the `' + axisname + '` position refers to a', axisname, 'coordinate. If set to *paper*, the `' + axisname + '`', 'position refers to the distance from the', lower, 'of the plotting', 'area in normalized coordinates where *0* (*1*) corresponds to the', lower, '(' + upper + '). If set to a', axisname, 'axis ID followed by', '*domain* (separated by a space), the position behaves like for', '*paper*, but refers to the distance in fractions of the domain', 'length from the', lower, 'of the domain of that axis: e.g.,', '*' + axisname + '2 domain* refers to the domain of the second', axisname, ' axis and a', axisname, 'position of 0.5 refers to the', 'point between the', lower, 'and the', upper, 'of the domain of the', 'second', axisname, 'axis.'].join(' ');
}
};
/***/ }),
/***/ 48164:
/***/ (function(module) {
"use strict";
module.exports = {
INCREASING: {
COLOR: '#3D9970',
SYMBOL: '▲'
},
DECREASING: {
COLOR: '#FF4136',
SYMBOL: '▼'
}
};
/***/ }),
/***/ 26880:
/***/ (function(module) {
"use strict";
module.exports = {
FORMAT_LINK: 'https://github.com/d3/d3-format/tree/v1.4.5#d3-format',
DATE_FORMAT_LINK: 'https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format'
};
/***/ }),
/***/ 69104:
/***/ (function(module) {
"use strict";
module.exports = {
COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='],
COMPARISON_OPS2: ['=', '<', '>=', '>', '<='],
INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['],
SET_OPS: ['{}', '}{'],
CONSTRAINT_REDUCTION: {
// for contour constraints, open/closed endpoints are equivalent
'=': '=',
'<': '<',
'<=': '<',
'>': '>',
'>=': '>',
'[]': '[]',
'()': '[]',
'[)': '[]',
'(]': '[]',
'][': '][',
')(': '][',
'](': '][',
')[': ']['
}
};
/***/ }),
/***/ 99168:
/***/ (function(module) {
"use strict";
module.exports = {
solid: [[], 0],
dot: [[0.5, 1], 200],
dash: [[0.5, 1], 50],
longdash: [[0.5, 1], 10],
dashdot: [[0.5, 0.625, 0.875, 1], 50],
longdashdot: [[0.5, 0.7, 0.8, 1], 10]
};
/***/ }),
/***/ 87792:
/***/ (function(module) {
"use strict";
module.exports = {
circle: '●',
'circle-open': '○',
square: '■',
'square-open': '□',
diamond: '◆',
'diamond-open': '◇',
cross: '+',
x: '❌'
};
/***/ }),
/***/ 13448:
/***/ (function(module) {
"use strict";
module.exports = {
/**
* Timing information for interactive elements
*/
SHOW_PLACEHOLDER: 100,
HIDE_PLACEHOLDER: 1000,
// opacity dimming fraction for points that are not in selection
DESELECTDIM: 0.2
};
/***/ }),
/***/ 39032:
/***/ (function(module) {
"use strict";
module.exports = {
/**
* Standardize all missing data in calcdata to use undefined
* never null or NaN.
* That way we can use !==undefined, or !== BADNUM,
* to test for real data
*/
BADNUM: undefined,
/*
* Limit certain operations to well below floating point max value
* to avoid glitches: Make sure that even when you multiply it by the
* number of pixels on a giant screen it still works
*/
FP_SAFE: Number.MAX_VALUE * 1e-4,
/*
* conversion of date units to milliseconds
* year and month constants are marked "AVG"
* to remind us that not all years and months
* have the same length
*/
ONEMAXYEAR: 31622400000,
// 366 * ONEDAY
ONEAVGYEAR: 31557600000,
// 365.25 days
ONEMINYEAR: 31536000000,
// 365 * ONEDAY
ONEMAXQUARTER: 7948800000,
// 92 * ONEDAY
ONEAVGQUARTER: 7889400000,
// 1/4 of ONEAVGYEAR
ONEMINQUARTER: 7689600000,
// 89 * ONEDAY
ONEMAXMONTH: 2678400000,
// 31 * ONEDAY
ONEAVGMONTH: 2629800000,
// 1/12 of ONEAVGYEAR
ONEMINMONTH: 2419200000,
// 28 * ONEDAY
ONEWEEK: 604800000,
// 7 * ONEDAY
ONEDAY: 86400000,
// 24 * ONEHOUR
ONEHOUR: 3600000,
ONEMIN: 60000,
ONESEC: 1000,
ONEMILLI: 1,
ONEMICROSEC: 0.001,
/*
* For fast conversion btwn world calendars and epoch ms, the Julian Day Number
* of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD()
*/
EPOCHJD: 2440587.5,
/*
* Are two values nearly equal? Compare to 1PPM
*/
ALMOST_EQUAL: 1 - 1e-6,
/*
* If we're asked to clip a non-positive log value, how far off-screen
* do we put it?
*/
LOG_CLIP: 10,
/*
* not a number, but for displaying numbers: the "minus sign" symbol is
* wider than the regular ascii dash "-"
*/
MINUS_SIGN: '\u2212'
};
/***/ }),
/***/ 2264:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
// Pixelated image rendering
// The actual CSS declaration is prepended with fallbacks for older browsers.
// NB. IE's `-ms-interpolation-mode` works only with not with SVG
// https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering
// https://caniuse.com/?search=image-rendering
// http://phrogz.net/tmp/canvas_image_zoom.html
exports.CSS_DECLARATIONS = [['image-rendering', 'optimizeSpeed'], ['image-rendering', '-moz-crisp-edges'], ['image-rendering', '-o-crisp-edges'], ['image-rendering', '-webkit-optimize-contrast'], ['image-rendering', 'optimize-contrast'], ['image-rendering', 'crisp-edges'], ['image-rendering', 'pixelated']];
exports.STYLE = exports.CSS_DECLARATIONS.map(function (d) {
return d.join(': ') + '; ';
}).join('');
/***/ }),
/***/ 9616:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
exports.xmlns = 'http://www.w3.org/2000/xmlns/';
exports.svg = 'http://www.w3.org/2000/svg';
exports.xlink = 'http://www.w3.org/1999/xlink';
// the 'old' d3 quirk got fix in v3.5.7
// https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed
exports.svgAttrs = {
xmlns: exports.svg,
'xmlns:xlink': exports.xlink
};
/***/ }),
/***/ 64884:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
exports.version = __webpack_require__(25788).version;
// inject promise polyfill
__webpack_require__(88324);
// inject plot css
__webpack_require__(79288);
// include registry module and expose register method
var Registry = __webpack_require__(24040);
var register = exports.register = Registry.register;
// expose plot api methods
var plotApi = __webpack_require__(22448);
var methodNames = Object.keys(plotApi);
for (var i = 0; i < methodNames.length; i++) {
var name = methodNames[i];
// _ -> private API methods, but still registered for internal use
if (name.charAt(0) !== '_') exports[name] = plotApi[name];
register({
moduleType: 'apiMethod',
name: name,
fn: plotApi[name]
});
}
// scatter is the only trace included by default
register(__webpack_require__(65875));
// register all registrable components modules
register([__webpack_require__(79180), __webpack_require__(56864), __webpack_require__(22676), __webpack_require__(41592), __webpack_require__(7402), __webpack_require__(76908), __webpack_require__(97544), __webpack_require__(49692), __webpack_require__(41152), __webpack_require__(12704), __webpack_require__(64968), __webpack_require__(8932), __webpack_require__(55080), __webpack_require__(2780),
// legend needs to come after shape | legend defaults depends on shapes
__webpack_require__(93024),
// fx needs to come after legend | unified hover defaults depends on legends
__webpack_require__(45460)]);
// locales en and en-US are required for default behavior
register([__webpack_require__(6580), __webpack_require__(11680)]);
// locales that are present in the window should be loaded
if (window.PlotlyLocales && Array.isArray(window.PlotlyLocales)) {
register(window.PlotlyLocales);
delete window.PlotlyLocales;
}
// plot icons
exports.Icons = __webpack_require__(9224);
// unofficial 'beta' plot methods, use at your own risk
var Fx = __webpack_require__(93024);
var Plots = __webpack_require__(7316);
exports.Plots = {
resize: Plots.resize,
graphJson: Plots.graphJson,
sendDataToCloud: Plots.sendDataToCloud
};
exports.Fx = {
hover: Fx.hover,
unhover: Fx.unhover,
loneHover: Fx.loneHover,
loneUnhover: Fx.loneUnhover
};
exports.Snapshot = __webpack_require__(78904);
exports.PlotSchema = __webpack_require__(73060);
/***/ }),
/***/ 9224:
/***/ (function(module) {
"use strict";
module.exports = {
undo: {
width: 857.1,
height: 1000,
path: 'm857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z',
transform: 'matrix(1 0 0 -1 0 850)'
},
home: {
width: 928.6,
height: 1000,
path: 'm786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z',
transform: 'matrix(1 0 0 -1 0 850)'
},
'camera-retro': {
width: 1000,
height: 1000,
path: 'm518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z',
transform: 'matrix(1 0 0 -1 0 850)'
},
zoombox: {
width: 1000,
height: 1000,
path: 'm1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z',
transform: 'matrix(1 0 0 -1 0 850)'
},
pan: {
width: 1000,
height: 1000,
path: 'm1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z',
transform: 'matrix(1 0 0 -1 0 850)'
},
zoom_plus: {
width: 875,
height: 1000,
path: 'm1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z',
transform: 'matrix(1 0 0 -1 0 850)'
},
zoom_minus: {
width: 875,
height: 1000,
path: 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z',
transform: 'matrix(1 0 0 -1 0 850)'
},
autoscale: {
width: 1000,
height: 1000,
path: 'm250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z',
transform: 'matrix(1 0 0 -1 0 850)'
},
tooltip_basic: {
width: 1500,
height: 1000,
path: 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z',
transform: 'matrix(1 0 0 -1 0 850)'
},
tooltip_compare: {
width: 1125,
height: 1000,
path: 'm187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z',
transform: 'matrix(1 0 0 -1 0 850)'
},
plotlylogo: {
width: 1542,
height: 1000,
path: 'm0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z',
transform: 'matrix(1 0 0 -1 0 850)'
},
'z-axis': {
width: 1000,
height: 1000,
path: 'm833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z',
transform: 'matrix(1 0 0 -1 0 850)'
},
'3d_rotate': {
width: 1000,
height: 1000,
path: 'm922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z',
transform: 'matrix(1 0 0 -1 0 850)'
},
camera: {
width: 1000,
height: 1000,
path: 'm500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z',
transform: 'matrix(1 0 0 -1 0 850)'
},
movie: {
width: 1000,
height: 1000,
path: 'm938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z',
transform: 'matrix(1 0 0 -1 0 850)'
},
question: {
width: 857.1,
height: 1000,
path: 'm500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z',
transform: 'matrix(1 0 0 -1 0 850)'
},
disk: {
width: 857.1,
height: 1000,
path: 'm214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z',
transform: 'matrix(1 0 0 -1 0 850)'
},
drawopenpath: {
width: 70,
height: 70,
path: 'M33.21,85.65a7.31,7.31,0,0,1-2.59-.48c-8.16-3.11-9.27-19.8-9.88-41.3-.1-3.58-.19-6.68-.35-9-.15-2.1-.67-3.48-1.43-3.79-2.13-.88-7.91,2.32-12,5.86L3,32.38c1.87-1.64,11.55-9.66,18.27-6.9,2.13.87,4.75,3.14,5.17,9,.17,2.43.26,5.59.36,9.25a224.17,224.17,0,0,0,1.5,23.4c1.54,10.76,4,12.22,4.48,12.4.84.32,2.79-.46,5.76-3.59L43,80.07C41.53,81.57,37.68,85.64,33.21,85.65ZM74.81,69a11.34,11.34,0,0,0,6.09-6.72L87.26,44.5,74.72,32,56.9,38.35c-2.37.86-5.57,3.42-6.61,6L38.65,72.14l8.42,8.43ZM55,46.27a7.91,7.91,0,0,1,3.64-3.17l14.8-5.3,8,8L76.11,60.6l-.06.19a6.37,6.37,0,0,1-3,3.43L48.25,74.59,44.62,71Zm16.57,7.82A6.9,6.9,0,1,0,64.64,61,6.91,6.91,0,0,0,71.54,54.09Zm-4.05,0a2.85,2.85,0,1,1-2.85-2.85A2.86,2.86,0,0,1,67.49,54.09Zm-4.13,5.22L60.5,56.45,44.26,72.7l2.86,2.86ZM97.83,35.67,84.14,22l-8.57,8.57L89.26,44.24Zm-13.69-8,8,8-2.85,2.85-8-8Z',
transform: 'matrix(1 0 0 1 -15 -15)'
},
drawclosedpath: {
width: 90,
height: 90,
path: 'M88.41,21.12a26.56,26.56,0,0,0-36.18,0l-2.07,2-2.07-2a26.57,26.57,0,0,0-36.18,0,23.74,23.74,0,0,0,0,34.8L48,90.12a3.22,3.22,0,0,0,4.42,0l36-34.21a23.73,23.73,0,0,0,0-34.79ZM84,51.24,50.16,83.35,16.35,51.25a17.28,17.28,0,0,1,0-25.47,20,20,0,0,1,27.3,0l4.29,4.07a3.23,3.23,0,0,0,4.44,0l4.29-4.07a20,20,0,0,1,27.3,0,17.27,17.27,0,0,1,0,25.46ZM66.76,47.68h-33v6.91h33ZM53.35,35H46.44V68h6.91Z',
transform: 'matrix(1 0 0 1 -5 -5)'
},
lasso: {
width: 1031,
height: 1000,
path: 'm1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z',
transform: 'matrix(1 0 0 -1 0 850)'
},
selectbox: {
width: 1000,
height: 1000,
path: 'm0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z',
transform: 'matrix(1 0 0 -1 0 850)'
},
drawline: {
width: 70,
height: 70,
path: 'M60.64,62.3a11.29,11.29,0,0,0,6.09-6.72l6.35-17.72L60.54,25.31l-17.82,6.4c-2.36.86-5.57,3.41-6.6,6L24.48,65.5l8.42,8.42ZM40.79,39.63a7.89,7.89,0,0,1,3.65-3.17l14.79-5.31,8,8L61.94,54l-.06.19a6.44,6.44,0,0,1-3,3.43L34.07,68l-3.62-3.63Zm16.57,7.81a6.9,6.9,0,1,0-6.89,6.9A6.9,6.9,0,0,0,57.36,47.44Zm-4,0a2.86,2.86,0,1,1-2.85-2.85A2.86,2.86,0,0,1,53.32,47.44Zm-4.13,5.22L46.33,49.8,30.08,66.05l2.86,2.86ZM83.65,29,70,15.34,61.4,23.9,75.09,37.59ZM70,21.06l8,8-2.84,2.85-8-8ZM87,80.49H10.67V87H87Z',
transform: 'matrix(1 0 0 1 -15 -15)'
},
drawrect: {
width: 80,
height: 80,
path: 'M78,22V79H21V22H78m9-9H12V88H87V13ZM68,46.22H31V54H68ZM53,32H45.22V69H53Z',
transform: 'matrix(1 0 0 1 -10 -10)'
},
drawcircle: {
width: 80,
height: 80,
path: 'M50,84.72C26.84,84.72,8,69.28,8,50.3S26.84,15.87,50,15.87,92,31.31,92,50.3,73.16,84.72,50,84.72Zm0-60.59c-18.6,0-33.74,11.74-33.74,26.17S31.4,76.46,50,76.46,83.74,64.72,83.74,50.3,68.6,24.13,50,24.13Zm17.15,22h-34v7.11h34Zm-13.8-13H46.24v34h7.11Z',
transform: 'matrix(1 0 0 1 -10 -10)'
},
eraseshape: {
width: 80,
height: 80,
path: 'M82.77,78H31.85L6,49.57,31.85,21.14H82.77a8.72,8.72,0,0,1,8.65,8.77V69.24A8.72,8.72,0,0,1,82.77,78ZM35.46,69.84H82.77a.57.57,0,0,0,.49-.6V29.91a.57.57,0,0,0-.49-.61H35.46L17,49.57Zm32.68-34.7-24,24,5,5,24-24Zm-19,.53-5,5,24,24,5-5Z',
transform: 'matrix(1 0 0 1 -10 -10)'
},
spikeline: {
width: 1000,
height: 1000,
path: 'M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z',
transform: 'matrix(1.5 0 0 -1.5 0 850)'
},
pencil: {
width: 1792,
height: 1792,
path: 'M491 1536l91-91-235-235-91 91v107h128v128h107zm523-928q0-22-22-22-10 0-17 7l-542 542q-7 7-7 17 0 22 22 22 10 0 17-7l542-542q7-7 7-17zm-54-192l416 416-832 832h-416v-416zm683 96q0 53-37 90l-166 166-416-416 166-165q36-38 90-38 53 0 91 38l235 234q37 39 37 91z',
transform: 'matrix(1 0 0 1 0 1)'
},
newplotlylogo: {
name: 'newplotlylogo',
svg: ['', '', ' ', ' ', ' plotly-logomark ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '].join('')
}
};
/***/ }),
/***/ 98308:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
/**
* Determine the position anchor property of x/y xanchor/yanchor components.
*
* - values < 1/3 align the low side at that fraction,
* - values [1/3, 2/3] align the center at that fraction,
* - values > 2/3 align the right at that fraction.
*/
exports.isLeftAnchor = function isLeftAnchor(opts) {
return opts.xanchor === 'left' || opts.xanchor === 'auto' && opts.x <= 1 / 3;
};
exports.isCenterAnchor = function isCenterAnchor(opts) {
return opts.xanchor === 'center' || opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3;
};
exports.isRightAnchor = function isRightAnchor(opts) {
return opts.xanchor === 'right' || opts.xanchor === 'auto' && opts.x >= 2 / 3;
};
exports.isTopAnchor = function isTopAnchor(opts) {
return opts.yanchor === 'top' || opts.yanchor === 'auto' && opts.y >= 2 / 3;
};
exports.isMiddleAnchor = function isMiddleAnchor(opts) {
return opts.yanchor === 'middle' || opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3;
};
exports.isBottomAnchor = function isBottomAnchor(opts) {
return opts.yanchor === 'bottom' || opts.yanchor === 'auto' && opts.y <= 1 / 3;
};
/***/ }),
/***/ 11864:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var modModule = __webpack_require__(20435);
var mod = modModule.mod;
var modHalf = modModule.modHalf;
var PI = Math.PI;
var twoPI = 2 * PI;
function deg2rad(deg) {
return deg / 180 * PI;
}
function rad2deg(rad) {
return rad / PI * 180;
}
/**
* is sector a full circle?
* ... this comes up a lot in SVG path-drawing routines
*
* N.B. we consider all sectors that span more that 2pi 'full' circles
*
* @param {2-item array} aBnds : angular bounds in *radians*
* @return {boolean}
*/
function isFullCircle(aBnds) {
return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-14;
}
/**
* angular delta between angle 'a' and 'b'
* solution taken from: https://stackoverflow.com/a/2007279
*
* @param {number} a : first angle in *radians*
* @param {number} b : second angle in *radians*
* @return {number} angular delta in *radians*
*/
function angleDelta(a, b) {
return modHalf(b - a, twoPI);
}
/**
* angular distance between angle 'a' and 'b'
*
* @param {number} a : first angle in *radians*
* @param {number} b : second angle in *radians*
* @return {number} angular distance in *radians*
*/
function angleDist(a, b) {
return Math.abs(angleDelta(a, b));
}
/**
* is angle inside sector?
*
* @param {number} a : angle to test in *radians*
* @param {2-item array} aBnds : sector's angular bounds in *radians*
* @param {boolean}
*/
function isAngleInsideSector(a, aBnds) {
if (isFullCircle(aBnds)) return true;
var s0, s1;
if (aBnds[0] < aBnds[1]) {
s0 = aBnds[0];
s1 = aBnds[1];
} else {
s0 = aBnds[1];
s1 = aBnds[0];
}
s0 = mod(s0, twoPI);
s1 = mod(s1, twoPI);
if (s0 > s1) s1 += twoPI;
var a0 = mod(a, twoPI);
var a1 = a0 + twoPI;
return a0 >= s0 && a0 <= s1 || a1 >= s0 && a1 <= s1;
}
/**
* is pt (r,a) inside sector?
*
* @param {number} r : pt's radial coordinate
* @param {number} a : pt's angular coordinate in *radians*
* @param {2-item array} rBnds : sector's radial bounds
* @param {2-item array} aBnds : sector's angular bounds in *radians*
* @return {boolean}
*/
function isPtInsideSector(r, a, rBnds, aBnds) {
if (!isAngleInsideSector(a, aBnds)) return false;
var r0, r1;
if (rBnds[0] < rBnds[1]) {
r0 = rBnds[0];
r1 = rBnds[1];
} else {
r0 = rBnds[1];
r1 = rBnds[0];
}
return r >= r0 && r <= r1;
}
// common to pathArc, pathSector and pathAnnulus
function _path(r0, r1, a0, a1, cx, cy, isClosed) {
cx = cx || 0;
cy = cy || 0;
var isCircle = isFullCircle([a0, a1]);
var aStart, aMid, aEnd;
var rStart, rEnd;
if (isCircle) {
aStart = 0;
aMid = PI;
aEnd = twoPI;
} else {
if (a0 < a1) {
aStart = a0;
aEnd = a1;
} else {
aStart = a1;
aEnd = a0;
}
}
if (r0 < r1) {
rStart = r0;
rEnd = r1;
} else {
rStart = r1;
rEnd = r0;
}
// N.B. svg coordinates here, where y increases downward
function pt(r, a) {
return [r * Math.cos(a) + cx, cy - r * Math.sin(a)];
}
var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1;
function arc(r, a, cw) {
return 'A' + [r, r] + ' ' + [0, largeArc, cw] + ' ' + pt(r, a);
}
var p;
if (isCircle) {
if (rStart === null) {
p = 'M' + pt(rEnd, aStart) + arc(rEnd, aMid, 0) + arc(rEnd, aEnd, 0) + 'Z';
} else {
p = 'M' + pt(rStart, aStart) + arc(rStart, aMid, 0) + arc(rStart, aEnd, 0) + 'Z' + 'M' + pt(rEnd, aStart) + arc(rEnd, aMid, 1) + arc(rEnd, aEnd, 1) + 'Z';
}
} else {
if (rStart === null) {
p = 'M' + pt(rEnd, aStart) + arc(rEnd, aEnd, 0);
if (isClosed) p += 'L0,0Z';
} else {
p = 'M' + pt(rStart, aStart) + 'L' + pt(rEnd, aStart) + arc(rEnd, aEnd, 0) + 'L' + pt(rStart, aEnd) + arc(rStart, aStart, 1) + 'Z';
}
}
return p;
}
/**
* path an arc
*
* @param {number} r : radius
* @param {number} a0 : first angular coordinate in *radians*
* @param {number} a1 : second angular coordinate in *radians*
* @param {number (optional)} cx : x coordinate of center
* @param {number (optional)} cy : y coordinate of center
* @return {string} svg path
*/
function pathArc(r, a0, a1, cx, cy) {
return _path(null, r, a0, a1, cx, cy, 0);
}
/**
* path a sector
*
* @param {number} r : radius
* @param {number} a0 : first angular coordinate in *radians*
* @param {number} a1 : second angular coordinate in *radians*
* @param {number (optional)} cx : x coordinate of center
* @param {number (optional)} cy : y coordinate of center
* @return {string} svg path
*/
function pathSector(r, a0, a1, cx, cy) {
return _path(null, r, a0, a1, cx, cy, 1);
}
/**
* path an annulus
*
* @param {number} r0 : first radial coordinate
* @param {number} r1 : second radial coordinate
* @param {number} a0 : first angular coordinate in *radians*
* @param {number} a1 : second angular coordinate in *radians*
* @param {number (optional)} cx : x coordinate of center
* @param {number (optional)} cy : y coordinate of center
* @return {string} svg path
*/
function pathAnnulus(r0, r1, a0, a1, cx, cy) {
return _path(r0, r1, a0, a1, cx, cy, 1);
}
module.exports = {
deg2rad: deg2rad,
rad2deg: rad2deg,
angleDelta: angleDelta,
angleDist: angleDist,
isFullCircle: isFullCircle,
isAngleInsideSector: isAngleInsideSector,
isPtInsideSector: isPtInsideSector,
pathArc: pathArc,
pathSector: pathSector,
pathAnnulus: pathAnnulus
};
/***/ }),
/***/ 38116:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var b64decode = (__webpack_require__(83160).decode);
var isPlainObject = __webpack_require__(63620);
var isArray = Array.isArray;
var ab = ArrayBuffer;
var dv = DataView;
function isTypedArray(a) {
return ab.isView(a) && !(a instanceof dv);
}
exports.isTypedArray = isTypedArray;
function isArrayOrTypedArray(a) {
return isArray(a) || isTypedArray(a);
}
exports.isArrayOrTypedArray = isArrayOrTypedArray;
/*
* Test whether an input object is 1D.
*
* Assumes we already know the object is an array.
*
* Looks only at the first element, if the dimensionality is
* not consistent we won't figure that out here.
*/
function isArray1D(a) {
return !isArrayOrTypedArray(a[0]);
}
exports.isArray1D = isArray1D;
/*
* Ensures an array has the right amount of storage space. If it doesn't
* exist, it creates an array. If it does exist, it returns it if too
* short or truncates it in-place.
*
* The goal is to just reuse memory to avoid a bit of excessive garbage
* collection.
*/
exports.ensureArray = function (out, n) {
// TODO: typed array support here? This is only used in
// traces/carpet/compute_control_points
if (!isArray(out)) out = [];
// If too long, truncate. (If too short, it will grow
// automatically so we don't care about that case)
out.length = n;
return out;
};
var typedArrays = {
u1c: typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
// not supported in numpy?
i1: typeof Int8Array === 'undefined' ? undefined : Int8Array,
u1: typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
i2: typeof Int16Array === 'undefined' ? undefined : Int16Array,
u2: typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
i4: typeof Int32Array === 'undefined' ? undefined : Int32Array,
u4: typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
f4: typeof Float32Array === 'undefined' ? undefined : Float32Array,
f8: typeof Float64Array === 'undefined' ? undefined : Float64Array
/* TODO: potentially add Big Int
i8: typeof BigInt64Array === 'undefined' ? undefined :
BigInt64Array,
u8: typeof BigUint64Array === 'undefined' ? undefined :
BigUint64Array,
*/
};
typedArrays.uint8c = typedArrays.u1c;
typedArrays.uint8 = typedArrays.u1;
typedArrays.int8 = typedArrays.i1;
typedArrays.uint16 = typedArrays.u2;
typedArrays.int16 = typedArrays.i2;
typedArrays.uint32 = typedArrays.u4;
typedArrays.int32 = typedArrays.i4;
typedArrays.float32 = typedArrays.f4;
typedArrays.float64 = typedArrays.f8;
function isArrayBuffer(a) {
return a.constructor === ArrayBuffer;
}
exports.isArrayBuffer = isArrayBuffer;
exports.decodeTypedArraySpec = function (vIn) {
var out = [];
var v = coerceTypedArraySpec(vIn);
var dtype = v.dtype;
var T = typedArrays[dtype];
if (!T) throw new Error('Error in dtype: "' + dtype + '"');
var BYTES_PER_ELEMENT = T.BYTES_PER_ELEMENT;
var buffer = v.bdata;
if (!isArrayBuffer(buffer)) {
buffer = b64decode(buffer);
}
var shape = v.shape === undefined ?
// detect 1-d length
[buffer.byteLength / BYTES_PER_ELEMENT] :
// convert number to string and split to array
('' + v.shape).split(',');
shape.reverse(); // i.e. to match numpy order
var ndim = shape.length;
var nj, j;
var ni = +shape[0];
var rowBytes = BYTES_PER_ELEMENT * ni;
var pos = 0;
if (ndim === 1) {
out = new T(buffer);
} else if (ndim === 2) {
nj = +shape[1];
for (j = 0; j < nj; j++) {
out[j] = new T(buffer, pos, ni);
pos += rowBytes;
}
} else if (ndim === 3) {
nj = +shape[1];
var nk = +shape[2];
for (var k = 0; k < nk; k++) {
out[k] = [];
for (j = 0; j < nj; j++) {
out[k][j] = new T(buffer, pos, ni);
pos += rowBytes;
}
}
} else {
throw new Error('ndim: ' + ndim + 'is not supported with the shape:"' + v.shape + '"');
}
// attach bdata, dtype & shape to array for json export
out.bdata = v.bdata;
out.dtype = v.dtype;
out.shape = shape.reverse().join(',');
vIn._inputArray = out;
return out;
};
exports.isTypedArraySpec = function (v) {
return isPlainObject(v) && v.hasOwnProperty('dtype') && typeof v.dtype === 'string' && v.hasOwnProperty('bdata') && (typeof v.bdata === 'string' || isArrayBuffer(v.bdata)) && (v.shape === undefined || v.hasOwnProperty('shape') && (typeof v.shape === 'string' || typeof v.shape === 'number'));
};
function coerceTypedArraySpec(v) {
return {
bdata: v.bdata,
dtype: v.dtype,
shape: v.shape
};
}
/*
* TypedArray-compatible concatenation of n arrays
* if all arrays are the same type it will preserve that type,
* otherwise it falls back on Array.
* Also tries to avoid copying, in case one array has zero length
* But never mutates an existing array
*/
exports.concat = function () {
var args = [];
var allArray = true;
var totalLen = 0;
var _constructor, arg0, i, argi, posi, leni, out, j;
for (i = 0; i < arguments.length; i++) {
argi = arguments[i];
leni = argi.length;
if (leni) {
if (arg0) args.push(argi);else {
arg0 = argi;
posi = leni;
}
if (isArray(argi)) {
_constructor = false;
} else {
allArray = false;
if (!totalLen) {
_constructor = argi.constructor;
} else if (_constructor !== argi.constructor) {
// TODO: in principle we could upgrade here,
// ie keep typed array but convert all to Float64Array?
_constructor = false;
}
}
totalLen += leni;
}
}
if (!totalLen) return [];
if (!args.length) return arg0;
if (allArray) return arg0.concat.apply(arg0, args);
if (_constructor) {
// matching typed arrays
out = new _constructor(totalLen);
out.set(arg0);
for (i = 0; i < args.length; i++) {
argi = args[i];
out.set(argi, posi);
posi += argi.length;
}
return out;
}
// mismatched types or Array + typed
out = new Array(totalLen);
for (j = 0; j < arg0.length; j++) out[j] = arg0[j];
for (i = 0; i < args.length; i++) {
argi = args[i];
for (j = 0; j < argi.length; j++) out[posi + j] = argi[j];
posi += j;
}
return out;
};
exports.maxRowLength = function (z) {
return _rowLength(z, Math.max, 0);
};
exports.minRowLength = function (z) {
return _rowLength(z, Math.min, Infinity);
};
function _rowLength(z, fn, len0) {
if (isArrayOrTypedArray(z)) {
if (isArrayOrTypedArray(z[0])) {
var len = len0;
for (var i = 0; i < z.length; i++) {
len = fn(len, z[i].length);
}
return len;
} else {
return z.length;
}
}
return 0;
}
/***/ }),
/***/ 54037:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var BADNUM = (__webpack_require__(39032).BADNUM);
// precompile for speed
var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;
/**
* cleanNumber: remove common leading and trailing cruft
* Always returns either a number or BADNUM.
*/
module.exports = function cleanNumber(v) {
if (typeof v === 'string') {
v = v.replace(JUNK, '');
}
if (isNumeric(v)) return Number(v);
return BADNUM;
};
/***/ }),
/***/ 73696:
/***/ (function(module) {
"use strict";
/**
* Clear gl frame (if any). This is a common pattern as
* we usually set `preserveDrawingBuffer: true` during
* gl context creation (e.g. via `reglUtils.prepare`).
*
* @param {DOM node or object} gd : graph div object
*/
module.exports = function clearGlCanvases(gd) {
var fullLayout = gd._fullLayout;
if (fullLayout._glcanvas && fullLayout._glcanvas.size()) {
fullLayout._glcanvas.each(function (d) {
if (d.regl) d.regl.clear({
color: true,
depth: true
});
});
}
};
/***/ }),
/***/ 75352:
/***/ (function(module) {
"use strict";
/**
* Clear responsive handlers (if any).
*
* @param {DOM node or object} gd : graph div object
*/
module.exports = function clearResponsive(gd) {
if (gd._responsiveChartHandler) {
window.removeEventListener('resize', gd._responsiveChartHandler);
delete gd._responsiveChartHandler;
}
};
/***/ }),
/***/ 63064:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var tinycolor = __webpack_require__(49760);
var extendFlat = (__webpack_require__(92880).extendFlat);
var baseTraceAttrs = __webpack_require__(45464);
var colorscales = __webpack_require__(88304);
var Color = __webpack_require__(76308);
var DESELECTDIM = (__webpack_require__(13448).DESELECTDIM);
var nestedProperty = __webpack_require__(22296);
var counterRegex = (__webpack_require__(53756).counter);
var modHalf = (__webpack_require__(20435).modHalf);
var isArrayOrTypedArray = (__webpack_require__(38116).isArrayOrTypedArray);
var isTypedArraySpec = (__webpack_require__(38116).isTypedArraySpec);
var decodeTypedArraySpec = (__webpack_require__(38116).decodeTypedArraySpec);
exports.valObjectMeta = {
data_array: {
// You can use *dflt=[] to force said array to exist though.
coerceFunction: function (v, propOut, dflt) {
propOut.set(isArrayOrTypedArray(v) ? v : isTypedArraySpec(v) ? decodeTypedArraySpec(v) : dflt);
}
},
enumerated: {
coerceFunction: function (v, propOut, dflt, opts) {
if (opts.coerceNumber) v = +v;
if (opts.values.indexOf(v) === -1) propOut.set(dflt);else propOut.set(v);
},
validateFunction: function (v, opts) {
if (opts.coerceNumber) v = +v;
var values = opts.values;
for (var i = 0; i < values.length; i++) {
var k = String(values[i]);
if (k.charAt(0) === '/' && k.charAt(k.length - 1) === '/') {
var regex = new RegExp(k.substr(1, k.length - 2));
if (regex.test(v)) return true;
} else if (v === values[i]) return true;
}
return false;
}
},
boolean: {
coerceFunction: function (v, propOut, dflt) {
if (v === true || v === false) propOut.set(v);else propOut.set(dflt);
}
},
number: {
coerceFunction: function (v, propOut, dflt, opts) {
if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
if (!isNumeric(v) || opts.min !== undefined && v < opts.min || opts.max !== undefined && v > opts.max) {
propOut.set(dflt);
} else propOut.set(+v);
}
},
integer: {
coerceFunction: function (v, propOut, dflt, opts) {
if ((opts.extras || []).indexOf(v) !== -1) {
propOut.set(v);
return;
}
if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
if (v % 1 || !isNumeric(v) || opts.min !== undefined && v < opts.min || opts.max !== undefined && v > opts.max) {
propOut.set(dflt);
} else propOut.set(+v);
}
},
string: {
// TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
coerceFunction: function (v, propOut, dflt, opts) {
if (typeof v !== 'string') {
var okToCoerce = typeof v === 'number';
if (opts.strict === true || !okToCoerce) propOut.set(dflt);else propOut.set(String(v));
} else if (opts.noBlank && !v) propOut.set(dflt);else propOut.set(v);
}
},
color: {
coerceFunction: function (v, propOut, dflt) {
if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
if (tinycolor(v).isValid()) propOut.set(v);else propOut.set(dflt);
}
},
colorlist: {
coerceFunction: function (v, propOut, dflt) {
function isColor(color) {
return tinycolor(color).isValid();
}
if (!Array.isArray(v) || !v.length) propOut.set(dflt);else if (v.every(isColor)) propOut.set(v);else propOut.set(dflt);
}
},
colorscale: {
coerceFunction: function (v, propOut, dflt) {
propOut.set(colorscales.get(v, dflt));
}
},
angle: {
coerceFunction: function (v, propOut, dflt) {
if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
if (v === 'auto') propOut.set('auto');else if (!isNumeric(v)) propOut.set(dflt);else propOut.set(modHalf(+v, 360));
}
},
subplotid: {
coerceFunction: function (v, propOut, dflt, opts) {
var regex = opts.regex || counterRegex(dflt);
if (typeof v === 'string' && regex.test(v)) {
propOut.set(v);
return;
}
propOut.set(dflt);
},
validateFunction: function (v, opts) {
var dflt = opts.dflt;
if (v === dflt) return true;
if (typeof v !== 'string') return false;
if (counterRegex(dflt).test(v)) return true;
return false;
}
},
flaglist: {
coerceFunction: function (v, propOut, dflt, opts) {
if ((opts.extras || []).indexOf(v) !== -1) {
propOut.set(v);
return;
}
if (typeof v !== 'string') {
propOut.set(dflt);
return;
}
var vParts = v.split('+');
var i = 0;
while (i < vParts.length) {
var vi = vParts[i];
if (opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) {
vParts.splice(i, 1);
} else i++;
}
if (!vParts.length) propOut.set(dflt);else propOut.set(vParts.join('+'));
}
},
any: {
coerceFunction: function (v, propOut, dflt) {
if (v === undefined) {
propOut.set(dflt);
} else {
propOut.set(isTypedArraySpec(v) ? decodeTypedArraySpec(v) : v);
}
}
},
info_array: {
// set `dimensions=2` for a 2D array or '1-2' for either
// `items` may be a single object instead of an array, in which case
// `freeLength` must be true.
// if `dimensions='1-2'` and items is a 1D array, then the value can
// either be a matching 1D array or an array of such matching 1D arrays
coerceFunction: function (v, propOut, dflt, opts) {
// simplified coerce function just for array items
function coercePart(v, opts, dflt) {
var out;
var propPart = {
set: function (v) {
out = v;
}
};
if (dflt === undefined) dflt = opts.dflt;
exports.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts);
return out;
}
if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
if (!isArrayOrTypedArray(v)) {
propOut.set(dflt);
return;
}
var twoD = opts.dimensions === 2 || opts.dimensions === '1-2' && Array.isArray(v) && isArrayOrTypedArray(v[0]);
var items = opts.items;
var vOut = [];
var arrayItems = Array.isArray(items);
var arrayItems2D = arrayItems && twoD && isArrayOrTypedArray(items[0]);
var innerItemsOnly = twoD && arrayItems && !arrayItems2D;
var len = arrayItems && !innerItemsOnly ? items.length : v.length;
var i, j, row, item, len2, vNew;
dflt = Array.isArray(dflt) ? dflt : [];
if (twoD) {
for (i = 0; i < len; i++) {
vOut[i] = [];
row = isArrayOrTypedArray(v[i]) ? v[i] : [];
if (innerItemsOnly) len2 = items.length;else if (arrayItems) len2 = items[i].length;else len2 = row.length;
for (j = 0; j < len2; j++) {
if (innerItemsOnly) item = items[j];else if (arrayItems) item = items[i][j];else item = items;
vNew = coercePart(row[j], item, (dflt[i] || [])[j]);
if (vNew !== undefined) vOut[i][j] = vNew;
}
}
} else {
for (i = 0; i < len; i++) {
vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]);
if (vNew !== undefined) vOut[i] = vNew;
}
}
propOut.set(vOut);
},
validateFunction: function (v, opts) {
if (!isArrayOrTypedArray(v)) return false;
var items = opts.items;
var arrayItems = Array.isArray(items);
var twoD = opts.dimensions === 2;
// when free length is off, input and declared lengths must match
if (!opts.freeLength && v.length !== items.length) return false;
// valid when all input items are valid
for (var i = 0; i < v.length; i++) {
if (twoD) {
if (!isArrayOrTypedArray(v[i]) || !opts.freeLength && v[i].length !== items[i].length) {
return false;
}
for (var j = 0; j < v[i].length; j++) {
if (!validate(v[i][j], arrayItems ? items[i][j] : items)) {
return false;
}
}
} else if (!validate(v[i], arrayItems ? items[i] : items)) return false;
}
return true;
}
}
};
/**
* Ensures that container[attribute] has a valid value.
*
* attributes[attribute] is an object with possible keys:
* - valType: data_array, enumerated, boolean, ... as in valObjectMeta
* - values: (enumerated only) array of allowed vals
* - min, max: (number, integer only) inclusive bounds on allowed vals
* either or both may be omitted
* - dflt: if attribute is invalid or missing, use this default
* if dflt is provided as an argument to lib.coerce it takes precedence
* as a convenience, returns the value it finally set
*/
exports.coerce = function (containerIn, containerOut, attributes, attribute, dflt) {
var opts = nestedProperty(attributes, attribute).get();
var propIn = nestedProperty(containerIn, attribute);
var propOut = nestedProperty(containerOut, attribute);
var v = propIn.get();
var template = containerOut._template;
if (v === undefined && template) {
v = nestedProperty(template, attribute).get();
// already used the template value, so short-circuit the second check
template = 0;
}
if (dflt === undefined) dflt = opts.dflt;
if (opts.arrayOk) {
if (isArrayOrTypedArray(v)) {
/**
* arrayOk: value MAY be an array, then we do no value checking
* at this point, because it can be more complicated than the
* individual form (eg. some array vals can be numbers, even if the
* single values must be color strings)
*/
propOut.set(v);
return v;
} else {
if (isTypedArraySpec(v)) {
v = decodeTypedArraySpec(v);
propOut.set(v);
return v;
}
}
}
var coerceFunction = exports.valObjectMeta[opts.valType].coerceFunction;
coerceFunction(v, propOut, dflt, opts);
var out = propOut.get();
// in case v was provided but invalid, try the template again so it still
// overrides the regular default
if (template && out === dflt && !validate(v, opts)) {
v = nestedProperty(template, attribute).get();
coerceFunction(v, propOut, dflt, opts);
out = propOut.get();
}
return out;
};
/**
* Variation on coerce
*
* Uses coerce to get attribute value if user input is valid,
* returns attribute default if user input it not valid or
* returns false if there is no user input.
*/
exports.coerce2 = function (containerIn, containerOut, attributes, attribute, dflt) {
var propIn = nestedProperty(containerIn, attribute);
var propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt);
var valIn = propIn.get();
return valIn !== undefined && valIn !== null ? propOut : false;
};
/*
* Shortcut to coerce the three font attributes
*
* 'coerce' is a lib.coerce wrapper with implied first three arguments
*/
exports.coerceFont = function (coerce, attr, dfltObj, opts) {
if (!opts) opts = {};
dfltObj = extendFlat({}, dfltObj);
dfltObj = extendFlat(dfltObj, opts.overrideDflt || {});
var out = {
family: coerce(attr + '.family', dfltObj.family),
size: coerce(attr + '.size', dfltObj.size),
color: coerce(attr + '.color', dfltObj.color),
weight: coerce(attr + '.weight', dfltObj.weight),
style: coerce(attr + '.style', dfltObj.style)
};
if (!opts.noFontVariant) out.variant = coerce(attr + '.variant', dfltObj.variant);
if (!opts.noFontLineposition) out.lineposition = coerce(attr + '.lineposition', dfltObj.lineposition);
if (!opts.noFontTextcase) out.textcase = coerce(attr + '.textcase', dfltObj.textcase);
if (!opts.noFontShadow) {
var dfltShadow = dfltObj.shadow;
if (dfltShadow === 'none' && opts.autoShadowDflt) {
dfltShadow = 'auto';
}
out.shadow = coerce(attr + '.shadow', dfltShadow);
}
return out;
};
/*
* Shortcut to coerce the pattern attributes
*/
exports.coercePattern = function (coerce, attr, markerColor, hasMarkerColorscale) {
var shape = coerce(attr + '.shape');
if (shape) {
coerce(attr + '.solidity');
coerce(attr + '.size');
var fillmode = coerce(attr + '.fillmode');
var isOverlay = fillmode === 'overlay';
if (!hasMarkerColorscale) {
var bgcolor = coerce(attr + '.bgcolor', isOverlay ? markerColor : undefined);
coerce(attr + '.fgcolor', isOverlay ? Color.contrast(bgcolor) : markerColor);
}
coerce(attr + '.fgopacity', isOverlay ? 0.5 : 1);
}
};
/** Coerce shortcut for 'hoverinfo'
* handling 1-vs-multi-trace dflt logic
*
* @param {object} traceIn : user trace object
* @param {object} traceOut : full trace object (requires _module ref)
* @param {object} layoutOut : full layout object (require _dataLength ref)
* @return {any} : the coerced value
*/
exports.coerceHoverinfo = function (traceIn, traceOut, layoutOut) {
var moduleAttrs = traceOut._module.attributes;
var attrs = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs;
var valObj = attrs.hoverinfo;
var dflt;
if (layoutOut._dataLength === 1) {
var flags = valObj.dflt === 'all' ? valObj.flags.slice() : valObj.dflt.split('+');
flags.splice(flags.indexOf('name'), 1);
dflt = flags.join('+');
}
return exports.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt);
};
/** Coerce shortcut for [un]selected.marker.opacity,
* which has special default logic, to ensure that it corresponds to the
* default selection behavior while allowing to be overtaken by any other
* [un]selected attribute.
*
* N.B. This must be called *after* coercing all the other [un]selected attrs,
* to give the intended result.
*
* @param {object} traceOut : fullData item
* @param {function} coerce : lib.coerce wrapper with implied first three arguments
*/
exports.coerceSelectionMarkerOpacity = function (traceOut, coerce) {
if (!traceOut.marker) return;
var mo = traceOut.marker.opacity;
// you can still have a `marker` container with no markers if there's text
if (mo === undefined) return;
var smoDflt;
var usmoDflt;
// Don't give [un]selected.marker.opacity a default value if
// marker.opacity is an array: handle this during style step.
//
// Only give [un]selected.marker.opacity a default value if you don't
// set any other [un]selected attributes.
if (!isArrayOrTypedArray(mo) && !traceOut.selected && !traceOut.unselected) {
smoDflt = mo;
usmoDflt = DESELECTDIM * mo;
}
coerce('selected.marker.opacity', smoDflt);
coerce('unselected.marker.opacity', usmoDflt);
};
function validate(value, opts) {
var valObjectDef = exports.valObjectMeta[opts.valType];
if (opts.arrayOk && isArrayOrTypedArray(value)) return true;
if (valObjectDef.validateFunction) {
return valObjectDef.validateFunction(value, opts);
}
var failed = {};
var out = failed;
var propMock = {
set: function (v) {
out = v;
}
};
// 'failed' just something mutable that won't be === anything else
valObjectDef.coerceFunction(value, propMock, failed, opts);
return out !== failed;
}
exports.validate = validate;
/***/ }),
/***/ 67555:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var timeFormat = (__webpack_require__(94336)/* .timeFormat */ .Yn);
var isNumeric = __webpack_require__(38248);
var Loggers = __webpack_require__(24248);
var mod = (__webpack_require__(20435).mod);
var constants = __webpack_require__(39032);
var BADNUM = constants.BADNUM;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var EPOCHJD = constants.EPOCHJD;
var Registry = __webpack_require__(24040);
var utcFormat = (__webpack_require__(94336)/* .utcFormat */ .E9);
var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d(:?\d\d)?)?)?)?)?)?\s*$/m;
// special regex for chinese calendars to support yyyy-mmi-dd etc for intercalary months
var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d(:?\d\d)?)?)?)?)?)?\s*$/m;
// for 2-digit years, the first year we map them onto
var YFIRST = new Date().getFullYear() - 70;
function isWorldCalendar(calendar) {
return calendar && Registry.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian';
}
/*
* dateTick0: get the canonical tick for this calendar
*
* integer weekdays : Saturday: 0, Sunday: 1, Monday: 2, etc.
*/
exports.dateTick0 = function (calendar, dayOfWeek) {
var tick0 = _dateTick0(calendar, !!dayOfWeek);
if (dayOfWeek < 2) return tick0;
var v = exports.dateTime2ms(tick0, calendar);
v += ONEDAY * (dayOfWeek - 1); // shift Sunday to Monday, etc.
return exports.ms2DateTime(v, 0, calendar);
};
/*
* _dateTick0: get the canonical tick for this calendar
*
* bool sunday is for week ticks, shift it to a Sunday.
*/
function _dateTick0(calendar, sunday) {
if (isWorldCalendar(calendar)) {
return sunday ? Registry.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : Registry.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar];
} else {
return sunday ? '2000-01-02' : '2000-01-01';
}
}
/*
* dfltRange: for each calendar, give a valid default range
*/
exports.dfltRange = function (calendar) {
if (isWorldCalendar(calendar)) {
return Registry.getComponentMethod('calendars', 'DFLTRANGE')[calendar];
} else {
return ['2000-01-01', '2001-01-01'];
}
};
// is an object a javascript date?
exports.isJSDate = function (v) {
return typeof v === 'object' && v !== null && typeof v.getTime === 'function';
};
// The absolute limits of our date-time system
// This is a little weird: we use MIN_MS and MAX_MS in dateTime2ms
// but we use dateTime2ms to calculate them (after defining it!)
var MIN_MS, MAX_MS;
/**
* dateTime2ms - turn a date object or string s into milliseconds
* (relative to 1970-01-01, per javascript standard)
* optional calendar (string) to use a non-gregorian calendar
*
* Returns BADNUM if it doesn't find a date
*
* strings should have the form:
*
* -?YYYY-mm-ddHH:MM:SS.sss?
*
* : space (our normal standard) or T or t (ISO-8601)
* : Z, z, [+\-]HH:?MM or [+\-]HH and we THROW IT AWAY
* this format comes from https://tools.ietf.org/html/rfc3339#section-5.6
* and 4.2.5.1 Difference between local time and UTC of day (ISO-8601)
* but we allow it even with a space as the separator
*
* May truncate after any full field, and sss can be any length
* even >3 digits, though javascript dates truncate to milliseconds,
* we keep as much as javascript numeric precision can hold, but we only
* report back up to 100 microsecond precision, because most dates support
* this precision (close to 1970 support more, very far away support less)
*
* Expanded to support negative years to -9999 but you must always
* give 4 digits, except for 2-digit positive years which we assume are
* near the present time.
* Note that we follow ISO 8601:2004: there *is* a year 0, which
* is 1BC/BCE, and -1===2BC etc.
*
* World calendars: not all of these *have* agreed extensions to this full range,
* if you have another calendar system but want a date range outside its validity,
* you can use a gregorian date string prefixed with 'G' or 'g'.
*
* Where to cut off 2-digit years between 1900s and 2000s?
* from https://docs.microsoft.com/en-us/office/troubleshoot/excel/two-digit-year-numbers#the-2029-rule:
* 1930-2029 (the most retro of all...)
* but in my mac chrome from eg. d=new Date(Date.parse('8/19/50')):
* 1950-2049
* by Java, from http://stackoverflow.com/questions/2024273/:
* now-80 - now+19
* or FileMaker Pro, from
* https://fmhelp.filemaker.com/help/18/fmp/en/index.html#page/FMP_Help/dates-with-two-digit-years.html:
* now-70 - now+29
* but python strptime etc, via
* http://docs.python.org/py3k/library/time.html:
* 1969-2068 (super forward-looking, but static, not sliding!)
*
* lets go with now-70 to now+29, and if anyone runs into this problem
* they can learn the hard way not to use 2-digit years, as no choice we
* make now will cover all possibilities. mostly this will all be taken
* care of in initial parsing, should only be an issue for hand-entered data
* currently (2016) this range is:
* 1946-2045
*/
exports.dateTime2ms = function (s, calendar) {
// first check if s is a date object
if (exports.isJSDate(s)) {
// Convert to the UTC milliseconds that give the same
// hours as this date has in the local timezone
var tzOffset = s.getTimezoneOffset() * ONEMIN;
var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN + (s.getUTCSeconds() - s.getSeconds()) * ONESEC + (s.getUTCMilliseconds() - s.getMilliseconds());
if (offsetTweak) {
var comb = 3 * ONEMIN;
tzOffset = tzOffset - comb / 2 + mod(offsetTweak - tzOffset + comb / 2, comb);
}
s = Number(s) - tzOffset;
if (s >= MIN_MS && s <= MAX_MS) return s;
return BADNUM;
}
// otherwise only accept strings and numbers
if (typeof s !== 'string' && typeof s !== 'number') return BADNUM;
s = String(s);
var isWorld = isWorldCalendar(calendar);
// to handle out-of-range dates in international calendars, accept
// 'G' as a prefix to force the built-in gregorian calendar.
var s0 = s.charAt(0);
if (isWorld && (s0 === 'G' || s0 === 'g')) {
s = s.substr(1);
calendar = '';
}
var isChinese = isWorld && calendar.substr(0, 7) === 'chinese';
var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP);
if (!match) return BADNUM;
var y = match[1];
var m = match[3] || '1';
var d = Number(match[5] || 1);
var H = Number(match[7] || 0);
var M = Number(match[9] || 0);
var S = Number(match[11] || 0);
if (isWorld) {
// disallow 2-digit years for world calendars
if (y.length === 2) return BADNUM;
y = Number(y);
var cDate;
try {
var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
if (isChinese) {
var isIntercalary = m.charAt(m.length - 1) === 'i';
m = parseInt(m, 10);
cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d);
} else {
cDate = calInstance.newDate(y, Number(m), d);
}
} catch (e) {
return BADNUM;
} // Invalid ... date
if (!cDate) return BADNUM;
return (cDate.toJD() - EPOCHJD) * ONEDAY + H * ONEHOUR + M * ONEMIN + S * ONESEC;
}
if (y.length === 2) {
y = (Number(y) + 2000 - YFIRST) % 100 + YFIRST;
} else y = Number(y);
// new Date uses months from 0; subtract 1 here just so we
// don't have to do it again during the validity test below
m -= 1;
// javascript takes new Date(0..99,m,d) to mean 1900-1999, so
// to support years 0-99 we need to use setFullYear explicitly
// Note that 2000 is a leap year.
var date = new Date(Date.UTC(2000, m, d, H, M));
date.setUTCFullYear(y);
if (date.getUTCMonth() !== m) return BADNUM;
if (date.getUTCDate() !== d) return BADNUM;
return date.getTime() + S * ONESEC;
};
MIN_MS = exports.MIN_MS = exports.dateTime2ms('-9999');
MAX_MS = exports.MAX_MS = exports.dateTime2ms('9999-12-31 23:59:59.9999');
// is string s a date? (see above)
exports.isDateTime = function (s, calendar) {
return exports.dateTime2ms(s, calendar) !== BADNUM;
};
// pad a number with zeroes, to given # of digits before the decimal point
function lpad(val, digits) {
return String(val + Math.pow(10, digits)).substr(1);
}
/**
* Turn ms into string of the form YYYY-mm-dd HH:MM:SS.ssss
* Crop any trailing zeros in time, except never stop right after hours
* (we could choose to crop '-01' from date too but for now we always
* show the whole date)
* Optional range r is the data range that applies, also in ms.
* If rng is big, the later parts of time will be omitted
*/
var NINETYDAYS = 90 * ONEDAY;
var THREEHOURS = 3 * ONEHOUR;
var FIVEMIN = 5 * ONEMIN;
exports.ms2DateTime = function (ms, r, calendar) {
if (typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM;
if (!r) r = 0;
var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
var msRounded = Math.round(ms - msecTenths / 10);
var dateStr, h, m, s, msec10, d;
if (isWorldCalendar(calendar)) {
var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD;
var timeMs = Math.floor(mod(ms, ONEDAY));
try {
dateStr = Registry.getComponentMethod('calendars', 'getCal')(calendar).fromJD(dateJD).formatDate('yyyy-mm-dd');
} catch (e) {
// invalid date in this calendar - fall back to Gyyyy-mm-dd
dateStr = utcFormat('G%Y-%m-%d')(new Date(msRounded));
}
// yyyy does NOT guarantee 4-digit years. YYYY mostly does, but does
// other things for a few calendars, so we can't trust it. Just pad
// it manually (after the '-' if there is one)
if (dateStr.charAt(0) === '-') {
while (dateStr.length < 11) dateStr = '-0' + dateStr.substr(1);
} else {
while (dateStr.length < 10) dateStr = '0' + dateStr;
}
// TODO: if this is faster, we could use this block for extracting
// the time components of regular gregorian too
h = r < NINETYDAYS ? Math.floor(timeMs / ONEHOUR) : 0;
m = r < NINETYDAYS ? Math.floor(timeMs % ONEHOUR / ONEMIN) : 0;
s = r < THREEHOURS ? Math.floor(timeMs % ONEMIN / ONESEC) : 0;
msec10 = r < FIVEMIN ? timeMs % ONESEC * 10 + msecTenths : 0;
} else {
d = new Date(msRounded);
dateStr = utcFormat('%Y-%m-%d')(d);
// <90 days: add hours and minutes - never *only* add hours
h = r < NINETYDAYS ? d.getUTCHours() : 0;
m = r < NINETYDAYS ? d.getUTCMinutes() : 0;
// <3 hours: add seconds
s = r < THREEHOURS ? d.getUTCSeconds() : 0;
// <5 minutes: add ms (plus one extra digit, this is msec*10)
msec10 = r < FIVEMIN ? d.getUTCMilliseconds() * 10 + msecTenths : 0;
}
return includeTime(dateStr, h, m, s, msec10);
};
// For converting old-style milliseconds to date strings,
// we use the local timezone rather than UTC like we use
// everywhere else, both for backward compatibility and
// because that's how people mostly use javasript date objects.
// Clip one extra day off our date range though so we can't get
// thrown beyond the range by the timezone shift.
exports.ms2DateTimeLocal = function (ms) {
if (!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return BADNUM;
var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
var d = new Date(Math.round(ms - msecTenths / 10));
var dateStr = timeFormat('%Y-%m-%d')(d);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var msec10 = d.getUTCMilliseconds() * 10 + msecTenths;
return includeTime(dateStr, h, m, s, msec10);
};
function includeTime(dateStr, h, m, s, msec10) {
// include each part that has nonzero data in or after it
if (h || m || s || msec10) {
dateStr += ' ' + lpad(h, 2) + ':' + lpad(m, 2);
if (s || msec10) {
dateStr += ':' + lpad(s, 2);
if (msec10) {
var digits = 4;
while (msec10 % 10 === 0) {
digits -= 1;
msec10 /= 10;
}
dateStr += '.' + lpad(msec10, digits);
}
}
}
return dateStr;
}
// normalize date format to date string, in case it starts as
// a Date object or milliseconds
// optional dflt is the return value if cleaning fails
exports.cleanDate = function (v, dflt, calendar) {
// let us use cleanDate to provide a missing default without an error
if (v === BADNUM) return dflt;
if (exports.isJSDate(v) || typeof v === 'number' && isFinite(v)) {
// do not allow milliseconds (old) or jsdate objects (inherently
// described as gregorian dates) with world calendars
if (isWorldCalendar(calendar)) {
Loggers.error('JS Dates and milliseconds are incompatible with world calendars', v);
return dflt;
}
// NOTE: if someone puts in a year as a number rather than a string,
// this will mistakenly convert it thinking it's milliseconds from 1970
// that is: '2012' -> Jan. 1, 2012, but 2012 -> 2012 epoch milliseconds
v = exports.ms2DateTimeLocal(+v);
if (!v && dflt !== undefined) return dflt;
} else if (!exports.isDateTime(v, calendar)) {
Loggers.error('unrecognized date', v);
return dflt;
}
return v;
};
/*
* Date formatting for ticks and hovertext
*/
/*
* modDateFormat: Support world calendars, and add two items to
* d3's vocabulary:
* %{n}f where n is the max number of digits of fractional seconds
* %h formats: half of the year as a decimal number [1,2]
*/
var fracMatch = /%\d?f/g;
var halfYearMatch = /%h/g;
var quarterToHalfYear = {
1: '1',
2: '1',
3: '2',
4: '2'
};
function modDateFormat(fmt, x, formatter, calendar) {
fmt = fmt.replace(fracMatch, function (match) {
var digits = Math.min(+match.charAt(1) || 6, 6);
var fracSecs = (x / 1000 % 1 + 2).toFixed(digits).substr(2).replace(/0+$/, '') || '0';
return fracSecs;
});
var d = new Date(Math.floor(x + 0.05));
fmt = fmt.replace(halfYearMatch, function () {
return quarterToHalfYear[formatter('%q')(d)];
});
if (isWorldCalendar(calendar)) {
try {
fmt = Registry.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar);
} catch (e) {
return 'Invalid';
}
}
return formatter(fmt)(d);
}
/*
* formatTime: create a time string from:
* x: milliseconds
* tr: tickround ('M', 'S', or # digits)
* only supports UTC times (where every day is 24 hours and 0 is at midnight)
*/
var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999];
function formatTime(x, tr) {
var timePart = mod(x + 0.05, ONEDAY);
var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + lpad(mod(Math.floor(timePart / ONEMIN), 60), 2);
if (tr !== 'M') {
if (!isNumeric(tr)) tr = 0; // should only be 'S'
/*
* this is a weird one - and shouldn't come up unless people
* monkey with tick0 in weird ways, but we need to do something!
* IN PARTICULAR we had better not display garbage (see below)
* for numbers we always round to the nearest increment of the
* precision we're showing, and this seems like the right way to
* handle seconds and milliseconds, as they have a decimal point
* and people will interpret that to mean rounding like numbers.
* but for larger increments we floor the value: it's always
* 2013 until the ball drops on the new year. We could argue about
* which field it is where we start rounding (should 12:08:59
* round to 12:09 if we're stopping at minutes?) but for now I'll
* say we round seconds but floor everything else. BUT that means
* we need to never round up to 60 seconds, ie 23:59:60
*/
var sec = Math.min(mod(x / ONESEC, 60), MAXSECONDS[tr]);
var secStr = (100 + sec).toFixed(tr).substr(1);
if (tr > 0) {
secStr = secStr.replace(/0+$/, '').replace(/[\.]$/, '');
}
timeStr += ':' + secStr;
}
return timeStr;
}
/*
* formatDate: turn a date into tick or hover label text.
*
* x: milliseconds, the value to convert
* fmt: optional, an explicit format string (d3 format, even for world calendars)
* tr: tickround ('y', 'm', 'd', 'M', 'S', or # digits)
* used if no explicit fmt is provided
* formatter: locale-aware d3 date formatter for standard gregorian calendars
* should be the result of exports.getD3DateFormat(gd)
* calendar: optional string, the world calendar system to use
*
* returns the date/time as a string, potentially with the leading portion
* on a separate line (after '\n')
* Note that this means if you provide an explicit format which includes '\n'
* the axis may choose to strip things after it when they don't change from
* one tick to the next (as it does with automatic formatting)
*/
exports.formatDate = function (x, fmt, tr, formatter, calendar, extraFormat) {
calendar = isWorldCalendar(calendar) && calendar;
if (!fmt) {
if (tr === 'y') fmt = extraFormat.year;else if (tr === 'm') fmt = extraFormat.month;else if (tr === 'd') {
fmt = extraFormat.dayMonth + '\n' + extraFormat.year;
} else {
return formatTime(x, tr) + '\n' + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar);
}
}
return modDateFormat(fmt, x, formatter, calendar);
};
/*
* incrementMonth: make a new milliseconds value from the given one,
* having changed the month
*
* special case for world calendars: multiples of 12 are treated as years,
* even for calendar systems that don't have (always or ever) 12 months/year
* TODO: perhaps we need a different code for year increments to support this?
*
* ms (number): the initial millisecond value
* dMonth (int): the (signed) number of months to shift
* calendar (string): the calendar system to use
*
* changing month does not (and CANNOT) always preserve day, since
* months have different lengths. The worst example of this is:
* d = new Date(1970,0,31); d.setMonth(1) -> Feb 31 turns into Mar 3
*
* But we want to be able to iterate over the last day of each month,
* regardless of what its number is.
* So shift 3 days forward, THEN set the new month, then unshift:
* 1/31 -> 2/28 (or 29) -> 3/31 -> 4/30 -> ...
*
* Note that odd behavior still exists if you start from the 26th-28th:
* 1/28 -> 2/28 -> 3/31
* but at least you can't shift any dates into the wrong month,
* and ticks on these days incrementing by month would be very unusual
*/
var THREEDAYS = 3 * ONEDAY;
exports.incrementMonth = function (ms, dMonth, calendar) {
calendar = isWorldCalendar(calendar) && calendar;
// pull time out and operate on pure dates, then add time back at the end
// this gives maximum precision - not that we *normally* care if we're
// incrementing by month, but better to be safe!
var timeMs = mod(ms, ONEDAY);
ms = Math.round(ms - timeMs);
if (calendar) {
try {
var dateJD = Math.round(ms / ONEDAY) + EPOCHJD;
var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
var cDate = calInstance.fromJD(dateJD);
if (dMonth % 12) calInstance.add(cDate, dMonth, 'm');else calInstance.add(cDate, dMonth / 12, 'y');
return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs;
} catch (e) {
Loggers.error('invalid ms ' + ms + ' in calendar ' + calendar);
// then keep going in gregorian even though the result will be 'Invalid'
}
}
var y = new Date(ms + THREEDAYS);
return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS;
};
/*
* findExactDates: what fraction of data is exact days, months, or years?
*
* data: array of millisecond values
* calendar (string) the calendar to test against
*/
exports.findExactDates = function (data, calendar) {
var exactYears = 0;
var exactMonths = 0;
var exactDays = 0;
var blankCount = 0;
var d;
var di;
var calInstance = isWorldCalendar(calendar) && Registry.getComponentMethod('calendars', 'getCal')(calendar);
for (var i = 0; i < data.length; i++) {
di = data[i];
// not date data at all
if (!isNumeric(di)) {
blankCount++;
continue;
}
// not an exact date
if (di % ONEDAY) continue;
if (calInstance) {
try {
d = calInstance.fromJD(di / ONEDAY + EPOCHJD);
if (d.day() === 1) {
if (d.month() === 1) exactYears++;else exactMonths++;
} else exactDays++;
} catch (e) {
// invalid date in this calendar - ignore it here.
}
} else {
d = new Date(di);
if (d.getUTCDate() === 1) {
if (d.getUTCMonth() === 0) exactYears++;else exactMonths++;
} else exactDays++;
}
}
exactMonths += exactYears;
exactDays += exactMonths;
var dataCount = data.length - blankCount;
return {
exactYears: exactYears / dataCount,
exactMonths: exactMonths / dataCount,
exactDays: exactDays / dataCount
};
};
/***/ }),
/***/ 52200:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var loggers = __webpack_require__(24248);
var matrix = __webpack_require__(52248);
var mat4X4 = __webpack_require__(36524);
/**
* Allow referencing a graph DOM element either directly
* or by its id string
*
* @param {HTMLDivElement|string} gd: a graph element or its id
*
* @returns {HTMLDivElement} the DOM element of the graph
*/
function getGraphDiv(gd) {
var gdElement;
if (typeof gd === 'string') {
gdElement = document.getElementById(gd);
if (gdElement === null) {
throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
}
return gdElement;
} else if (gd === null || gd === undefined) {
throw new Error('DOM element provided is null or undefined');
}
// otherwise assume that gd is a DOM element
return gd;
}
function isPlotDiv(el) {
var el3 = d3.select(el);
return el3.node() instanceof HTMLElement && el3.size() && el3.classed('js-plotly-plot');
}
function removeElement(el) {
var elParent = el && el.parentNode;
if (elParent) elParent.removeChild(el);
}
/**
* for dynamically adding style rules
* makes one stylesheet that contains all rules added
* by all calls to this function
*/
function addStyleRule(selector, styleString) {
addRelatedStyleRule('global', selector, styleString);
}
/**
* for dynamically adding style rules
* to a stylesheet uniquely identified by a uid
*/
function addRelatedStyleRule(uid, selector, styleString) {
var id = 'plotly.js-style-' + uid;
var style = document.getElementById(id);
if (!style) {
style = document.createElement('style');
style.setAttribute('id', id);
// WebKit hack :(
style.appendChild(document.createTextNode(''));
document.head.appendChild(style);
}
var styleSheet = style.sheet;
if (styleSheet.insertRule) {
styleSheet.insertRule(selector + '{' + styleString + '}', 0);
} else if (styleSheet.addRule) {
styleSheet.addRule(selector, styleString, 0);
} else loggers.warn('addStyleRule failed');
}
/**
* to remove from the page a stylesheet identified by a given uid
*/
function deleteRelatedStyleRule(uid) {
var id = 'plotly.js-style-' + uid;
var style = document.getElementById(id);
if (style) removeElement(style);
}
function getFullTransformMatrix(element) {
var allElements = getElementAndAncestors(element);
// the identity matrix
var out = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
allElements.forEach(function (e) {
var t = getElementTransformMatrix(e);
if (t) {
var m = matrix.convertCssMatrix(t);
out = mat4X4.multiply(out, out, m);
}
});
return out;
}
/**
* extracts and parses the 2d css style transform matrix from some element
*/
function getElementTransformMatrix(element) {
var style = window.getComputedStyle(element, null);
var transform = style.getPropertyValue('-webkit-transform') || style.getPropertyValue('-moz-transform') || style.getPropertyValue('-ms-transform') || style.getPropertyValue('-o-transform') || style.getPropertyValue('transform');
if (transform === 'none') return null;
// the transform is a string in the form of matrix(a, b, ...) or matrix3d(...)
return transform.replace('matrix', '').replace('3d', '').slice(1, -1).split(',').map(function (n) {
return +n;
});
}
/**
* retrieve all DOM elements that are ancestors of the specified one (including itself)
*/
function getElementAndAncestors(element) {
var allElements = [];
while (isTransformableElement(element)) {
allElements.push(element);
element = element.parentNode;
if (typeof ShadowRoot === 'function' && element instanceof ShadowRoot) {
element = element.host;
}
}
return allElements;
}
function isTransformableElement(element) {
return element && (element instanceof Element || element instanceof HTMLElement);
}
function equalDomRects(a, b) {
return a && b && a.top === b.top && a.left === b.left && a.right === b.right && a.bottom === b.bottom;
}
module.exports = {
getGraphDiv: getGraphDiv,
isPlotDiv: isPlotDiv,
removeElement: removeElement,
addStyleRule: addStyleRule,
addRelatedStyleRule: addRelatedStyleRule,
deleteRelatedStyleRule: deleteRelatedStyleRule,
getFullTransformMatrix: getFullTransformMatrix,
getElementTransformMatrix: getElementTransformMatrix,
getElementAndAncestors: getElementAndAncestors,
equalDomRects: equalDomRects
};
/***/ }),
/***/ 95924:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* global jQuery:false */
var EventEmitter = (__webpack_require__(61252).EventEmitter);
var Events = {
init: function (plotObj) {
/*
* If we have already instantiated an emitter for this plot
* return early.
*/
if (plotObj._ev instanceof EventEmitter) return plotObj;
var ev = new EventEmitter();
var internalEv = new EventEmitter();
/*
* Assign to plot._ev while we still live in a land
* where plot is a DOM element with stuff attached to it.
* In the future we can make plot the event emitter itself.
*/
plotObj._ev = ev;
/*
* Create a second event handler that will manage events *internally*.
* This allows parts of plotly to respond to thing like relayout without
* having to use the user-facing event handler. They cannot peacefully
* coexist on the same handler because a user invoking
* plotObj.removeAllListeners() would detach internal events, breaking
* plotly.
*/
plotObj._internalEv = internalEv;
/*
* Assign bound methods from the ev to the plot object. These methods
* will reference the 'this' of plot._ev even though they are methods
* of plot. This will keep the event machinery away from the plot object
* which currently is often a DOM element but presents an API that will
* continue to function when plot becomes an emitter. Not all EventEmitter
* methods have been bound to `plot` as some do not currently add value to
* the Plotly event API.
*/
plotObj.on = ev.on.bind(ev);
plotObj.once = ev.once.bind(ev);
plotObj.removeListener = ev.removeListener.bind(ev);
plotObj.removeAllListeners = ev.removeAllListeners.bind(ev);
/*
* Create functions for managing internal events. These are *only* triggered
* by the mirroring of external events via the emit function.
*/
plotObj._internalOn = internalEv.on.bind(internalEv);
plotObj._internalOnce = internalEv.once.bind(internalEv);
plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv);
plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv);
/*
* We must wrap emit to continue to support JQuery events. The idea
* is to check to see if the user is using JQuery events, if they are
* we emit JQuery events to trigger user handlers as well as the EventEmitter
* events.
*/
plotObj.emit = function (event, data) {
if (typeof jQuery !== 'undefined') {
jQuery(plotObj).trigger(event, data);
}
ev.emit(event, data);
internalEv.emit(event, data);
};
return plotObj;
},
/*
* This function behaves like jQuery's triggerHandler. It calls
* all handlers for a particular event and returns the return value
* of the LAST handler. This function also triggers jQuery's
* triggerHandler for backwards compatibility.
*/
triggerHandler: function (plotObj, event, data) {
var jQueryHandlerValue;
var nodeEventHandlerValue;
/*
* If jQuery exists run all its handlers for this event and
* collect the return value of the LAST handler function
*/
if (typeof jQuery !== 'undefined') {
jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data);
}
/*
* Now run all the node style event handlers
*/
var ev = plotObj._ev;
if (!ev) return jQueryHandlerValue;
var handlers = ev._events[event];
if (!handlers) return jQueryHandlerValue;
// making sure 'this' is the EventEmitter instance
function apply(handler) {
// The 'once' case, we can't just call handler() as we need
// the return value here. So,
// - remove handler
// - call listener and grab return value!
// - stash 'fired' key to not call handler twice
if (handler.listener) {
ev.removeListener(event, handler.listener);
if (!handler.fired) {
handler.fired = true;
return handler.listener.apply(ev, [data]);
}
} else {
return handler.apply(ev, [data]);
}
}
// handlers can be function or an array of functions
handlers = Array.isArray(handlers) ? handlers : [handlers];
var i;
for (i = 0; i < handlers.length - 1; i++) {
apply(handlers[i]);
}
// now call the final handler and collect its value
nodeEventHandlerValue = apply(handlers[i]);
/*
* Return either the jQuery handler value if it exists or the
* nodeEventHandler value. jQuery event value supersedes nodejs
* events for backwards compatibility reasons.
*/
return jQueryHandlerValue !== undefined ? jQueryHandlerValue : nodeEventHandlerValue;
},
purge: function (plotObj) {
delete plotObj._ev;
delete plotObj.on;
delete plotObj.once;
delete plotObj.removeListener;
delete plotObj.removeAllListeners;
delete plotObj.emit;
delete plotObj._ev;
delete plotObj._internalEv;
delete plotObj._internalOn;
delete plotObj._internalOnce;
delete plotObj._removeInternalListener;
delete plotObj._removeAllInternalListeners;
return plotObj;
}
};
module.exports = Events;
/***/ }),
/***/ 92880:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isPlainObject = __webpack_require__(63620);
var isArray = Array.isArray;
function primitivesLoopSplice(source, target) {
var i, value;
for (i = 0; i < source.length; i++) {
value = source[i];
if (value !== null && typeof value === 'object') {
return false;
}
if (value !== void 0) {
target[i] = value;
}
}
return true;
}
exports.extendFlat = function () {
return _extend(arguments, false, false, false);
};
exports.extendDeep = function () {
return _extend(arguments, true, false, false);
};
exports.extendDeepAll = function () {
return _extend(arguments, true, true, false);
};
exports.extendDeepNoArrays = function () {
return _extend(arguments, true, false, true);
};
/*
* Inspired by https://github.com/justmoon/node-extend/blob/master/index.js
* All credit to the jQuery authors for perfecting this amazing utility.
*
* API difference with jQuery version:
* - No optional boolean (true -> deep extend) first argument,
* use `extendFlat` for first-level only extend and
* use `extendDeep` for a deep extend.
*
* Other differences with jQuery version:
* - Uses a modern (and faster) isPlainObject routine.
* - Expected to work with object {} and array [] arguments only.
* - Does not check for circular structure.
* FYI: jQuery only does a check across one level.
* Warning: this might result in infinite loops.
*
*/
function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) {
var target = inputs[0];
var length = inputs.length;
var input, key, src, copy, copyIsArray, clone, allPrimitives;
// TODO does this do the right thing for typed arrays?
if (length === 2 && isArray(target) && isArray(inputs[1]) && target.length === 0) {
allPrimitives = primitivesLoopSplice(inputs[1], target);
if (allPrimitives) {
return target;
} else {
target.splice(0, target.length); // reset target and continue to next block
}
}
for (var i = 1; i < length; i++) {
input = inputs[i];
for (key in input) {
src = target[key];
copy = input[key];
if (noArrayCopies && isArray(copy)) {
// Stop early and just transfer the array if array copies are disallowed:
target[key] = copy;
} else if (isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
// recurse if we're merging plain objects or arrays
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// never move original objects, clone them
target[key] = _extend([clone, copy], isDeep, keepAllKeys, noArrayCopies);
} else if (typeof copy !== 'undefined' || keepAllKeys) {
// don't bring in undefined values, except for extendDeepAll
target[key] = copy;
}
}
}
return target;
}
/***/ }),
/***/ 68944:
/***/ (function(module) {
"use strict";
/**
* Return news array containing only the unique items
* found in input array.
*
* IMPORTANT: Note that items are considered unique
* if `String({})` is unique. For example;
*
* Lib.filterUnique([ { a: 1 }, { b: 2 } ])
*
* returns [{ a: 1 }]
*
* and
*
* Lib.filterUnique([ '1', 1 ])
*
* returns ['1']
*
*
* @param {array} array base array
* @return {array} new filtered array
*/
module.exports = function filterUnique(array) {
var seen = {};
var out = [];
var j = 0;
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out;
};
/***/ }),
/***/ 43880:
/***/ (function(module) {
"use strict";
/** Filter out object items with visible !== true
* insider array container.
*
* @param {array of objects} container
* @return {array of objects} of length <= container
*
*/
module.exports = function filterVisible(container) {
var filterFn = isCalcData(container) ? calcDataFilter : baseFilter;
var out = [];
for (var i = 0; i < container.length; i++) {
var item = container[i];
if (filterFn(item)) out.push(item);
}
return out;
};
function baseFilter(item) {
return item.visible === true;
}
function calcDataFilter(item) {
var trace = item[0].trace;
return trace.visible === true && trace._length !== 0;
}
function isCalcData(cont) {
return Array.isArray(cont) && Array.isArray(cont[0]) && cont[0][0] && cont[0][0].trace;
}
/***/ }),
/***/ 27144:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var countryRegex = __webpack_require__(36116);
var turfArea = __webpack_require__(40440);
var turfCentroid = __webpack_require__(77844);
var turfBbox = __webpack_require__(42428);
var identity = __webpack_require__(35536);
var loggers = __webpack_require__(24248);
var isPlainObject = __webpack_require__(63620);
var nestedProperty = __webpack_require__(22296);
var polygon = __webpack_require__(92065);
// make list of all country iso3 ids from at runtime
var countryIds = Object.keys(countryRegex);
var locationmodeToIdFinder = {
'ISO-3': identity,
'USA-states': identity,
'country names': countryNameToISO3
};
function countryNameToISO3(countryName) {
for (var i = 0; i < countryIds.length; i++) {
var iso3 = countryIds[i];
var regex = new RegExp(countryRegex[iso3]);
if (regex.test(countryName.trim().toLowerCase())) return iso3;
}
loggers.log('Unrecognized country name: ' + countryName + '.');
return false;
}
function locationToFeature(locationmode, location, features) {
if (!location || typeof location !== 'string') return false;
var locationId = locationmodeToIdFinder[locationmode](location);
var filteredFeatures;
var f, i;
if (locationId) {
if (locationmode === 'USA-states') {
// Filter out features out in USA
//
// This is important as the Natural Earth files
// include state/provinces from USA, Canada, Australia and Brazil
// which have some overlay in their two-letter ids. For example,
// 'WA' is used for both Washington state and Western Australia.
filteredFeatures = [];
for (i = 0; i < features.length; i++) {
f = features[i];
if (f.properties && f.properties.gu && f.properties.gu === 'USA') {
filteredFeatures.push(f);
}
}
} else {
filteredFeatures = features;
}
for (i = 0; i < filteredFeatures.length; i++) {
f = filteredFeatures[i];
if (f.id === locationId) return f;
}
loggers.log(['Location with id', locationId, 'does not have a matching topojson feature at this resolution.'].join(' '));
}
return false;
}
function feature2polygons(feature) {
var geometry = feature.geometry;
var coords = geometry.coordinates;
var loc = feature.id;
var polygons = [];
var appendPolygon, j, k, m;
function doesCrossAntiMerdian(pts) {
for (var l = 0; l < pts.length - 1; l++) {
if (pts[l][0] > 0 && pts[l + 1][0] < 0) return l;
}
return null;
}
if (loc === 'RUS' || loc === 'FJI') {
// Russia and Fiji have landmasses that cross the antimeridian,
// we need to add +360 to their longitude coordinates, so that
// polygon 'contains' doesn't get confused when crossing the antimeridian.
//
// Note that other countries have polygons on either side of the antimeridian
// (e.g. some Aleutian island for the USA), but those don't confuse
// the 'contains' method; these are skipped here.
appendPolygon = function (_pts) {
var pts;
if (doesCrossAntiMerdian(_pts) === null) {
pts = _pts;
} else {
pts = new Array(_pts.length);
for (m = 0; m < _pts.length; m++) {
// do not mutate calcdata[i][j].geojson !!
pts[m] = [_pts[m][0] < 0 ? _pts[m][0] + 360 : _pts[m][0], _pts[m][1]];
}
}
polygons.push(polygon.tester(pts));
};
} else if (loc === 'ATA') {
// Antarctica has a landmass that wraps around every longitudes which
// confuses the 'contains' methods.
appendPolygon = function (pts) {
var crossAntiMeridianIndex = doesCrossAntiMerdian(pts);
// polygon that do not cross anti-meridian need no special handling
if (crossAntiMeridianIndex === null) {
return polygons.push(polygon.tester(pts));
}
// stitch polygon by adding pt over South Pole,
// so that it covers the projected region covers all latitudes
//
// Note that the algorithm below only works for polygons that
// start and end on longitude -180 (like the ones built by
// https://github.com/etpinard/sane-topojson).
var stitch = new Array(pts.length + 1);
var si = 0;
for (m = 0; m < pts.length; m++) {
if (m > crossAntiMeridianIndex) {
stitch[si++] = [pts[m][0] + 360, pts[m][1]];
} else if (m === crossAntiMeridianIndex) {
stitch[si++] = pts[m];
stitch[si++] = [pts[m][0], -90];
} else {
stitch[si++] = pts[m];
}
}
// polygon.tester by default appends pt[0] to the points list,
// we must remove it here, to avoid a jump in longitude from 180 to -180,
// that would confuse the 'contains' method
var tester = polygon.tester(stitch);
tester.pts.pop();
polygons.push(tester);
};
} else {
// otherwise using same array ref is fine
appendPolygon = function (pts) {
polygons.push(polygon.tester(pts));
};
}
switch (geometry.type) {
case 'MultiPolygon':
for (j = 0; j < coords.length; j++) {
for (k = 0; k < coords[j].length; k++) {
appendPolygon(coords[j][k]);
}
}
break;
case 'Polygon':
for (j = 0; j < coords.length; j++) {
appendPolygon(coords[j]);
}
break;
}
return polygons;
}
function getTraceGeojson(trace) {
var g = trace.geojson;
var PlotlyGeoAssets = window.PlotlyGeoAssets || {};
var geojsonIn = typeof g === 'string' ? PlotlyGeoAssets[g] : g;
// This should not happen, but just in case something goes
// really wrong when fetching the GeoJSON
if (!isPlainObject(geojsonIn)) {
loggers.error('Oops ... something went wrong when fetching ' + g);
return false;
}
return geojsonIn;
}
function extractTraceFeature(calcTrace) {
var trace = calcTrace[0].trace;
var geojsonIn = getTraceGeojson(trace);
if (!geojsonIn) return false;
var lookup = {};
var featuresOut = [];
var i;
for (i = 0; i < trace._length; i++) {
var cdi = calcTrace[i];
if (cdi.loc || cdi.loc === 0) {
lookup[cdi.loc] = cdi;
}
}
function appendFeature(fIn) {
var id = nestedProperty(fIn, trace.featureidkey || 'id').get();
var cdi = lookup[id];
if (cdi) {
var geometry = fIn.geometry;
if (geometry.type === 'Polygon' || geometry.type === 'MultiPolygon') {
var fOut = {
type: 'Feature',
id: id,
geometry: geometry,
properties: {}
};
// Compute centroid, add it to the properties
fOut.properties.ct = findCentroid(fOut);
// Mutate in in/out features into calcdata
cdi.fIn = fIn;
cdi.fOut = fOut;
featuresOut.push(fOut);
} else {
loggers.log(['Location', cdi.loc, 'does not have a valid GeoJSON geometry.', 'Traces with locationmode *geojson-id* only support', '*Polygon* and *MultiPolygon* geometries.'].join(' '));
}
}
// remove key from lookup, so that we can track (if any)
// the locations that did not have a corresponding GeoJSON feature
delete lookup[id];
}
switch (geojsonIn.type) {
case 'FeatureCollection':
var featuresIn = geojsonIn.features;
for (i = 0; i < featuresIn.length; i++) {
appendFeature(featuresIn[i]);
}
break;
case 'Feature':
appendFeature(geojsonIn);
break;
default:
loggers.warn(['Invalid GeoJSON type', (geojsonIn.type || 'none') + '.', 'Traces with locationmode *geojson-id* only support', '*FeatureCollection* and *Feature* types.'].join(' '));
return false;
}
for (var loc in lookup) {
loggers.log(['Location *' + loc + '*', 'does not have a matching feature with id-key', '*' + trace.featureidkey + '*.'].join(' '));
}
return featuresOut;
}
// TODO this find the centroid of the polygon of maxArea
// (just like we currently do for geo choropleth polygons),
// maybe instead it would make more sense to compute the centroid
// of each polygon and consider those on hover/select
function findCentroid(feature) {
var geometry = feature.geometry;
var poly;
if (geometry.type === 'MultiPolygon') {
var coords = geometry.coordinates;
var maxArea = 0;
for (var i = 0; i < coords.length; i++) {
var polyi = {
type: 'Polygon',
coordinates: coords[i]
};
var area = turfArea.default(polyi);
if (area > maxArea) {
maxArea = area;
poly = polyi;
}
}
} else {
poly = geometry;
}
return turfCentroid.default(poly).geometry.coordinates;
}
function fetchTraceGeoData(calcData) {
var PlotlyGeoAssets = window.PlotlyGeoAssets || {};
var promises = [];
function fetch(url) {
return new Promise(function (resolve, reject) {
d3.json(url, function (err, d) {
if (err) {
delete PlotlyGeoAssets[url];
var msg = err.status === 404 ? 'GeoJSON at URL "' + url + '" does not exist.' : 'Unexpected error while fetching from ' + url;
return reject(new Error(msg));
}
PlotlyGeoAssets[url] = d;
return resolve(d);
});
});
}
function wait(url) {
return new Promise(function (resolve, reject) {
var cnt = 0;
var interval = setInterval(function () {
if (PlotlyGeoAssets[url] && PlotlyGeoAssets[url] !== 'pending') {
clearInterval(interval);
return resolve(PlotlyGeoAssets[url]);
}
if (cnt > 100) {
clearInterval(interval);
return reject('Unexpected error while fetching from ' + url);
}
cnt++;
}, 50);
});
}
for (var i = 0; i < calcData.length; i++) {
var trace = calcData[i][0].trace;
var url = trace.geojson;
if (typeof url === 'string') {
if (!PlotlyGeoAssets[url]) {
PlotlyGeoAssets[url] = 'pending';
promises.push(fetch(url));
} else if (PlotlyGeoAssets[url] === 'pending') {
promises.push(wait(url));
}
}
}
return promises;
}
// TODO `turf/bbox` gives wrong result when the input feature/geometry
// crosses the anti-meridian. We should try to implement our own bbox logic.
function computeBbox(d) {
return turfBbox.default(d);
}
module.exports = {
locationToFeature: locationToFeature,
feature2polygons: feature2polygons,
getTraceGeojson: getTraceGeojson,
extractTraceFeature: extractTraceFeature,
fetchTraceGeoData: fetchTraceGeoData,
computeBbox: computeBbox
};
/***/ }),
/***/ 44808:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var BADNUM = (__webpack_require__(39032).BADNUM);
/**
* Convert calcTrace to GeoJSON 'MultiLineString' coordinate arrays
*
* @param {object} calcTrace
* gd.calcdata item.
* Note that calcTrace[i].lonlat is assumed to be defined
*
* @return {array}
* return line coords array (or array of arrays)
*
*/
exports.calcTraceToLineCoords = function (calcTrace) {
var trace = calcTrace[0].trace;
var connectgaps = trace.connectgaps;
var coords = [];
var lineString = [];
for (var i = 0; i < calcTrace.length; i++) {
var calcPt = calcTrace[i];
var lonlat = calcPt.lonlat;
if (lonlat[0] !== BADNUM) {
lineString.push(lonlat);
} else if (!connectgaps && lineString.length > 0) {
coords.push(lineString);
lineString = [];
}
}
if (lineString.length > 0) {
coords.push(lineString);
}
return coords;
};
/**
* Make line ('LineString' or 'MultiLineString') GeoJSON
*
* @param {array} coords
* results form calcTraceToLineCoords
* @return {object} out
* GeoJSON object
*
*/
exports.makeLine = function (coords) {
if (coords.length === 1) {
return {
type: 'LineString',
coordinates: coords[0]
};
} else {
return {
type: 'MultiLineString',
coordinates: coords
};
}
};
/**
* Make polygon ('Polygon' or 'MultiPolygon') GeoJSON
*
* @param {array} coords
* results form calcTraceToLineCoords
* @return {object} out
* GeoJSON object
*/
exports.makePolygon = function (coords) {
if (coords.length === 1) {
return {
type: 'Polygon',
coordinates: coords
};
} else {
var _coords = new Array(coords.length);
for (var i = 0; i < coords.length; i++) {
_coords[i] = [coords[i]];
}
return {
type: 'MultiPolygon',
coordinates: _coords
};
}
};
/**
* Make blank GeoJSON
*
* @return {object}
* Blank GeoJSON object
*
*/
exports.makeBlank = function () {
return {
type: 'Point',
coordinates: []
};
};
/***/ }),
/***/ 92348:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var mod = (__webpack_require__(20435).mod);
/*
* look for intersection of two line segments
* (1->2 and 3->4) - returns array [x,y] if they do, null if not
*/
exports.segmentsIntersect = segmentsIntersect;
function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
var a = x2 - x1;
var b = x3 - x1;
var c = x4 - x3;
var d = y2 - y1;
var e = y3 - y1;
var f = y4 - y3;
var det = a * f - c * d;
// parallel lines? intersection is undefined
// ignore the case where they are colinear
if (det === 0) return null;
var t = (b * f - c * e) / det;
var u = (b * d - a * e) / det;
// segments do not intersect?
if (u < 0 || u > 1 || t < 0 || t > 1) return null;
return {
x: x1 + a * t,
y: y1 + d * t
};
}
/*
* find the minimum distance between two line segments (1->2 and 3->4)
*/
exports.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) {
if (segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return 0;
// the two segments and their lengths squared
var x12 = x2 - x1;
var y12 = y2 - y1;
var x34 = x4 - x3;
var y34 = y4 - y3;
var ll12 = x12 * x12 + y12 * y12;
var ll34 = x34 * x34 + y34 * y34;
// calculate distance squared, then take the sqrt at the very end
var dist2 = Math.min(perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1), perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1), perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3), perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3));
return Math.sqrt(dist2);
};
/*
* distance squared from segment ab to point c
* [xab, yab] is the vector b-a
* [xac, yac] is the vector c-a
* llab is the length squared of (b-a), just to simplify calculation
*/
function perpDistance2(xab, yab, llab, xac, yac) {
var fcAB = xac * xab + yac * yab;
if (fcAB < 0) {
// point c is closer to point a
return xac * xac + yac * yac;
} else if (fcAB > llab) {
// point c is closer to point b
var xbc = xac - xab;
var ybc = yac - yab;
return xbc * xbc + ybc * ybc;
} else {
// perpendicular distance is the shortest
var crossProduct = xac * yab - yac * xab;
return crossProduct * crossProduct / llab;
}
}
// a very short-term cache for getTextLocation, just because
// we're often looping over the same locations multiple times
// invalidated as soon as we look at a different path
var locationCache, workingPath, workingTextWidth;
// turn a path and position along it into x, y, and angle for the given text
exports.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) {
if (path !== workingPath || textWidth !== workingTextWidth) {
locationCache = {};
workingPath = path;
workingTextWidth = textWidth;
}
if (locationCache[positionOnPath]) {
return locationCache[positionOnPath];
}
// for the angle, use points on the path separated by the text width
// even though due to curvature, the text will cover a bit more than that
var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen));
var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen));
// note: atan handles 1/0 nicely
var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
// center the text at 2/3 of the center position plus 1/3 the p0/p1 midpoint
// that's the average position of this segment, assuming it's roughly quadratic
var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen));
var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
var y = (pCenter.y * 4 + p0.y + p1.y) / 6;
var out = {
x: x,
y: y,
theta: theta
};
locationCache[positionOnPath] = out;
return out;
};
exports.clearLocationCache = function () {
workingPath = null;
};
/*
* Find the segment of `path` that's within the visible area
* given by `bounds` {left, right, top, bottom}, to within a
* precision of `buffer` px
*
* returns: undefined if nothing is visible, else object:
* {
* min: position where the path first enters bounds, or 0 if it
* starts within bounds
* max: position where the path last exits bounds, or the path length
* if it finishes within bounds
* len: max - min, ie the length of visible path
* total: the total path length - just included so the caller doesn't
* need to call path.getTotalLength() again
* isClosed: true iff the start and end points of the path are both visible
* and are at the same point
* }
*
* Works by starting from either end and repeatedly finding the distance from
* that point to the plot area, and if it's outside the plot, moving along the
* path by that distance (because the plot must be at least that far away on
* the path). Note that if a path enters, exits, and re-enters the plot, we
* will not capture this behavior.
*/
exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
var left = bounds.left;
var right = bounds.right;
var top = bounds.top;
var bottom = bounds.bottom;
var pMin = 0;
var pTotal = path.getTotalLength();
var pMax = pTotal;
var pt0, ptTotal;
function getDistToPlot(len) {
var pt = path.getPointAtLength(len);
// hold on to the start and end points for `closed`
if (len === 0) pt0 = pt;else if (len === pTotal) ptTotal = pt;
var dx = pt.x < left ? left - pt.x : pt.x > right ? pt.x - right : 0;
var dy = pt.y < top ? top - pt.y : pt.y > bottom ? pt.y - bottom : 0;
return Math.sqrt(dx * dx + dy * dy);
}
var distToPlot = getDistToPlot(pMin);
while (distToPlot) {
pMin += distToPlot + buffer;
if (pMin > pMax) return;
distToPlot = getDistToPlot(pMin);
}
distToPlot = getDistToPlot(pMax);
while (distToPlot) {
pMax -= distToPlot + buffer;
if (pMin > pMax) return;
distToPlot = getDistToPlot(pMax);
}
return {
min: pMin,
max: pMax,
len: pMax - pMin,
total: pTotal,
isClosed: pMin === 0 && pMax === pTotal && Math.abs(pt0.x - ptTotal.x) < 0.1 && Math.abs(pt0.y - ptTotal.y) < 0.1
};
};
/**
* Find point on SVG path corresponding to a given constraint coordinate
*
* @param {SVGPathElement} path
* @param {Number} val : constraint coordinate value
* @param {String} coord : 'x' or 'y' the constraint coordinate
* @param {Object} opts :
* - {Number} pathLength : supply total path length before hand
* - {Number} tolerance
* - {Number} iterationLimit
* @return {SVGPoint}
*/
exports.findPointOnPath = function findPointOnPath(path, val, coord, opts) {
opts = opts || {};
var pathLength = opts.pathLength || path.getTotalLength();
var tolerance = opts.tolerance || 1e-3;
var iterationLimit = opts.iterationLimit || 30;
// if path starts at a val greater than the path tail (like on vertical violins),
// we must flip the sign of the computed diff.
var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1;
var i = 0;
var b0 = 0;
var b1 = pathLength;
var mid;
var pt;
var diff;
while (i < iterationLimit) {
mid = (b0 + b1) / 2;
pt = path.getPointAtLength(mid);
diff = pt[coord] - val;
if (Math.abs(diff) < tolerance) {
return pt;
} else {
if (mul * diff > 0) {
b1 = mid;
} else {
b0 = mid;
}
i++;
}
}
return pt;
};
/***/ }),
/***/ 33040:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var tinycolor = __webpack_require__(49760);
var rgba = __webpack_require__(72160);
var Colorscale = __webpack_require__(8932);
var colorDflt = (__webpack_require__(22548).defaultLine);
var isArrayOrTypedArray = (__webpack_require__(38116).isArrayOrTypedArray);
var colorDfltRgba = rgba(colorDflt);
var opacityDflt = 1;
function calculateColor(colorIn, opacityIn) {
var colorOut = colorIn;
colorOut[3] *= opacityIn;
return colorOut;
}
function validateColor(colorIn) {
if (isNumeric(colorIn)) return colorDfltRgba;
var colorOut = rgba(colorIn);
return colorOut.length ? colorOut : colorDfltRgba;
}
function validateOpacity(opacityIn) {
return isNumeric(opacityIn) ? opacityIn : opacityDflt;
}
function formatColor(containerIn, opacityIn, len) {
var colorIn = containerIn.color;
if (colorIn && colorIn._inputArray) colorIn = colorIn._inputArray;
var isArrayColorIn = isArrayOrTypedArray(colorIn);
var isArrayOpacityIn = isArrayOrTypedArray(opacityIn);
var cOpts = Colorscale.extractOpts(containerIn);
var colorOut = [];
var sclFunc, getColor, getOpacity, colori, opacityi;
if (cOpts.colorscale !== undefined) {
sclFunc = Colorscale.makeColorScaleFuncFromTrace(containerIn);
} else {
sclFunc = validateColor;
}
if (isArrayColorIn) {
getColor = function (c, i) {
// FIXME: there is double work, considering that sclFunc does the opposite
return c[i] === undefined ? colorDfltRgba : rgba(sclFunc(c[i]));
};
} else getColor = validateColor;
if (isArrayOpacityIn) {
getOpacity = function (o, i) {
return o[i] === undefined ? opacityDflt : validateOpacity(o[i]);
};
} else getOpacity = validateOpacity;
if (isArrayColorIn || isArrayOpacityIn) {
for (var i = 0; i < len; i++) {
colori = getColor(colorIn, i);
opacityi = getOpacity(opacityIn, i);
colorOut[i] = calculateColor(colori, opacityi);
}
} else colorOut = calculateColor(rgba(colorIn), opacityIn);
return colorOut;
}
function parseColorScale(cont) {
var cOpts = Colorscale.extractOpts(cont);
var colorscale = cOpts.colorscale;
if (cOpts.reversescale) colorscale = Colorscale.flipScale(cOpts.colorscale);
return colorscale.map(function (elem) {
var index = elem[0];
var color = tinycolor(elem[1]);
var rgb = color.toRgb();
return {
index: index,
rgb: [rgb.r, rgb.g, rgb.b, rgb.a]
};
});
}
module.exports = {
formatColor: formatColor,
parseColorScale: parseColorScale
};
/***/ }),
/***/ 71688:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var identity = __webpack_require__(35536);
function wrap(d) {
return [d];
}
module.exports = {
// The D3 data binding concept and the General Update Pattern promotes the idea of
// traversing into the scenegraph by using the `.data(fun, keyFun)` call.
// The `fun` is most often a `repeat`, ie. the elements beneath a `` element need
// access to the same data, or a `descend`, which fans a scenegraph node into a bunch of
// of elements, e.g. points, lines, rows, requiring an array as input.
// The role of the `keyFun` is to identify what elements are being entered/exited/updated,
// otherwise D3 reverts to using a plain index which would screw up `transition`s.
keyFun: function (d) {
return d.key;
},
repeat: wrap,
descend: identity,
// Plotly.js uses a convention of storing the actual contents of the `calcData` as the
// element zero of a container array. These helpers are just used for clarity as a
// newcomer to the codebase may not know what the `[0]` is, and whether there can be further
// elements (not atm).
wrap: wrap,
unwrap: function (d) {
return d[0];
}
};
/***/ }),
/***/ 35536:
/***/ (function(module) {
"use strict";
// Simple helper functions
// none of these need any external deps
module.exports = function identity(d) {
return d;
};
/***/ }),
/***/ 1396:
/***/ (function(module) {
"use strict";
module.exports = function incrementNumeric(x, delta) {
if (!delta) return x;
// Note 1:
// 0.3 != 0.1 + 0.2 == 0.30000000000000004
// but 0.3 == (10 * 0.1 + 10 * 0.2) / 10
// Attempt to use integer steps to increment
var scale = 1 / Math.abs(delta);
var newX = scale > 1 ? (scale * x + scale * delta) / scale : x + delta;
// Note 2:
// now we may also consider rounding to cover few more edge cases
// e.g. 0.3 * 3 = 0.8999999999999999
var lenX1 = String(newX).length;
if (lenX1 > 16) {
var lenDt = String(delta).length;
var lenX0 = String(x).length;
if (lenX1 >= lenX0 + lenDt) {
// likely a rounding error!
var s = parseFloat(newX).toPrecision(12);
if (s.indexOf('e+') === -1) newX = +s;
}
}
return newX;
};
/***/ }),
/***/ 3400:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var utcFormat = (__webpack_require__(94336)/* .utcFormat */ .E9);
var d3Format = (__webpack_require__(57624)/* .format */ .E9);
var isNumeric = __webpack_require__(38248);
var numConstants = __webpack_require__(39032);
var MAX_SAFE = numConstants.FP_SAFE;
var MIN_SAFE = -MAX_SAFE;
var BADNUM = numConstants.BADNUM;
var lib = module.exports = {};
lib.adjustFormat = function adjustFormat(formatStr) {
if (!formatStr || /^\d[.]\df/.test(formatStr) || /[.]\d%/.test(formatStr)) return formatStr;
if (formatStr === '0.f') return '~f';
if (/^\d%/.test(formatStr)) return '~%';
if (/^\ds/.test(formatStr)) return '~s';
// try adding tilde to the start of format in order to trim
if (!/^[~,.0$]/.test(formatStr) && /[&fps]/.test(formatStr)) return '~' + formatStr;
return formatStr;
};
var seenBadFormats = {};
lib.warnBadFormat = function (f) {
var key = String(f);
if (!seenBadFormats[key]) {
seenBadFormats[key] = 1;
lib.warn('encountered bad format: "' + key + '"');
}
};
lib.noFormat = function (value) {
return String(value);
};
lib.numberFormat = function (formatStr) {
var fn;
try {
fn = d3Format(lib.adjustFormat(formatStr));
} catch (e) {
lib.warnBadFormat(formatStr);
return lib.noFormat;
}
return fn;
};
lib.nestedProperty = __webpack_require__(22296);
lib.keyedContainer = __webpack_require__(37804);
lib.relativeAttr = __webpack_require__(23193);
lib.isPlainObject = __webpack_require__(63620);
lib.toLogRange = __webpack_require__(36896);
lib.relinkPrivateKeys = __webpack_require__(51528);
var arrayModule = __webpack_require__(38116);
lib.isArrayBuffer = arrayModule.isArrayBuffer;
lib.isTypedArray = arrayModule.isTypedArray;
lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray;
lib.isArray1D = arrayModule.isArray1D;
lib.ensureArray = arrayModule.ensureArray;
lib.concat = arrayModule.concat;
lib.maxRowLength = arrayModule.maxRowLength;
lib.minRowLength = arrayModule.minRowLength;
var modModule = __webpack_require__(20435);
lib.mod = modModule.mod;
lib.modHalf = modModule.modHalf;
var coerceModule = __webpack_require__(63064);
lib.valObjectMeta = coerceModule.valObjectMeta;
lib.coerce = coerceModule.coerce;
lib.coerce2 = coerceModule.coerce2;
lib.coerceFont = coerceModule.coerceFont;
lib.coercePattern = coerceModule.coercePattern;
lib.coerceHoverinfo = coerceModule.coerceHoverinfo;
lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity;
lib.validate = coerceModule.validate;
var datesModule = __webpack_require__(67555);
lib.dateTime2ms = datesModule.dateTime2ms;
lib.isDateTime = datesModule.isDateTime;
lib.ms2DateTime = datesModule.ms2DateTime;
lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal;
lib.cleanDate = datesModule.cleanDate;
lib.isJSDate = datesModule.isJSDate;
lib.formatDate = datesModule.formatDate;
lib.incrementMonth = datesModule.incrementMonth;
lib.dateTick0 = datesModule.dateTick0;
lib.dfltRange = datesModule.dfltRange;
lib.findExactDates = datesModule.findExactDates;
lib.MIN_MS = datesModule.MIN_MS;
lib.MAX_MS = datesModule.MAX_MS;
var searchModule = __webpack_require__(14952);
lib.findBin = searchModule.findBin;
lib.sorterAsc = searchModule.sorterAsc;
lib.sorterDes = searchModule.sorterDes;
lib.distinctVals = searchModule.distinctVals;
lib.roundUp = searchModule.roundUp;
lib.sort = searchModule.sort;
lib.findIndexOfMin = searchModule.findIndexOfMin;
lib.sortObjectKeys = __webpack_require__(95376);
var statsModule = __webpack_require__(63084);
lib.aggNums = statsModule.aggNums;
lib.len = statsModule.len;
lib.mean = statsModule.mean;
lib.geometricMean = statsModule.geometricMean;
lib.median = statsModule.median;
lib.midRange = statsModule.midRange;
lib.variance = statsModule.variance;
lib.stdev = statsModule.stdev;
lib.interp = statsModule.interp;
var matrixModule = __webpack_require__(52248);
lib.init2dArray = matrixModule.init2dArray;
lib.transposeRagged = matrixModule.transposeRagged;
lib.dot = matrixModule.dot;
lib.translationMatrix = matrixModule.translationMatrix;
lib.rotationMatrix = matrixModule.rotationMatrix;
lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
lib.apply3DTransform = matrixModule.apply3DTransform;
lib.apply2DTransform = matrixModule.apply2DTransform;
lib.apply2DTransform2 = matrixModule.apply2DTransform2;
lib.convertCssMatrix = matrixModule.convertCssMatrix;
lib.inverseTransformMatrix = matrixModule.inverseTransformMatrix;
var anglesModule = __webpack_require__(11864);
lib.deg2rad = anglesModule.deg2rad;
lib.rad2deg = anglesModule.rad2deg;
lib.angleDelta = anglesModule.angleDelta;
lib.angleDist = anglesModule.angleDist;
lib.isFullCircle = anglesModule.isFullCircle;
lib.isAngleInsideSector = anglesModule.isAngleInsideSector;
lib.isPtInsideSector = anglesModule.isPtInsideSector;
lib.pathArc = anglesModule.pathArc;
lib.pathSector = anglesModule.pathSector;
lib.pathAnnulus = anglesModule.pathAnnulus;
var anchorUtils = __webpack_require__(98308);
lib.isLeftAnchor = anchorUtils.isLeftAnchor;
lib.isCenterAnchor = anchorUtils.isCenterAnchor;
lib.isRightAnchor = anchorUtils.isRightAnchor;
lib.isTopAnchor = anchorUtils.isTopAnchor;
lib.isMiddleAnchor = anchorUtils.isMiddleAnchor;
lib.isBottomAnchor = anchorUtils.isBottomAnchor;
var geom2dModule = __webpack_require__(92348);
lib.segmentsIntersect = geom2dModule.segmentsIntersect;
lib.segmentDistance = geom2dModule.segmentDistance;
lib.getTextLocation = geom2dModule.getTextLocation;
lib.clearLocationCache = geom2dModule.clearLocationCache;
lib.getVisibleSegment = geom2dModule.getVisibleSegment;
lib.findPointOnPath = geom2dModule.findPointOnPath;
var extendModule = __webpack_require__(92880);
lib.extendFlat = extendModule.extendFlat;
lib.extendDeep = extendModule.extendDeep;
lib.extendDeepAll = extendModule.extendDeepAll;
lib.extendDeepNoArrays = extendModule.extendDeepNoArrays;
var loggersModule = __webpack_require__(24248);
lib.log = loggersModule.log;
lib.warn = loggersModule.warn;
lib.error = loggersModule.error;
var regexModule = __webpack_require__(53756);
lib.counterRegex = regexModule.counter;
var throttleModule = __webpack_require__(91200);
lib.throttle = throttleModule.throttle;
lib.throttleDone = throttleModule.done;
lib.clearThrottle = throttleModule.clear;
var domModule = __webpack_require__(52200);
lib.getGraphDiv = domModule.getGraphDiv;
lib.isPlotDiv = domModule.isPlotDiv;
lib.removeElement = domModule.removeElement;
lib.addStyleRule = domModule.addStyleRule;
lib.addRelatedStyleRule = domModule.addRelatedStyleRule;
lib.deleteRelatedStyleRule = domModule.deleteRelatedStyleRule;
lib.getFullTransformMatrix = domModule.getFullTransformMatrix;
lib.getElementTransformMatrix = domModule.getElementTransformMatrix;
lib.getElementAndAncestors = domModule.getElementAndAncestors;
lib.equalDomRects = domModule.equalDomRects;
lib.clearResponsive = __webpack_require__(75352);
lib.preserveDrawingBuffer = __webpack_require__(34296);
lib.makeTraceGroups = __webpack_require__(30988);
lib._ = __webpack_require__(98356);
lib.notifier = __webpack_require__(41792);
lib.filterUnique = __webpack_require__(68944);
lib.filterVisible = __webpack_require__(43880);
lib.pushUnique = __webpack_require__(52416);
lib.increment = __webpack_require__(1396);
lib.cleanNumber = __webpack_require__(54037);
lib.ensureNumber = function ensureNumber(v) {
if (!isNumeric(v)) return BADNUM;
v = Number(v);
return v > MAX_SAFE || v < MIN_SAFE ? BADNUM : v;
};
/**
* Is v a valid array index? Accepts numeric strings as well as numbers.
*
* @param {any} v: the value to test
* @param {Optional[integer]} len: the array length we are indexing
*
* @return {bool}: v is a valid array index
*/
lib.isIndex = function (v, len) {
if (len !== undefined && v >= len) return false;
return isNumeric(v) && v >= 0 && v % 1 === 0;
};
lib.noop = __webpack_require__(16628);
lib.identity = __webpack_require__(35536);
/**
* create an array of length 'cnt' filled with 'v' at all indices
*
* @param {any} v
* @param {number} cnt
* @return {array}
*/
lib.repeat = function (v, cnt) {
var out = new Array(cnt);
for (var i = 0; i < cnt; i++) {
out[i] = v;
}
return out;
};
/**
* swap x and y of the same attribute in container cont
* specify attr with a ? in place of x/y
* you can also swap other things than x/y by providing part1 and part2
*/
lib.swapAttrs = function (cont, attrList, part1, part2) {
if (!part1) part1 = 'x';
if (!part2) part2 = 'y';
for (var i = 0; i < attrList.length; i++) {
var attr = attrList[i];
var xp = lib.nestedProperty(cont, attr.replace('?', part1));
var yp = lib.nestedProperty(cont, attr.replace('?', part2));
var temp = xp.get();
xp.set(yp.get());
yp.set(temp);
}
};
/**
* SVG painter's algo worked around with reinsertion
*/
lib.raiseToTop = function raiseToTop(elem) {
elem.parentNode.appendChild(elem);
};
/**
* cancel a possibly pending transition; returned selection may be used by caller
*/
lib.cancelTransition = function (selection) {
return selection.transition().duration(0);
};
// constrain - restrict a number v to be between v0 and v1
lib.constrain = function (v, v0, v1) {
if (v0 > v1) return Math.max(v1, Math.min(v0, v));
return Math.max(v0, Math.min(v1, v));
};
/**
* do two bounding boxes from getBoundingClientRect,
* ie {left,right,top,bottom,width,height}, overlap?
* takes optional padding pixels
*/
lib.bBoxIntersect = function (a, b, pad) {
pad = pad || 0;
return a.left <= b.right + pad && b.left <= a.right + pad && a.top <= b.bottom + pad && b.top <= a.bottom + pad;
};
/*
* simpleMap: alternative to Array.map that only
* passes on the element and up to 2 extra args you
* provide (but not the array index or the whole array)
*
* array: the array to map it to
* func: the function to apply
* x1, x2: optional extra args
*/
lib.simpleMap = function (array, func, x1, x2, opts) {
var len = array.length;
var out = new Array(len);
for (var i = 0; i < len; i++) out[i] = func(array[i], x1, x2, opts);
return out;
};
/**
* Random string generator
*
* @param {object} existing
* pass in strings to avoid as keys with truthy values
* @param {int} bits
* bits of information in the output string, default 24
* @param {int} base
* base of string representation, default 16. Should be a power of 2.
*/
lib.randstr = function randstr(existing, bits, base, _recursion) {
if (!base) base = 16;
if (bits === undefined) bits = 24;
if (bits <= 0) return '0';
var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
var res = '';
var i, b, x;
for (i = 2; digits === Infinity; i *= 2) {
digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
}
var rem = digits - Math.floor(digits);
for (i = 0; i < Math.floor(digits); i++) {
x = Math.floor(Math.random() * base).toString(base);
res = x + res;
}
if (rem) {
b = Math.pow(base, rem);
x = Math.floor(Math.random() * b).toString(base);
res = x + res;
}
var parsed = parseInt(res, base);
if (existing && existing[res] || parsed !== Infinity && parsed >= Math.pow(2, bits)) {
if (_recursion > 10) {
lib.warn('randstr failed uniqueness');
return res;
}
return randstr(existing, bits, base, (_recursion || 0) + 1);
} else return res;
};
lib.OptionControl = function (opt, optname) {
/*
* An environment to contain all option setters and
* getters that collectively modify opts.
*
* You can call up opts from any function in new object
* as this.optname || this.opt
*
* See FitOpts for example of usage
*/
if (!opt) opt = {};
if (!optname) optname = 'opt';
var self = {};
self.optionList = [];
self._newoption = function (optObj) {
optObj[optname] = opt;
self[optObj.name] = optObj;
self.optionList.push(optObj);
};
self['_' + optname] = opt;
return self;
};
/**
* lib.smooth: smooth arrayIn by convolving with
* a hann window with given full width at half max
* bounce the ends in, so the output has the same length as the input
*/
lib.smooth = function (arrayIn, FWHM) {
FWHM = Math.round(FWHM) || 0; // only makes sense for integers
if (FWHM < 2) return arrayIn;
var alen = arrayIn.length;
var alen2 = 2 * alen;
var wlen = 2 * FWHM - 1;
var w = new Array(wlen);
var arrayOut = new Array(alen);
var i;
var j;
var k;
var v;
// first make the window array
for (i = 0; i < wlen; i++) {
w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
}
// now do the convolution
for (i = 0; i < alen; i++) {
v = 0;
for (j = 0; j < wlen; j++) {
k = i + j + 1 - FWHM;
// multibounce
if (k < -alen) k -= alen2 * Math.round(k / alen2);else if (k >= alen2) k -= alen2 * Math.floor(k / alen2);
// single bounce
if (k < 0) k = -1 - k;else if (k >= alen) k = alen2 - 1 - k;
v += arrayIn[k] * w[j];
}
arrayOut[i] = v;
}
return arrayOut;
};
/**
* syncOrAsync: run a sequence of functions synchronously
* as long as its returns are not promises (ie have no .then)
* includes one argument arg to send to all functions...
* this is mainly just to prevent us having to make wrapper functions
* when the only purpose of the wrapper is to reference gd
* and a final step to be executed at the end
* TODO: if there's an error and everything is sync,
* this doesn't happen yet because we want to make sure
* that it gets reported
*/
lib.syncOrAsync = function (sequence, arg, finalStep) {
var ret, fni;
function continueAsync() {
return lib.syncOrAsync(sequence, arg, finalStep);
}
while (sequence.length) {
fni = sequence.splice(0, 1)[0];
ret = fni(arg);
if (ret && ret.then) {
return ret.then(continueAsync);
}
}
return finalStep && finalStep(arg);
};
/**
* Helper to strip trailing slash, from
* http://stackoverflow.com/questions/6680825/return-string-without-trailing-slash
*/
lib.stripTrailingSlash = function (str) {
if (str.substr(-1) === '/') return str.substr(0, str.length - 1);
return str;
};
lib.noneOrAll = function (containerIn, containerOut, attrList) {
/**
* some attributes come together, so if you have one of them
* in the input, you should copy the default values of the others
* to the input as well.
*/
if (!containerIn) return;
var hasAny = false;
var hasAll = true;
var i;
var val;
for (i = 0; i < attrList.length; i++) {
val = containerIn[attrList[i]];
if (val !== undefined && val !== null) hasAny = true;else hasAll = false;
}
if (hasAny && !hasAll) {
for (i = 0; i < attrList.length; i++) {
containerIn[attrList[i]] = containerOut[attrList[i]];
}
}
};
/** merges calcdata field (given by cdAttr) with traceAttr values
*
* N.B. Loop over minimum of cd.length and traceAttr.length
* i.e. it does not try to fill in beyond traceAttr.length-1
*
* @param {array} traceAttr : trace attribute
* @param {object} cd : calcdata trace
* @param {string} cdAttr : calcdata key
*/
lib.mergeArray = function (traceAttr, cd, cdAttr, fn) {
var hasFn = typeof fn === 'function';
if (lib.isArrayOrTypedArray(traceAttr)) {
var imax = Math.min(traceAttr.length, cd.length);
for (var i = 0; i < imax; i++) {
var v = traceAttr[i];
cd[i][cdAttr] = hasFn ? fn(v) : v;
}
}
};
// cast numbers to positive numbers, returns 0 if not greater than 0
lib.mergeArrayCastPositive = function (traceAttr, cd, cdAttr) {
return lib.mergeArray(traceAttr, cd, cdAttr, function (v) {
var w = +v;
return !isFinite(w) ? 0 : w > 0 ? w : 0;
});
};
/** fills calcdata field (given by cdAttr) with traceAttr values
* or function of traceAttr values (e.g. some fallback)
*
* N.B. Loops over all cd items.
*
* @param {array} traceAttr : trace attribute
* @param {object} cd : calcdata trace
* @param {string} cdAttr : calcdata key
* @param {function} [fn] : optional function to apply to each array item
*/
lib.fillArray = function (traceAttr, cd, cdAttr, fn) {
fn = fn || lib.identity;
if (lib.isArrayOrTypedArray(traceAttr)) {
for (var i = 0; i < cd.length; i++) {
cd[i][cdAttr] = fn(traceAttr[i]);
}
}
};
/** Handler for trace-wide vs per-point options
*
* @param {object} trace : (full) trace object
* @param {number} ptNumber : index of the point in question
* @param {string} astr : attribute string
* @param {function} [fn] : optional function to apply to each array item
*
* @return {any}
*/
lib.castOption = function (trace, ptNumber, astr, fn) {
fn = fn || lib.identity;
var val = lib.nestedProperty(trace, astr).get();
if (lib.isArrayOrTypedArray(val)) {
if (Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) {
return fn(val[ptNumber[0]][ptNumber[1]]);
} else {
return fn(val[ptNumber]);
}
} else {
return val;
}
};
/** Extract option from calcdata item, correctly falling back to
* trace value if not found.
*
* @param {object} calcPt : calcdata[i][j] item
* @param {object} trace : (full) trace object
* @param {string} calcKey : calcdata key
* @param {string} traceKey : aka trace attribute string
* @return {any}
*/
lib.extractOption = function (calcPt, trace, calcKey, traceKey) {
if (calcKey in calcPt) return calcPt[calcKey];
// fallback to trace value,
// must check if value isn't itself an array
// which means the trace attribute has a corresponding
// calcdata key, but its value is falsy
var traceVal = lib.nestedProperty(trace, traceKey).get();
if (!Array.isArray(traceVal)) return traceVal;
};
function makePtIndex2PtNumber(indexToPoints) {
var ptIndex2ptNumber = {};
for (var k in indexToPoints) {
var pts = indexToPoints[k];
for (var j = 0; j < pts.length; j++) {
ptIndex2ptNumber[pts[j]] = +k;
}
}
return ptIndex2ptNumber;
}
/** Tag selected calcdata items
*
* N.B. note that point 'index' corresponds to input data array index
* whereas 'number' is its post-transform version.
*
* @param {array} calcTrace
* @param {object} trace
* - selectedpoints {array}
* - _indexToPoints {object}
* @param {ptNumber2cdIndex} ptNumber2cdIndex (optional)
* optional map object for trace types that do not have 1-to-1 point number to
* calcdata item index correspondence (e.g. histogram)
*/
lib.tagSelected = function (calcTrace, trace, ptNumber2cdIndex) {
var selectedpoints = trace.selectedpoints;
var indexToPoints = trace._indexToPoints;
var ptIndex2ptNumber;
// make pt index-to-number map object, which takes care of transformed traces
if (indexToPoints) {
ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
}
function isCdIndexValid(v) {
return v !== undefined && v < calcTrace.length;
}
for (var i = 0; i < selectedpoints.length; i++) {
var ptIndex = selectedpoints[i];
if (lib.isIndex(ptIndex) || lib.isArrayOrTypedArray(ptIndex) && lib.isIndex(ptIndex[0]) && lib.isIndex(ptIndex[1])) {
var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex;
var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber;
if (isCdIndexValid(cdIndex)) {
calcTrace[cdIndex].selected = 1;
}
}
}
};
lib.selIndices2selPoints = function (trace) {
var selectedpoints = trace.selectedpoints;
var indexToPoints = trace._indexToPoints;
if (indexToPoints) {
var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
var out = [];
for (var i = 0; i < selectedpoints.length; i++) {
var ptIndex = selectedpoints[i];
if (lib.isIndex(ptIndex)) {
var ptNumber = ptIndex2ptNumber[ptIndex];
if (lib.isIndex(ptNumber)) {
out.push(ptNumber);
}
}
}
return out;
} else {
return selectedpoints;
}
};
/** Returns target as set by 'target' transform attribute
*
* @param {object} trace : full trace object
* @param {object} transformOpts : transform option object
* - target (string} :
* either an attribute string referencing an array in the trace object, or
* a set array.
*
* @return {array or false} : the target array (NOT a copy!!) or false if invalid
*/
lib.getTargetArray = function (trace, transformOpts) {
var target = transformOpts.target;
if (typeof target === 'string' && target) {
var array = lib.nestedProperty(trace, target).get();
return lib.isArrayOrTypedArray(array) ? array : false;
} else if (lib.isArrayOrTypedArray(target)) {
return target;
}
return false;
};
/**
* modified version of jQuery's extend to strip out private objs and functions,
* and cut arrays down to first or 1 elements
* because extend-like algorithms are hella slow
* obj2 is assumed to already be clean of these things (including no arrays)
*/
function minExtend(obj1, obj2, opt) {
var objOut = {};
if (typeof obj2 !== 'object') obj2 = {};
var arrayLen = opt === 'pieLike' ? -1 : 3;
var keys = Object.keys(obj1);
var i, k, v;
for (i = 0; i < keys.length; i++) {
k = keys[i];
v = obj1[k];
if (k.charAt(0) === '_' || typeof v === 'function') continue;else if (k === 'module') objOut[k] = v;else if (Array.isArray(v)) {
if (k === 'colorscale' || arrayLen === -1) {
objOut[k] = v.slice();
} else {
objOut[k] = v.slice(0, arrayLen);
}
} else if (lib.isTypedArray(v)) {
if (arrayLen === -1) {
objOut[k] = v.subarray();
} else {
objOut[k] = v.subarray(0, arrayLen);
}
} else if (v && typeof v === 'object') objOut[k] = minExtend(obj1[k], obj2[k], opt);else objOut[k] = v;
}
keys = Object.keys(obj2);
for (i = 0; i < keys.length; i++) {
k = keys[i];
v = obj2[k];
if (typeof v !== 'object' || !(k in objOut) || typeof objOut[k] !== 'object') {
objOut[k] = v;
}
}
return objOut;
}
lib.minExtend = minExtend;
lib.titleCase = function (s) {
return s.charAt(0).toUpperCase() + s.substr(1);
};
lib.containsAny = function (s, fragments) {
for (var i = 0; i < fragments.length; i++) {
if (s.indexOf(fragments[i]) !== -1) return true;
}
return false;
};
lib.isIE = function () {
return typeof window.navigator.msSaveBlob !== 'undefined';
};
var IS_SAFARI_REGEX = /Version\/[\d\.]+.*Safari/;
lib.isSafari = function () {
return IS_SAFARI_REGEX.test(window.navigator.userAgent);
};
var IS_IOS_REGEX = /iPad|iPhone|iPod/;
lib.isIOS = function () {
return IS_IOS_REGEX.test(window.navigator.userAgent);
};
var FIREFOX_VERSION_REGEX = /Firefox\/(\d+)\.\d+/;
lib.getFirefoxVersion = function () {
var match = FIREFOX_VERSION_REGEX.exec(window.navigator.userAgent);
if (match && match.length === 2) {
var versionInt = parseInt(match[1]);
if (!isNaN(versionInt)) {
return versionInt;
}
}
return null;
};
lib.isD3Selection = function (obj) {
return obj instanceof d3.selection;
};
/**
* Append element to DOM only if not present.
*
* @param {d3 selection} parent : parent selection of the element in question
* @param {string} nodeType : node type of element to append
* @param {string} className (optional) : class name of element in question
* @param {fn} enterFn (optional) : optional fn applied to entering elements only
* @return {d3 selection} selection of new layer
*
* Previously, we were using the following pattern:
*
* ```
* var sel = parent.selectAll('.' + className)
* .data([0]);
*
* sel.enter().append(nodeType)
* .classed(className, true);
*
* return sel;
* ```
*
* in numerous places in our codebase to achieve the same behavior.
*
* The logic below performs much better, mostly as we are using
* `.select` instead `.selectAll` that is `querySelector` instead of
* `querySelectorAll`.
*
*/
lib.ensureSingle = function (parent, nodeType, className, enterFn) {
var sel = parent.select(nodeType + (className ? '.' + className : ''));
if (sel.size()) return sel;
var layer = parent.append(nodeType);
if (className) layer.classed(className, true);
if (enterFn) layer.call(enterFn);
return layer;
};
/**
* Same as Lib.ensureSingle, but using id as selector.
* This version is mostly used for clipPath nodes.
*
* @param {d3 selection} parent : parent selection of the element in question
* @param {string} nodeType : node type of element to append
* @param {string} id : id of element in question
* @param {fn} enterFn (optional) : optional fn applied to entering elements only
* @return {d3 selection} selection of new layer
*/
lib.ensureSingleById = function (parent, nodeType, id, enterFn) {
var sel = parent.select(nodeType + '#' + id);
if (sel.size()) return sel;
var layer = parent.append(nodeType).attr('id', id);
if (enterFn) layer.call(enterFn);
return layer;
};
/**
* Converts a string path to an object.
*
* When given a string containing an array element, it will create a `null`
* filled array of the given size.
*
* @example
* lib.objectFromPath('nested.test[2].path', 'value');
* // returns { nested: { test: [null, null, { path: 'value' }]}
*
* @param {string} path to nested value
* @param {*} any value to be set
*
* @return {Object} the constructed object with a full nested path
*/
lib.objectFromPath = function (path, value) {
var keys = path.split('.');
var tmpObj;
var obj = tmpObj = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var el = null;
var parts = keys[i].match(/(.*)\[([0-9]+)\]/);
if (parts) {
key = parts[1];
el = parts[2];
tmpObj = tmpObj[key] = [];
if (i === keys.length - 1) {
tmpObj[el] = value;
} else {
tmpObj[el] = {};
}
tmpObj = tmpObj[el];
} else {
if (i === keys.length - 1) {
tmpObj[key] = value;
} else {
tmpObj[key] = {};
}
tmpObj = tmpObj[key];
}
}
return obj;
};
/**
* Iterate through an object in-place, converting dotted properties to objects.
*
* Examples:
*
* lib.expandObjectPaths({'nested.test.path': 'value'});
* => { nested: { test: {path: 'value'}}}
*
* It also handles array notation, e.g.:
*
* lib.expandObjectPaths({'foo[1].bar': 'value'});
* => { foo: [null, {bar: value}] }
*
* It handles merges the results when two properties are specified in parallel:
*
* lib.expandObjectPaths({'foo[1].bar': 10, 'foo[0].bar': 20});
* => { foo: [{bar: 10}, {bar: 20}] }
*
* It does NOT, however, merge multiple multiply-nested arrays::
*
* lib.expandObjectPaths({'marker[1].range[1]': 5, 'marker[1].range[0]': 4})
* => { marker: [null, {range: 4}] }
*/
// Store this to avoid recompiling regex on *every* prop since this may happen many
// many times for animations. Could maybe be inside the function. Not sure about
// scoping vs. recompilation tradeoff, but at least it's not just inlining it into
// the inner loop.
var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/;
var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;
function notValid(prop) {
// guard against polluting __proto__ and other internals getters and setters
return prop.slice(0, 2) === '__';
}
lib.expandObjectPaths = function (data) {
var match, key, prop, datum, idx, dest, trailingPath;
if (typeof data === 'object' && !Array.isArray(data)) {
for (key in data) {
if (data.hasOwnProperty(key)) {
if (match = key.match(dottedPropertyRegex)) {
datum = data[key];
prop = match[1];
if (notValid(prop)) continue;
delete data[key];
data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]);
} else if (match = key.match(indexedPropertyRegex)) {
datum = data[key];
prop = match[1];
if (notValid(prop)) continue;
idx = parseInt(match[2]);
delete data[key];
data[prop] = data[prop] || [];
if (match[3] === '.') {
// This is the case where theere are subsequent properties into which
// we must recurse, e.g. transforms[0].value
trailingPath = match[4];
dest = data[prop][idx] = data[prop][idx] || {};
// NB: Extend deep no arrays prevents this from working on multiple
// nested properties in the same object, e.g.
//
// {
// foo[0].bar[1].range
// foo[0].bar[0].range
// }
//
// In this case, the extendDeepNoArrays will overwrite one array with
// the other, so that both properties *will not* be present in the
// result. Fixing this would require a more intelligent tracking
// of changes and merging than extendDeepNoArrays currently accomplishes.
lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum)));
} else {
// This is the case where this property is the end of the line,
// e.g. xaxis.range[0]
if (notValid(prop)) continue;
data[prop][idx] = lib.expandObjectPaths(datum);
}
} else {
if (notValid(key)) continue;
data[key] = lib.expandObjectPaths(data[key]);
}
}
}
}
return data;
};
/**
* Converts value to string separated by the provided separators.
*
* @example
* lib.numSeparate(2016, '.,');
* // returns '2016'
*
* @example
* lib.numSeparate(3000, '.,', true);
* // returns '3,000'
*
* @example
* lib.numSeparate(1234.56, '|,')
* // returns '1,234|56'
*
* @param {string|number} value the value to be converted
* @param {string} separators string of decimal, then thousands separators
* @param {boolean} separatethousands boolean, 4-digit integers are separated if true
*
* @return {string} the value that has been separated
*/
lib.numSeparate = function (value, separators, separatethousands) {
if (!separatethousands) separatethousands = false;
if (typeof separators !== 'string' || separators.length === 0) {
throw new Error('Separator string required for formatting!');
}
if (typeof value === 'number') {
value = String(value);
}
var thousandsRe = /(\d+)(\d{3})/;
var decimalSep = separators.charAt(0);
var thouSep = separators.charAt(1);
var x = value.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? decimalSep + x[1] : '';
// Years are ignored for thousands separators
if (thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) {
while (thousandsRe.test(x1)) {
x1 = x1.replace(thousandsRe, '$1' + thouSep + '$2');
}
}
return x1 + x2;
};
lib.TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)([:|\|][^}]*)?}/g;
var SIMPLE_PROPERTY_REGEX = /^\w*$/;
/**
* Substitute values from an object into a string
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
*
* @param {string} input string containing %{...} template strings
* @param {obj} data object containing substitution values
*
* @return {string} templated string
*/
lib.templateString = function (string, obj) {
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};
return string.replace(lib.TEMPLATE_STRING_REGEX, function (dummy, key) {
var v;
if (SIMPLE_PROPERTY_REGEX.test(key)) {
v = obj[key];
} else {
getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get;
v = getterCache[key]();
}
return lib.isValidTextValue(v) ? v : '';
});
};
var hovertemplateWarnings = {
max: 10,
count: 0,
name: 'hovertemplate'
};
lib.hovertemplateString = function () {
return templateFormatString.apply(hovertemplateWarnings, arguments);
};
var texttemplateWarnings = {
max: 10,
count: 0,
name: 'texttemplate'
};
lib.texttemplateString = function () {
return templateFormatString.apply(texttemplateWarnings, arguments);
};
// Regex for parsing multiplication and division operations applied to a template key
// Used for shape.label.texttemplate
// Matches a key name (non-whitespace characters), followed by a * or / character, followed by a number
// For example, the following strings are matched: `x0*2`, `slope/1.60934`, `y1*2.54`
var MULT_DIV_REGEX = /^(\S+)([\*\/])(-?\d+(\.\d+)?)$/;
function multDivParser(inputStr) {
var match = inputStr.match(MULT_DIV_REGEX);
if (match) return {
key: match[1],
op: match[2],
number: Number(match[3])
};
return {
key: inputStr,
op: null,
number: null
};
}
var texttemplateWarningsForShapes = {
max: 10,
count: 0,
name: 'texttemplate',
parseMultDiv: true
};
lib.texttemplateStringForShapes = function () {
return templateFormatString.apply(texttemplateWarningsForShapes, arguments);
};
var TEMPLATE_STRING_FORMAT_SEPARATOR = /^[:|\|]/;
/**
* Substitute values from an object into a string and optionally formats them using d3-format,
* or fallback to associated labels.
*
* Examples:
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} d3 locale
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
function templateFormatString(string, labels, d3locale) {
var opts = this;
var args = arguments;
if (!labels) labels = {};
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};
return string.replace(lib.TEMPLATE_STRING_REGEX, function (match, rawKey, format) {
var isOther = rawKey === 'xother' || rawKey === 'yother';
var isSpaceOther = rawKey === '_xother' || rawKey === '_yother';
var isSpaceOtherSpace = rawKey === '_xother_' || rawKey === '_yother_';
var isOtherSpace = rawKey === 'xother_' || rawKey === 'yother_';
var hasOther = isOther || isSpaceOther || isOtherSpace || isSpaceOtherSpace;
var key = rawKey;
if (isSpaceOther || isSpaceOtherSpace) key = key.substring(1);
if (isOtherSpace || isSpaceOtherSpace) key = key.substring(0, key.length - 1);
// Shape labels support * and / operators in template string
// Parse these if the parseMultDiv param is set to true
var parsedOp = null;
var parsedNumber = null;
if (opts.parseMultDiv) {
var _match = multDivParser(key);
key = _match.key;
parsedOp = _match.op;
parsedNumber = _match.number;
}
var value;
if (hasOther) {
value = labels[key];
if (value === undefined) return '';
} else {
var obj, i;
for (i = 3; i < args.length; i++) {
obj = args[i];
if (!obj) continue;
if (obj.hasOwnProperty(key)) {
value = obj[key];
break;
}
if (!SIMPLE_PROPERTY_REGEX.test(key)) {
value = lib.nestedProperty(obj, key).get();
value = getterCache[key] || lib.nestedProperty(obj, key).get();
if (value) getterCache[key] = value;
}
if (value !== undefined) break;
}
}
// Apply mult/div operation (if applicable)
if (value !== undefined) {
if (parsedOp === '*') value *= parsedNumber;
if (parsedOp === '/') value /= parsedNumber;
}
if (value === undefined && opts) {
if (opts.count < opts.max) {
lib.warn('Variable \'' + key + '\' in ' + opts.name + ' could not be found!');
value = match;
}
if (opts.count === opts.max) {
lib.warn('Too many ' + opts.name + ' warnings - additional warnings will be suppressed');
}
opts.count++;
return match;
}
if (format) {
var fmt;
if (format[0] === ':') {
fmt = d3locale ? d3locale.numberFormat : lib.numberFormat;
if (value !== '') {
// e.g. skip missing data on heatmap
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
}
}
if (format[0] === '|') {
fmt = d3locale ? d3locale.timeFormat : utcFormat;
var ms = lib.dateTime2ms(value);
value = lib.formatDate(ms, format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''), false, fmt);
}
} else {
var keyLabel = key + 'Label';
if (labels.hasOwnProperty(keyLabel)) value = labels[keyLabel];
}
if (hasOther) {
value = '(' + value + ')';
if (isSpaceOther || isSpaceOtherSpace) value = ' ' + value;
if (isOtherSpace || isSpaceOtherSpace) value = value + ' ';
}
return value;
});
}
/*
* alphanumeric string sort, tailored for subplot IDs like scene2, scene10, x10y13 etc
*/
var char0 = 48;
var char9 = 57;
lib.subplotSort = function (a, b) {
var l = Math.min(a.length, b.length) + 1;
var numA = 0;
var numB = 0;
for (var i = 0; i < l; i++) {
var charA = a.charCodeAt(i) || 0;
var charB = b.charCodeAt(i) || 0;
var isNumA = charA >= char0 && charA <= char9;
var isNumB = charB >= char0 && charB <= char9;
if (isNumA) numA = 10 * numA + charA - char0;
if (isNumB) numB = 10 * numB + charB - char0;
if (!isNumA || !isNumB) {
if (numA !== numB) return numA - numB;
if (charA !== charB) return charA - charB;
}
}
return numB - numA;
};
// repeatable pseudorandom generator
var randSeed = 2000000000;
lib.seedPseudoRandom = function () {
randSeed = 2000000000;
};
lib.pseudoRandom = function () {
var lastVal = randSeed;
randSeed = (69069 * randSeed + 1) % 4294967296;
// don't let consecutive vals be too close together
// gets away from really trying to be random, in favor of better local uniformity
if (Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom();
return randSeed / 4294967296;
};
/** Fill hover 'pointData' container with 'correct' hover text value
*
* - If trace hoverinfo contains a 'text' flag and hovertext is not set,
* the text elements will be seen in the hover labels.
*
* - If trace hoverinfo contains a 'text' flag and hovertext is set,
* hovertext takes precedence over text
* i.e. the hoverinfo elements will be seen in the hover labels
*
* @param {object} calcPt
* @param {object} trace
* @param {object || array} contOut (mutated here)
*/
lib.fillText = function (calcPt, trace, contOut) {
var fill = Array.isArray(contOut) ? function (v) {
contOut.push(v);
} : function (v) {
contOut.text = v;
};
var htx = lib.extractOption(calcPt, trace, 'htx', 'hovertext');
if (lib.isValidTextValue(htx)) return fill(htx);
var tx = lib.extractOption(calcPt, trace, 'tx', 'text');
if (lib.isValidTextValue(tx)) return fill(tx);
};
// accept all truthy values and 0 (which gets cast to '0' in the hover labels)
lib.isValidTextValue = function (v) {
return v || v === 0;
};
/**
* @param {number} ratio
* @param {number} n (number of decimal places)
*/
lib.formatPercent = function (ratio, n) {
n = n || 0;
var str = (Math.round(100 * ratio * Math.pow(10, n)) * Math.pow(0.1, n)).toFixed(n) + '%';
for (var i = 0; i < n; i++) {
if (str.indexOf('.') !== -1) {
str = str.replace('0%', '%');
str = str.replace('.%', '%');
}
}
return str;
};
lib.isHidden = function (gd) {
var display = window.getComputedStyle(gd).display;
return !display || display === 'none';
};
lib.strTranslate = function (x, y) {
return x || y ? 'translate(' + x + ',' + y + ')' : '';
};
lib.strRotate = function (a) {
return a ? 'rotate(' + a + ')' : '';
};
lib.strScale = function (s) {
return s !== 1 ? 'scale(' + s + ')' : '';
};
/** Return transform text for bar bar-like rectangles and pie-like slices
* @param {object} transform
* - targetX: desired position on the x-axis
* - targetY: desired position on the y-axis
* - textX: text middle position on the x-axis
* - textY: text middle position on the y-axis
* - anchorX: (optional) text anchor position on the x-axis (computed from textX), zero for middle anchor
* - anchorY: (optional) text anchor position on the y-axis (computed from textY), zero for middle anchor
* - scale: (optional) scale applied after translate
* - rotate: (optional) rotation applied after scale
* - noCenter: when defined no extra arguments needed in rotation
*/
lib.getTextTransform = function (transform) {
var noCenter = transform.noCenter;
var textX = transform.textX;
var textY = transform.textY;
var targetX = transform.targetX;
var targetY = transform.targetY;
var anchorX = transform.anchorX || 0;
var anchorY = transform.anchorY || 0;
var rotate = transform.rotate;
var scale = transform.scale;
if (!scale) scale = 0;else if (scale > 1) scale = 1;
return lib.strTranslate(targetX - scale * (textX + anchorX), targetY - scale * (textY + anchorY)) + lib.strScale(scale) + (rotate ? 'rotate(' + rotate + (noCenter ? '' : ' ' + textX + ' ' + textY) + ')' : '');
};
lib.setTransormAndDisplay = function (s, transform) {
s.attr('transform', lib.getTextTransform(transform));
s.style('display', transform.scale ? null : 'none');
};
lib.ensureUniformFontSize = function (gd, baseFont) {
var out = lib.extendFlat({}, baseFont);
out.size = Math.max(baseFont.size, gd._fullLayout.uniformtext.minsize || 0);
return out;
};
/**
* provide a human-readable list e.g. "A, B, C and D" with an ending separator
*
* @param {array} arr : the array to join
* @param {string} mainSeparator : main separator
* @param {string} lastSeparator : last separator
*
* @return {string} : joined list
*/
lib.join2 = function (arr, mainSeparator, lastSeparator) {
var len = arr.length;
if (len > 1) {
return arr.slice(0, -1).join(mainSeparator) + lastSeparator + arr[len - 1];
}
return arr.join(mainSeparator);
};
lib.bigFont = function (size) {
return Math.round(1.2 * size);
};
var firefoxVersion = lib.getFirefoxVersion();
// see https://bugzilla.mozilla.org/show_bug.cgi?id=1684973
var isProblematicFirefox = firefoxVersion !== null && firefoxVersion < 86;
/**
* Return the mouse position from the last event registered by D3.
* @returns An array with two numbers, representing the x and y coordinates of the mouse pointer
* at the event relative to the targeted node.
*/
lib.getPositionFromD3Event = function () {
if (isProblematicFirefox) {
// layerX and layerY are non-standard, so we only fallback to them when we have to:
return [d3.event.layerX, d3.event.layerY];
} else {
return [d3.event.offsetX, d3.event.offsetY];
}
};
/***/ }),
/***/ 63620:
/***/ (function(module) {
"use strict";
// more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
module.exports = function isPlainObject(obj) {
// We need to be a little less strict in the `imagetest` container because
// of how async image requests are handled.
//
// N.B. isPlainObject(new Constructor()) will return true in `imagetest`
if (window && window.process && window.process.versions) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
return Object.prototype.toString.call(obj) === '[object Object]' && Object.getPrototypeOf(obj).hasOwnProperty('hasOwnProperty');
};
/***/ }),
/***/ 37804:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var nestedProperty = __webpack_require__(22296);
var SIMPLE_PROPERTY_REGEX = /^\w*$/;
// bitmask for deciding what's updated. Sometimes the name needs to be updated,
// sometimes the value needs to be updated, and sometimes both do. This is just
// a simple way to track what's updated such that it's a simple OR operation to
// assimilate new updates.
//
// The only exception is the UNSET bit that tracks when we need to explicitly
// unset and remove the property. This concrn arises because of the special
// way in which nestedProperty handles null/undefined. When you specify `null`,
// it prunes any unused items in the tree. I ran into some issues with it getting
// null vs undefined confused, so UNSET is just a bit that forces the property
// update to send `null`, removing the property explicitly rather than setting
// it to undefined.
var NONE = 0;
var NAME = 1;
var VALUE = 2;
var BOTH = 3;
var UNSET = 4;
module.exports = function keyedContainer(baseObj, path, keyName, valueName) {
keyName = keyName || 'name';
valueName = valueName || 'value';
var i, arr, baseProp;
var changeTypes = {};
if (path && path.length) {
baseProp = nestedProperty(baseObj, path);
arr = baseProp.get();
} else {
arr = baseObj;
}
path = path || '';
// Construct an index:
var indexLookup = {};
if (arr) {
for (i = 0; i < arr.length; i++) {
indexLookup[arr[i][keyName]] = i;
}
}
var isSimpleValueProp = SIMPLE_PROPERTY_REGEX.test(valueName);
var obj = {
set: function (name, value) {
var changeType = value === null ? UNSET : NONE;
// create the base array if necessary
if (!arr) {
if (!baseProp || changeType === UNSET) return;
arr = [];
baseProp.set(arr);
}
var idx = indexLookup[name];
if (idx === undefined) {
if (changeType === UNSET) return;
changeType = changeType | BOTH;
idx = arr.length;
indexLookup[name] = idx;
} else if (value !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty(arr[idx], valueName).get())) {
changeType = changeType | VALUE;
}
var newValue = arr[idx] = arr[idx] || {};
newValue[keyName] = name;
if (isSimpleValueProp) {
newValue[valueName] = value;
} else {
nestedProperty(newValue, valueName).set(value);
}
// If it's not an unset, force that bit to be unset. This is all related to the fact
// that undefined and null are a bit specially implemented in nestedProperties.
if (value !== null) {
changeType = changeType & ~UNSET;
}
changeTypes[idx] = changeTypes[idx] | changeType;
return obj;
},
get: function (name) {
if (!arr) return;
var idx = indexLookup[name];
if (idx === undefined) {
return undefined;
} else if (isSimpleValueProp) {
return arr[idx][valueName];
} else {
return nestedProperty(arr[idx], valueName).get();
}
},
rename: function (name, newName) {
var idx = indexLookup[name];
if (idx === undefined) return obj;
changeTypes[idx] = changeTypes[idx] | NAME;
indexLookup[newName] = idx;
delete indexLookup[name];
arr[idx][keyName] = newName;
return obj;
},
remove: function (name) {
var idx = indexLookup[name];
if (idx === undefined) return obj;
var object = arr[idx];
if (Object.keys(object).length > 2) {
// This object contains more than just the key/value, so unset
// the value without modifying the entry otherwise:
changeTypes[idx] = changeTypes[idx] | VALUE;
return obj.set(name, null);
}
if (isSimpleValueProp) {
for (i = idx; i < arr.length; i++) {
changeTypes[i] = changeTypes[i] | BOTH;
}
for (i = idx; i < arr.length; i++) {
indexLookup[arr[i][keyName]]--;
}
arr.splice(idx, 1);
delete indexLookup[name];
} else {
// Perform this update *strictly* so we can check whether the result's
// been pruned. If so, it's a removal. If not, it's a value unset only.
nestedProperty(object, valueName).set(null);
// Now check if the top level nested property has any keys left. If so,
// the object still has values so we only want to unset the key. If not,
// the entire object can be removed since there's no other data.
// var topLevelKeys = Object.keys(object[valueName.split('.')[0]] || []);
changeTypes[idx] = changeTypes[idx] | VALUE | UNSET;
}
return obj;
},
constructUpdate: function () {
var astr, idx;
var update = {};
var changed = Object.keys(changeTypes);
for (var i = 0; i < changed.length; i++) {
idx = changed[i];
astr = path + '[' + idx + ']';
if (arr[idx]) {
if (changeTypes[idx] & NAME) {
update[astr + '.' + keyName] = arr[idx][keyName];
}
if (changeTypes[idx] & VALUE) {
if (isSimpleValueProp) {
update[astr + '.' + valueName] = changeTypes[idx] & UNSET ? null : arr[idx][valueName];
} else {
update[astr + '.' + valueName] = changeTypes[idx] & UNSET ? null : nestedProperty(arr[idx], valueName).get();
}
}
} else {
update[astr] = null;
}
}
return update;
}
};
return obj;
};
/***/ }),
/***/ 98356:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
/**
* localize: translate a string for the current locale
*
* @param {object} gd: the graphDiv for context
* gd._context.locale determines the language (& optional region/country)
* the dictionary for each locale may either be supplied in
* gd._context.locales or globally via Plotly.register
* @param {string} s: the string to translate
*/
module.exports = function localize(gd, s) {
var locale = gd._context.locale;
/*
* Priority of lookup:
* contextDicts[locale],
* registeredDicts[locale],
* contextDicts[baseLocale], (if baseLocale is distinct)
* registeredDicts[baseLocale]
* Return the first translation we find.
* This way if you have a regionalization you are allowed to specify
* only what's different from the base locale, everything else will
* fall back on the base.
*/
for (var i = 0; i < 2; i++) {
var locales = gd._context.locales;
for (var j = 0; j < 2; j++) {
var dict = (locales[locale] || {}).dictionary;
if (dict) {
var out = dict[s];
if (out) return out;
}
locales = Registry.localeRegistry;
}
var baseLocale = locale.split('-')[0];
if (baseLocale === locale) break;
locale = baseLocale;
}
return s;
};
/***/ }),
/***/ 24248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* eslint-disable no-console */
var dfltConfig = (__webpack_require__(20556).dfltConfig);
var notifier = __webpack_require__(41792);
var loggers = module.exports = {};
/**
* ------------------------------------------
* debugging tools
* ------------------------------------------
*/
loggers.log = function () {
var i;
if (dfltConfig.logging > 1) {
var messages = ['LOG:'];
for (i = 0; i < arguments.length; i++) {
messages.push(arguments[i]);
}
console.trace.apply(console, messages);
}
if (dfltConfig.notifyOnLogging > 1) {
var lines = [];
for (i = 0; i < arguments.length; i++) {
lines.push(arguments[i]);
}
notifier(lines.join(' '), 'long');
}
};
loggers.warn = function () {
var i;
if (dfltConfig.logging > 0) {
var messages = ['WARN:'];
for (i = 0; i < arguments.length; i++) {
messages.push(arguments[i]);
}
console.trace.apply(console, messages);
}
if (dfltConfig.notifyOnLogging > 0) {
var lines = [];
for (i = 0; i < arguments.length; i++) {
lines.push(arguments[i]);
}
notifier(lines.join(' '), 'stick');
}
};
loggers.error = function () {
var i;
if (dfltConfig.logging > 0) {
var messages = ['ERROR:'];
for (i = 0; i < arguments.length; i++) {
messages.push(arguments[i]);
}
console.error.apply(console, messages);
}
if (dfltConfig.notifyOnLogging > 0) {
var lines = [];
for (i = 0; i < arguments.length; i++) {
lines.push(arguments[i]);
}
notifier(lines.join(' '), 'stick');
}
};
/***/ }),
/***/ 30988:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
/**
* General helper to manage trace groups based on calcdata
*
* @param {d3.selection} traceLayer: a selection containing a single group
* to draw these traces into
* @param {array} cdModule: array of calcdata items for this
* module and subplot combination. Assumes the calcdata item for each
* trace is an array with the fullData trace attached to the first item.
* @param {string} cls: the class attribute to give each trace group
* so you can give multiple classes separated by spaces
*/
module.exports = function makeTraceGroups(traceLayer, cdModule, cls) {
var traces = traceLayer.selectAll('g.' + cls.replace(/\s/g, '.')).data(cdModule, function (cd) {
return cd[0].trace.uid;
});
traces.exit().remove();
traces.enter().append('g').attr('class', cls);
traces.order();
// stash ref node to trace group in calcdata,
// useful for (fast) styleOnSelect
var k = traceLayer.classed('rangeplot') ? 'nodeRangePlot3' : 'node3';
traces.each(function (cd) {
cd[0][k] = d3.select(this);
});
return traces;
};
/***/ }),
/***/ 52248:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var mat4X4 = __webpack_require__(36524);
exports.init2dArray = function (rowLength, colLength) {
var array = new Array(rowLength);
for (var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
return array;
};
/**
* transpose a (possibly ragged) 2d array z. inspired by
* http://stackoverflow.com/questions/17428587/
* transposing-a-2d-array-in-javascript
*/
exports.transposeRagged = function (z) {
var maxlen = 0;
var zlen = z.length;
var i, j;
// Maximum row length:
for (i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);
var t = new Array(maxlen);
for (i = 0; i < maxlen; i++) {
t[i] = new Array(zlen);
for (j = 0; j < zlen; j++) t[i][j] = z[j][i];
}
return t;
};
// our own dot function so that we don't need to include numeric
exports.dot = function (x, y) {
if (!(x.length && y.length) || x.length !== y.length) return null;
var len = x.length;
var out;
var i;
if (x[0].length) {
// mat-vec or mat-mat
out = new Array(len);
for (i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
} else if (y[0].length) {
// vec-mat
var yTranspose = exports.transposeRagged(y);
out = new Array(yTranspose.length);
for (i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
} else {
// vec-vec
out = 0;
for (i = 0; i < len; i++) out += x[i] * y[i];
}
return out;
};
// translate by (x,y)
exports.translationMatrix = function (x, y) {
return [[1, 0, x], [0, 1, y], [0, 0, 1]];
};
// rotate by alpha around (0,0)
exports.rotationMatrix = function (alpha) {
var a = alpha * Math.PI / 180;
return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], [0, 0, 1]];
};
// rotate by alpha around (x,y)
exports.rotationXYMatrix = function (a, x, y) {
return exports.dot(exports.dot(exports.translationMatrix(x, y), exports.rotationMatrix(a)), exports.translationMatrix(-x, -y));
};
// applies a 3D transformation matrix to either x, y and z params
// Note: z is optional
exports.apply3DTransform = function (transform) {
return function () {
var args = arguments;
var xyz = arguments.length === 1 ? args[0] : [args[0], args[1], args[2] || 0];
return exports.dot(transform, [xyz[0], xyz[1], xyz[2], 1]).slice(0, 3);
};
};
// applies a 2D transformation matrix to either x and y params or an [x,y] array
exports.apply2DTransform = function (transform) {
return function () {
var args = arguments;
if (args.length === 3) {
args = args[0];
} // from map
var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
};
};
// applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment)
exports.apply2DTransform2 = function (transform) {
var at = exports.apply2DTransform(transform);
return function (xys) {
return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
};
};
exports.convertCssMatrix = function (m) {
if (m) {
var len = m.length;
if (len === 16) return m;
if (len === 6) {
// converts a 2x3 css transform matrix to a 4x4 matrix see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix
return [m[0], m[1], 0, 0, m[2], m[3], 0, 0, 0, 0, 1, 0, m[4], m[5], 0, 1];
}
}
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
};
// find the inverse for a 4x4 affine transform matrix
exports.inverseTransformMatrix = function (m) {
var out = [];
mat4X4.invert(out, m);
return [[out[0], out[1], out[2], out[3]], [out[4], out[5], out[6], out[7]], [out[8], out[9], out[10], out[11]], [out[12], out[13], out[14], out[15]]];
};
/***/ }),
/***/ 20435:
/***/ (function(module) {
"use strict";
/**
* sanitized modulus function that always returns in the range [0, d)
* rather than (-d, 0] if v is negative
*/
function mod(v, d) {
var out = v % d;
return out < 0 ? out + d : out;
}
/**
* sanitized modulus function that always returns in the range [-d/2, d/2]
* rather than (-d, 0] if v is negative
*/
function modHalf(v, d) {
return Math.abs(v) > d / 2 ? v - Math.round(v / d) * d : v;
}
module.exports = {
mod: mod,
modHalf: modHalf
};
/***/ }),
/***/ 22296:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var isArrayOrTypedArray = (__webpack_require__(38116).isArrayOrTypedArray);
/**
* convert a string s (such as 'xaxis.range[0]')
* representing a property of nested object into set and get methods
* also return the string and object so we don't have to keep track of them
* allows [-1] for an array index, to set a property inside all elements
* of an array
* eg if obj = {arr: [{a: 1}, {a: 2}]}
* you can do p = nestedProperty(obj, 'arr[-1].a')
* but you cannot set the array itself this way, to do that
* just set the whole array.
* eg if obj = {arr: [1, 2, 3]}
* you can't do nestedProperty(obj, 'arr[-1]').set(5)
* but you can do nestedProperty(obj, 'arr').set([5, 5, 5])
*/
module.exports = function nestedProperty(container, propStr) {
if (isNumeric(propStr)) propStr = String(propStr);else if (typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') {
throw 'bad property string';
}
var propParts = propStr.split('.');
var indexed;
var indices;
var i, j;
for (j = 0; j < propParts.length; j++) {
// guard against polluting __proto__ and other internals
if (String(propParts[j]).slice(0, 2) === '__') {
throw 'bad property string';
}
}
// check for parts of the nesting hierarchy that are numbers (ie array elements)
j = 0;
while (j < propParts.length) {
// look for non-bracket chars, then any number of [##] blocks
indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
if (indexed) {
if (indexed[1]) propParts[j] = indexed[1];
// allow propStr to start with bracketed array indices
else if (j === 0) propParts.splice(0, 1);else throw 'bad property string';
indices = indexed[2].substr(1, indexed[2].length - 2).split('][');
for (i = 0; i < indices.length; i++) {
j++;
propParts.splice(j, 0, Number(indices[i]));
}
}
j++;
}
if (typeof container !== 'object') {
return badContainer(container, propStr, propParts);
}
return {
set: npSet(container, propParts, propStr),
get: npGet(container, propParts),
astr: propStr,
parts: propParts,
obj: container
};
};
function npGet(cont, parts) {
return function () {
var curCont = cont;
var curPart;
var allSame;
var out;
var i;
var j;
for (i = 0; i < parts.length - 1; i++) {
curPart = parts[i];
if (curPart === -1) {
allSame = true;
out = [];
for (j = 0; j < curCont.length; j++) {
out[j] = npGet(curCont[j], parts.slice(i + 1))();
if (out[j] !== out[0]) allSame = false;
}
return allSame ? out[0] : out;
}
if (typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
return undefined;
}
curCont = curCont[curPart];
if (typeof curCont !== 'object' || curCont === null) {
return undefined;
}
}
// only hit this if parts.length === 1
if (typeof curCont !== 'object' || curCont === null) return undefined;
out = curCont[parts[i]];
if (out === null) return undefined;
return out;
};
}
/*
* Can this value be deleted? We can delete `undefined`, and `null` except INSIDE an
* *args* array.
*
* Previously we also deleted some `{}` and `[]`, in order to try and make set/unset
* a net noop; but this causes far more complication than it's worth, and still had
* lots of exceptions. See https://github.com/plotly/plotly.js/issues/1410
*
* *args* arrays get passed directly to API methods and we should respect null if
* the user put it there, but otherwise null is deleted as we use it as code
* in restyle/relayout/update for "delete this value" whereas undefined means
* "ignore this edit"
*/
var ARGS_PATTERN = /(^|\.)args\[/;
function isDeletable(val, propStr) {
return val === undefined || val === null && !propStr.match(ARGS_PATTERN);
}
function npSet(cont, parts, propStr) {
return function (val) {
var curCont = cont;
var propPart = '';
var containerLevels = [[cont, propPart]];
var toDelete = isDeletable(val, propStr);
var curPart;
var i;
for (i = 0; i < parts.length - 1; i++) {
curPart = parts[i];
if (typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
throw 'array index but container is not an array';
}
// handle special -1 array index
if (curPart === -1) {
toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr);
if (toDelete) break;else return;
}
if (!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
break;
}
curCont = curCont[curPart];
if (typeof curCont !== 'object' || curCont === null) {
throw 'container is not an object';
}
propPart = joinPropStr(propPart, curPart);
containerLevels.push([curCont, propPart]);
}
if (toDelete) {
if (i === parts.length - 1) {
delete curCont[parts[i]];
// The one bit of pruning we still do: drop `undefined` from the end of arrays.
// In case someone has already unset previous items, continue until we hit a
// non-undefined value.
if (Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
while (curCont.length && curCont[curCont.length - 1] === undefined) {
curCont.pop();
}
}
}
} else curCont[parts[i]] = val;
};
}
function joinPropStr(propStr, newPart) {
var toAdd = newPart;
if (isNumeric(newPart)) toAdd = '[' + newPart + ']';else if (propStr) toAdd = '.' + newPart;
return propStr + toAdd;
}
// handle special -1 array index
function setArrayAll(containerArray, innerParts, val, propStr) {
var arrayVal = isArrayOrTypedArray(val);
var allSet = true;
var thisVal = val;
var thisPropStr = propStr.replace('-1', 0);
var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr);
var firstPart = innerParts[0];
var i;
for (i = 0; i < containerArray.length; i++) {
thisPropStr = propStr.replace('-1', i);
if (arrayVal) {
thisVal = val[i % val.length];
deleteThis = isDeletable(thisVal, thisPropStr);
}
if (deleteThis) allSet = false;
if (!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
continue;
}
npSet(containerArray[i], innerParts, propStr.replace('-1', i))(thisVal);
}
return allSet;
}
/**
* make new sub-container as needed.
* returns false if there's no container and none is needed
* because we're only deleting an attribute
*/
function checkNewContainer(container, part, nextPart, toDelete) {
if (container[part] === undefined) {
if (toDelete) return false;
if (typeof nextPart === 'number') container[part] = [];else container[part] = {};
}
return true;
}
function badContainer(container, propStr, propParts) {
return {
set: function () {
throw 'bad container';
},
get: function () {},
astr: propStr,
parts: propParts,
obj: container
};
}
/***/ }),
/***/ 16628:
/***/ (function(module) {
"use strict";
// Simple helper functions
// none of these need any external deps
module.exports = function noop() {};
/***/ }),
/***/ 41792:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var isNumeric = __webpack_require__(38248);
var NOTEDATA = [];
/**
* notifier
* @param {String} text The person's user name
* @param {Number} [delay=1000] The delay time in milliseconds
* or 'long' which provides 2000 ms delay time.
* @return {undefined} this function does not return a value
*/
module.exports = function (text, displayLength) {
if (NOTEDATA.indexOf(text) !== -1) return;
NOTEDATA.push(text);
var ts = 1000;
if (isNumeric(displayLength)) ts = displayLength;else if (displayLength === 'long') ts = 3000;
var notifierContainer = d3.select('body').selectAll('.plotly-notifier').data([0]);
notifierContainer.enter().append('div').classed('plotly-notifier', true);
var notes = notifierContainer.selectAll('.notifier-note').data(NOTEDATA);
function killNote(transition) {
transition.duration(700).style('opacity', 0).each('end', function (thisText) {
var thisIndex = NOTEDATA.indexOf(thisText);
if (thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
d3.select(this).remove();
});
}
notes.enter().append('div').classed('notifier-note', true).style('opacity', 0).each(function (thisText) {
var note = d3.select(this);
note.append('button').classed('notifier-close', true).html('×').on('click', function () {
note.transition().call(killNote);
});
var p = note.append('p');
var lines = thisText.split(/ /g);
for (var i = 0; i < lines.length; i++) {
if (i) p.append('br');
p.append('span').text(lines[i]);
}
if (displayLength === 'stick') {
note.transition().duration(350).style('opacity', 1);
} else {
note.transition().duration(700).style('opacity', 1).transition().delay(ts).call(killNote);
}
});
};
/***/ }),
/***/ 72213:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var setCursor = __webpack_require__(93972);
var STASHATTR = 'data-savedcursor';
var NO_CURSOR = '!!';
/*
* works with our CSS cursor classes (see css/_cursor.scss)
* to override a previous cursor set on d3 single-element selections,
* by moving the name of the original cursor to the data-savedcursor attr.
* omit cursor to revert to the previously set value.
*/
module.exports = function overrideCursor(el3, csr) {
var savedCursor = el3.attr(STASHATTR);
if (csr) {
if (!savedCursor) {
var classes = (el3.attr('class') || '').split(' ');
for (var i = 0; i < classes.length; i++) {
var cls = classes[i];
if (cls.indexOf('cursor-') === 0) {
el3.attr(STASHATTR, cls.substr(7)).classed(cls, false);
}
}
if (!el3.attr(STASHATTR)) {
el3.attr(STASHATTR, NO_CURSOR);
}
}
setCursor(el3, csr);
} else if (savedCursor) {
el3.attr(STASHATTR, null);
if (savedCursor === NO_CURSOR) setCursor(el3);else setCursor(el3, savedCursor);
}
};
/***/ }),
/***/ 92065:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var dot = (__webpack_require__(52248).dot);
var BADNUM = (__webpack_require__(39032).BADNUM);
var polygon = module.exports = {};
/**
* Turn an array of [x, y] pairs into a polygon object
* that can test if points are inside it
*
* @param ptsIn Array of [x, y] pairs
*
* @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains}
* (x|y)(min|max) are the bounding rect of the polygon
* pts is the original array, with the first pair repeated at the end
* contains is a function: (pt, omitFirstEdge)
* pt is the [x, y] pair to test
* omitFirstEdge truthy means points exactly on the first edge don't
* count. This is for use adding one polygon to another so we
* don't double-count the edge where they meet.
* returns boolean: is pt inside the polygon (including on its edges)
*/
polygon.tester = function tester(ptsIn) {
var pts = ptsIn.slice();
var xmin = pts[0][0];
var xmax = xmin;
var ymin = pts[0][1];
var ymax = ymin;
var i;
if (pts[pts.length - 1][0] !== pts[0][0] || pts[pts.length - 1][1] !== pts[0][1]) {
// close the polygon
pts.push(pts[0]);
}
for (i = 1; i < pts.length; i++) {
xmin = Math.min(xmin, pts[i][0]);
xmax = Math.max(xmax, pts[i][0]);
ymin = Math.min(ymin, pts[i][1]);
ymax = Math.max(ymax, pts[i][1]);
}
// do we have a rectangle? Handle this here, so we can use the same
// tester for the rectangular case without sacrificing speed
var isRect = false;
var rectFirstEdgeTest;
if (pts.length === 5) {
if (pts[0][0] === pts[1][0]) {
// vert, horz, vert, horz
if (pts[2][0] === pts[3][0] && pts[0][1] === pts[3][1] && pts[1][1] === pts[2][1]) {
isRect = true;
rectFirstEdgeTest = function (pt) {
return pt[0] === pts[0][0];
};
}
} else if (pts[0][1] === pts[1][1]) {
// horz, vert, horz, vert
if (pts[2][1] === pts[3][1] && pts[0][0] === pts[3][0] && pts[1][0] === pts[2][0]) {
isRect = true;
rectFirstEdgeTest = function (pt) {
return pt[1] === pts[0][1];
};
}
}
}
function rectContains(pt, omitFirstEdge) {
var x = pt[0];
var y = pt[1];
if (x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
// pt is outside the bounding box of polygon
return false;
}
if (omitFirstEdge && rectFirstEdgeTest(pt)) return false;
return true;
}
function contains(pt, omitFirstEdge) {
var x = pt[0];
var y = pt[1];
if (x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
// pt is outside the bounding box of polygon
return false;
}
var imax = pts.length;
var x1 = pts[0][0];
var y1 = pts[0][1];
var crossings = 0;
var i;
var x0;
var y0;
var xmini;
var ycross;
for (i = 1; i < imax; i++) {
// find all crossings of a vertical line upward from pt with
// polygon segments
// crossings exactly at xmax don't count, unless the point is
// exactly on the segment, then it counts as inside.
x0 = x1;
y0 = y1;
x1 = pts[i][0];
y1 = pts[i][1];
xmini = Math.min(x0, x1);
if (x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) {
// outside the bounding box of this segment, it's only a crossing
// if it's below the box.
continue;
} else if (y < Math.min(y0, y1)) {
// don't count the left-most point of the segment as a crossing
// because we don't want to double-count adjacent crossings
// UNLESS the polygon turns past vertical at exactly this x
// Note that this is repeated below, but we can't factor it out
// because
if (x !== xmini) crossings++;
} else {
// inside the bounding box, check the actual line intercept
// vertical segment - we know already that the point is exactly
// on the segment, so mark the crossing as exactly at the point.
if (x1 === x0) ycross = y;
// any other angle
else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0);
// exactly on the edge: counts as inside the polygon, unless it's the
// first edge and we're omitting it.
if (y === ycross) {
if (i === 1 && omitFirstEdge) return false;
return true;
}
if (y <= ycross && x !== xmini) crossings++;
}
}
// if we've gotten this far, odd crossings means inside, even is outside
return crossings % 2 === 1;
}
// detect if poly is degenerate
var degenerate = true;
var lastPt = pts[0];
for (i = 1; i < pts.length; i++) {
if (lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) {
degenerate = false;
break;
}
}
return {
xmin: xmin,
xmax: xmax,
ymin: ymin,
ymax: ymax,
pts: pts,
contains: isRect ? rectContains : contains,
isRect: isRect,
degenerate: degenerate
};
};
/**
* Test if a segment of a points array is bent or straight
*
* @param pts Array of [x, y] pairs
* @param start the index of the proposed start of the straight section
* @param end the index of the proposed end point
* @param tolerance the max distance off the line connecting start and end
* before the line counts as bent
* @returns boolean: true means this segment is bent, false means straight
*/
polygon.isSegmentBent = function isSegmentBent(pts, start, end, tolerance) {
var startPt = pts[start];
var segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]];
var segmentSquared = dot(segment, segment);
var segmentLen = Math.sqrt(segmentSquared);
var unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen];
var i;
var part;
var partParallel;
for (i = start + 1; i < end; i++) {
part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]];
partParallel = dot(part, segment);
if (partParallel < 0 || partParallel > segmentSquared || Math.abs(dot(part, unitPerp)) > tolerance) return true;
}
return false;
};
/**
* Make a filtering polygon, to minimize the number of segments
*
* @param pts Array of [x, y] pairs (must start with at least 1 pair)
* @param tolerance the maximum deviation from straight allowed for
* removing points to simplify the polygon
*
* @returns Object {addPt, raw, filtered}
* addPt is a function(pt: [x, y] pair) to add a raw point and
* continue filtering
* raw is all the input points
* filtered is the resulting filtered Array of [x, y] pairs
*/
polygon.filter = function filter(pts, tolerance) {
var ptsFiltered = [pts[0]];
var doneRawIndex = 0;
var doneFilteredIndex = 0;
function addPt(pt) {
pts.push(pt);
var prevFilterLen = ptsFiltered.length;
var iLast = doneRawIndex;
ptsFiltered.splice(doneFilteredIndex + 1);
for (var i = iLast + 1; i < pts.length; i++) {
if (i === pts.length - 1 || polygon.isSegmentBent(pts, iLast, i + 1, tolerance)) {
ptsFiltered.push(pts[i]);
if (ptsFiltered.length < prevFilterLen - 2) {
doneRawIndex = i;
doneFilteredIndex = ptsFiltered.length - 1;
}
iLast = i;
}
}
}
if (pts.length > 1) {
var lastPt = pts.pop();
addPt(lastPt);
}
return {
addPt: addPt,
raw: pts,
filtered: ptsFiltered
};
};
/***/ }),
/***/ 5048:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var showNoWebGlMsg = __webpack_require__(16576);
// Note that this module should be ONLY required into
// files corresponding to regl trace modules
// so that bundles with non-regl only don't include
// regl and all its bytes.
var createRegl = __webpack_require__(28624);
/**
* Idempotent version of createRegl. Create regl instances
* in the correct canvases with the correct attributes and
* options
*
* @param {DOM node or object} gd : graph div object
* @param {array} extensions : list of extension to pass to createRegl
*
* @return {boolean} true if all createRegl calls succeeded, false otherwise
*/
module.exports = function prepareRegl(gd, extensions, reglPrecompiled) {
var fullLayout = gd._fullLayout;
var success = true;
fullLayout._glcanvas.each(function (d) {
if (d.regl) {
d.regl.preloadCachedCode(reglPrecompiled);
return;
}
// only parcoords needs pick layer
if (d.pick && !fullLayout._has('parcoords')) return;
try {
d.regl = createRegl({
canvas: this,
attributes: {
antialias: !d.pick,
preserveDrawingBuffer: true
},
pixelRatio: gd._context.plotGlPixelRatio || __webpack_require__.g.devicePixelRatio,
extensions: extensions || [],
cachedCode: reglPrecompiled || {}
});
} catch (e) {
success = false;
}
if (!d.regl) success = false;
if (success) {
this.addEventListener('webglcontextlost', function (event) {
if (gd && gd.emit) {
gd.emit('plotly_webglcontextlost', {
event: event,
layer: d.key
});
}
}, false);
}
});
if (!success) {
showNoWebGlMsg({
container: fullLayout._glcontainer.node()
});
}
return success;
};
/***/ }),
/***/ 34296:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var isMobileOrTablet = __webpack_require__(25928);
module.exports = function preserveDrawingBuffer(opts) {
var ua;
if (opts && opts.hasOwnProperty('userAgent')) {
ua = opts.userAgent;
} else {
ua = getUserAgent();
}
if (typeof ua !== 'string') return true;
var enable = isMobileOrTablet({
ua: {
headers: {
'user-agent': ua
}
},
tablet: true,
featureDetect: false
});
if (!enable) {
var allParts = ua.split(' ');
for (var i = 1; i < allParts.length; i++) {
var part = allParts[i];
if (part.indexOf('Safari') !== -1) {
// find Safari version
for (var k = i - 1; k > -1; k--) {
var prevPart = allParts[k];
if (prevPart.substr(0, 8) === 'Version/') {
var v = prevPart.substr(8).split('.')[0];
if (isNumeric(v)) v = +v;
if (v >= 13) return true;
}
}
}
}
}
return enable;
};
function getUserAgent() {
// similar to https://github.com/juliangruber/is-mobile/blob/91ca39ccdd4cfc5edfb5391e2515b923a730fbea/index.js#L14-L17
var ua;
if (typeof navigator !== 'undefined') {
ua = navigator.userAgent;
}
if (ua && ua.headers && typeof ua.headers['user-agent'] === 'string') {
ua = ua.headers['user-agent'];
}
return ua;
}
/***/ }),
/***/ 52416:
/***/ (function(module) {
"use strict";
/**
* Push array with unique items
*
* Ignores falsy items, except 0 so we can use it to construct arrays of indices.
*
* @param {array} array
* array to be filled
* @param {any} item
* item to be or not to be inserted
* @return {array}
* ref to array (now possibly containing one more item)
*
*/
module.exports = function pushUnique(array, item) {
if (item instanceof RegExp) {
var itemStr = item.toString();
for (var i = 0; i < array.length; i++) {
if (array[i] instanceof RegExp && array[i].toString() === itemStr) {
return array;
}
}
array.push(item);
} else if ((item || item === 0) && array.indexOf(item) === -1) array.push(item);
return array;
};
/***/ }),
/***/ 94552:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var dfltConfig = (__webpack_require__(20556).dfltConfig);
/**
* Copy arg array *without* removing `undefined` values from objects.
*
* @param gd
* @param args
* @returns {Array}
*/
function copyArgArray(gd, args) {
var copy = [];
var arg;
for (var i = 0; i < args.length; i++) {
arg = args[i];
if (arg === gd) copy[i] = arg;else if (typeof arg === 'object') {
copy[i] = Array.isArray(arg) ? Lib.extendDeep([], arg) : Lib.extendDeepAll({}, arg);
} else copy[i] = arg;
}
return copy;
}
// -----------------------------------------------------
// Undo/Redo queue for plots
// -----------------------------------------------------
var queue = {};
// TODO: disable/enable undo and redo buttons appropriately
/**
* Add an item to the undoQueue for a graphDiv
*
* @param gd
* @param undoFunc Function undo this operation
* @param undoArgs Args to supply undoFunc with
* @param redoFunc Function to redo this operation
* @param redoArgs Args to supply redoFunc with
*/
queue.add = function (gd, undoFunc, undoArgs, redoFunc, redoArgs) {
var queueObj, queueIndex;
// make sure we have the queue and our position in it
gd.undoQueue = gd.undoQueue || {
index: 0,
queue: [],
sequence: false
};
queueIndex = gd.undoQueue.index;
// if we're already playing an undo or redo, or if this is an auto operation
// (like pane resize... any others?) then we don't save this to the undo queue
if (gd.autoplay) {
if (!gd.undoQueue.inSequence) gd.autoplay = false;
return;
}
// if we're not in a sequence or are just starting, we need a new queue item
if (!gd.undoQueue.sequence || gd.undoQueue.beginSequence) {
queueObj = {
undo: {
calls: [],
args: []
},
redo: {
calls: [],
args: []
}
};
gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj);
gd.undoQueue.index += 1;
} else {
queueObj = gd.undoQueue.queue[queueIndex - 1];
}
gd.undoQueue.beginSequence = false;
// we unshift to handle calls for undo in a forward for loop later
if (queueObj) {
queueObj.undo.calls.unshift(undoFunc);
queueObj.undo.args.unshift(undoArgs);
queueObj.redo.calls.push(redoFunc);
queueObj.redo.args.push(redoArgs);
}
if (gd.undoQueue.queue.length > dfltConfig.queueLength) {
gd.undoQueue.queue.shift();
gd.undoQueue.index--;
}
};
/**
* Begin a sequence of undoQueue changes
*
* @param gd
*/
queue.startSequence = function (gd) {
gd.undoQueue = gd.undoQueue || {
index: 0,
queue: [],
sequence: false
};
gd.undoQueue.sequence = true;
gd.undoQueue.beginSequence = true;
};
/**
* Stop a sequence of undoQueue changes
*
* Call this *after* you're sure your undo chain has ended
*
* @param gd
*/
queue.stopSequence = function (gd) {
gd.undoQueue = gd.undoQueue || {
index: 0,
queue: [],
sequence: false
};
gd.undoQueue.sequence = false;
gd.undoQueue.beginSequence = false;
};
/**
* Move one step back in the undo queue, and undo the object there.
*
* @param gd
*/
queue.undo = function undo(gd) {
var queueObj, i;
if (gd.undoQueue === undefined || isNaN(gd.undoQueue.index) || gd.undoQueue.index <= 0) {
return;
}
// index is pointing to next *forward* queueObj, point to the one we're undoing
gd.undoQueue.index--;
// get the queueObj for instructions on how to undo
queueObj = gd.undoQueue.queue[gd.undoQueue.index];
// this sequence keeps things from adding to the queue during undo/redo
gd.undoQueue.inSequence = true;
for (i = 0; i < queueObj.undo.calls.length; i++) {
queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]);
}
gd.undoQueue.inSequence = false;
gd.autoplay = false;
};
/**
* Redo the current object in the undo, then move forward in the queue.
*
* @param gd
*/
queue.redo = function redo(gd) {
var queueObj, i;
if (gd.undoQueue === undefined || isNaN(gd.undoQueue.index) || gd.undoQueue.index >= gd.undoQueue.queue.length) {
return;
}
// get the queueObj for instructions on how to undo
queueObj = gd.undoQueue.queue[gd.undoQueue.index];
// this sequence keeps things from adding to the queue during undo/redo
gd.undoQueue.inSequence = true;
for (i = 0; i < queueObj.redo.calls.length; i++) {
queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]);
}
gd.undoQueue.inSequence = false;
gd.autoplay = false;
// index is pointing to the thing we just redid, move it
gd.undoQueue.index++;
};
/**
* Called by undo/redo to make the actual changes.
*
* Not meant to be called publically, but included for mocking out in tests.
*
* @param gd
* @param func
* @param args
*/
queue.plotDo = function (gd, func, args) {
gd.autoplay = true;
// this *won't* copy gd and it preserves `undefined` properties!
args = copyArgArray(gd, args);
// call the supplied function
func.apply(null, args);
};
module.exports = queue;
/***/ }),
/***/ 53756:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
/*
* make a regex for matching counter ids/names ie xaxis, xaxis2, xaxis10...
*
* @param {string} head: the head of the pattern, eg 'x' matches 'x', 'x2', 'x10' etc.
* 'xy' is a special case for cartesian subplots: it matches 'x2y3' etc
* @param {Optional(string)} tail: a fixed piece after the id
* eg counterRegex('scene', '.annotations') for scene2.annotations etc.
* @param {boolean} openEnded: if true, the string may continue past the match.
* @param {boolean} matchBeginning: if false, the string may start before the match.
*/
exports.counter = function (head, tail, openEnded, matchBeginning) {
var fullTail = (tail || '') + (openEnded ? '' : '$');
var startWithPrefix = matchBeginning === false ? '' : '^';
if (head === 'xy') {
return new RegExp(startWithPrefix + 'x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail);
}
return new RegExp(startWithPrefix + head + '([2-9]|[1-9][0-9]+)?' + fullTail);
};
/***/ }),
/***/ 23193:
/***/ (function(module) {
"use strict";
// ASCEND: chop off the last nesting level - either [] or . - to ascend
// the attribute tree. the remaining attrString is in match[1]
var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/;
// SIMPLEATTR: is this an un-nested attribute? (no dots or brackets)
var SIMPLEATTR = /^[^\.\[\]]+$/;
/*
* calculate a relative attribute string, similar to a relative path
*
* @param {string} baseAttr:
* an attribute string, such as 'annotations[3].x'. The "current location"
* is the attribute string minus the last component ('annotations[3]')
* @param {string} relativeAttr:
* a route to the desired attribute string, using '^' to ascend
*
* @return {string} attrString:
* for example:
* relativeAttr('annotations[3].x', 'y') = 'annotations[3].y'
* relativeAttr('annotations[3].x', '^[2].z') = 'annotations[2].z'
* relativeAttr('annotations[3].x', '^^margin') = 'margin'
* relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r'
*/
module.exports = function (baseAttr, relativeAttr) {
while (relativeAttr) {
var match = baseAttr.match(ASCEND);
if (match) baseAttr = match[1];else if (baseAttr.match(SIMPLEATTR)) baseAttr = '';else throw new Error('bad relativeAttr call:' + [baseAttr, relativeAttr]);
if (relativeAttr.charAt(0) === '^') relativeAttr = relativeAttr.slice(1);else break;
}
if (baseAttr && relativeAttr.charAt(0) !== '[') {
return baseAttr + '.' + relativeAttr;
}
return baseAttr + relativeAttr;
};
/***/ }),
/***/ 51528:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isArrayOrTypedArray = (__webpack_require__(38116).isArrayOrTypedArray);
var isPlainObject = __webpack_require__(63620);
/**
* Relink private _keys and keys with a function value from one container
* to the new container.
* Relink means copying if object is pass-by-value and adding a reference
* if object is pass-by-ref.
* This prevents deepCopying massive structures like a webgl context.
*/
module.exports = function relinkPrivateKeys(toContainer, fromContainer) {
for (var k in fromContainer) {
var fromVal = fromContainer[k];
var toVal = toContainer[k];
if (toVal === fromVal) continue;
if (k.charAt(0) === '_' || typeof fromVal === 'function') {
// if it already exists at this point, it's something
// that we recreate each time around, so ignore it
if (k in toContainer) continue;
toContainer[k] = fromVal;
} else if (isArrayOrTypedArray(fromVal) && isArrayOrTypedArray(toVal) && isPlainObject(fromVal[0])) {
// filter out data_array items that can contain user objects
// most of the time the toVal === fromVal check will catch these early
// but if the user makes new ones we also don't want to recurse in.
if (k === 'customdata' || k === 'ids') continue;
// recurse into arrays containers
var minLen = Math.min(fromVal.length, toVal.length);
for (var j = 0; j < minLen; j++) {
if (toVal[j] !== fromVal[j] && isPlainObject(fromVal[j]) && isPlainObject(toVal[j])) {
relinkPrivateKeys(toVal[j], fromVal[j]);
}
}
} else if (isPlainObject(fromVal) && isPlainObject(toVal)) {
// recurse into objects, but only if they still exist
relinkPrivateKeys(toVal, fromVal);
if (!Object.keys(toVal).length) delete toContainer[k];
}
}
};
/***/ }),
/***/ 14952:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var loggers = __webpack_require__(24248);
var identity = __webpack_require__(35536);
var BADNUM = (__webpack_require__(39032).BADNUM);
// don't trust floating point equality - fraction of bin size to call
// "on the line" and ensure that they go the right way specified by
// linelow
var roundingError = 1e-9;
/**
* findBin - find the bin for val - note that it can return outside the
* bin range any pos. or neg. integer for linear bins, or -1 or
* bins.length-1 for explicit.
* bins is either an object {start,size,end} or an array length #bins+1
* bins can be either increasing or decreasing but must be monotonic
* for linear bins, we can just calculate. For listed bins, run a binary
* search linelow (truthy) says the bin boundary should be attributed to
* the lower bin rather than the default upper bin
*/
exports.findBin = function (val, bins, linelow) {
if (isNumeric(bins.start)) {
return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : Math.floor((val - bins.start) / bins.size + roundingError);
} else {
var n1 = 0;
var n2 = bins.length;
var c = 0;
var binSize = n2 > 1 ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1;
var n, test;
if (binSize >= 0) {
test = linelow ? lessThan : lessOrEqual;
} else {
test = linelow ? greaterOrEqual : greaterThan;
}
val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1);
// c is just to avoid infinite loops if there's an error
while (n1 < n2 && c++ < 100) {
n = Math.floor((n1 + n2) / 2);
if (test(bins[n], val)) n1 = n + 1;else n2 = n;
}
if (c > 90) loggers.log('Long binary search...');
return n1 - 1;
}
};
function lessThan(a, b) {
return a < b;
}
function lessOrEqual(a, b) {
return a <= b;
}
function greaterThan(a, b) {
return a > b;
}
function greaterOrEqual(a, b) {
return a >= b;
}
exports.sorterAsc = function (a, b) {
return a - b;
};
exports.sorterDes = function (a, b) {
return b - a;
};
/**
* find distinct values in an array, lumping together ones that appear to
* just be off by a rounding error
* return the distinct values and the minimum difference between any two
*/
exports.distinctVals = function (valsIn) {
var vals = valsIn.slice(); // otherwise we sort the original array...
vals.sort(exports.sorterAsc); // undefined listed in the end - also works on IE11
var last;
for (last = vals.length - 1; last > -1; last--) {
if (vals[last] !== BADNUM) break;
}
var minDiff = vals[last] - vals[0] || 1;
var errDiff = minDiff / (last || 1) / 10000;
var newVals = [];
var preV;
for (var i = 0; i <= last; i++) {
var v = vals[i];
// make sure values aren't just off by a rounding error
var diff = v - preV;
if (preV === undefined) {
newVals.push(v);
preV = v;
} else if (diff > errDiff) {
minDiff = Math.min(minDiff, diff);
newVals.push(v);
preV = v;
}
}
return {
vals: newVals,
minDiff: minDiff
};
};
/**
* return the smallest element from (sorted) array arrayIn that's bigger than val,
* or (reverse) the largest element smaller than val
* used to find the best tick given the minimum (non-rounded) tick
* particularly useful for date/time where things are not powers of 10
* binary search is probably overkill here...
*/
exports.roundUp = function (val, arrayIn, reverse) {
var low = 0;
var high = arrayIn.length - 1;
var mid;
var c = 0;
var dlow = reverse ? 0 : 1;
var dhigh = reverse ? 1 : 0;
var rounded = reverse ? Math.ceil : Math.floor;
// c is just to avoid infinite loops if there's an error
while (low < high && c++ < 100) {
mid = rounded((low + high) / 2);
if (arrayIn[mid] <= val) low = mid + dlow;else high = mid - dhigh;
}
return arrayIn[low];
};
/**
* Tweak to Array.sort(sortFn) that improves performance for pre-sorted arrays
*
* Note that newer browsers (such as Chrome v70+) are starting to pick up
* on pre-sorted arrays which may render the following optimization unnecessary
* in the future.
*
* Motivation: sometimes we need to sort arrays but the input is likely to
* already be sorted. Browsers don't seem to pick up on pre-sorted arrays,
* and in fact Chrome is actually *slower* sorting pre-sorted arrays than purely
* random arrays. FF is at least faster if the array is pre-sorted, but still
* not as fast as it could be.
* Here's how this plays out sorting a length-1e6 array:
*
* Calls to Sort FN | Chrome bare | FF bare | Chrome tweak | FF tweak
* | v68.0 Mac | v61.0 Mac| |
* ------------------+---------------+-----------+----------------+------------
* ordered | 30.4e6 | 10.1e6 | 1e6 | 1e6
* reversed | 29.4e6 | 9.9e6 | 1e6 + reverse | 1e6 + reverse
* random | ~21e6 | ~18.7e6 | ~21e6 | ~18.7e6
*
* So this is a substantial win for pre-sorted (ordered or exactly reversed)
* arrays. Including this wrapper on an unsorted array adds a penalty that will
* in general be only a few calls to the sort function. The only case this
* penalty will be significant is if the array is mostly sorted but there are
* a few unsorted items near the end, but the penalty is still at most N calls
* out of (for N=1e6) ~20N total calls
*
* @param {Array} array: the array, to be sorted in place
* @param {function} sortFn: As in Array.sort, function(a, b) that puts
* item a before item b if the return is negative, a after b if positive,
* and no change if zero.
* @return {Array}: the original array, sorted in place.
*/
exports.sort = function (array, sortFn) {
var notOrdered = 0;
var notReversed = 0;
for (var i = 1; i < array.length; i++) {
var pairOrder = sortFn(array[i], array[i - 1]);
if (pairOrder < 0) notOrdered = 1;else if (pairOrder > 0) notReversed = 1;
if (notOrdered && notReversed) return array.sort(sortFn);
}
return notReversed ? array : array.reverse();
};
/**
* find index in array 'arr' that minimizes 'fn'
*
* @param {array} arr : array where to search
* @param {fn (optional)} fn : function to minimize,
* if not given, fn is the identity function
* @return {integer}
*/
exports.findIndexOfMin = function (arr, fn) {
fn = fn || identity;
var min = Infinity;
var ind;
for (var i = 0; i < arr.length; i++) {
var v = fn(arr[i]);
if (v < min) {
min = v;
ind = i;
}
}
return ind;
};
/***/ }),
/***/ 93972:
/***/ (function(module) {
"use strict";
// works with our CSS cursor classes (see css/_cursor.scss)
// to apply cursors to d3 single-element selections.
// omit cursor to revert to the default.
module.exports = function setCursor(el3, csr) {
(el3.attr('class') || '').split(' ').forEach(function (cls) {
if (cls.indexOf('cursor-') === 0) el3.classed(cls, false);
});
if (csr) el3.classed('cursor-' + csr, true);
};
/***/ }),
/***/ 16576:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var noop = function () {};
/**
* Prints a no webgl error message into the scene container
* @param {scene instance} scene
*
* Expects 'scene' to have property 'container'
*
*/
module.exports = function showNoWebGlMsg(scene) {
for (var prop in scene) {
if (typeof scene[prop] === 'function') scene[prop] = noop;
}
scene.destroy = function () {
scene.container.parentNode.removeChild(scene.container);
};
var div = document.createElement('div');
div.className = 'no-webgl';
div.style.cursor = 'pointer';
div.style.fontSize = '24px';
div.style.color = Color.defaults[0];
div.style.position = 'absolute';
div.style.left = div.style.top = '0px';
div.style.width = div.style.height = '100%';
div.style['background-color'] = Color.lightLine;
div.style['z-index'] = 30;
var p = document.createElement('p');
p.textContent = 'WebGL is not supported by your browser - visit https://get.webgl.org for more info';
p.style.position = 'relative';
p.style.top = '50%';
p.style.left = '50%';
p.style.height = '30%';
p.style.width = '50%';
p.style.margin = '-15% 0 0 -25%';
div.appendChild(p);
scene.container.appendChild(div);
scene.container.style.background = '#FFFFFF';
scene.container.onclick = function () {
window.open('https://get.webgl.org');
};
// return before setting up camera and onrender methods
return false;
};
/***/ }),
/***/ 95376:
/***/ (function(module) {
"use strict";
module.exports = function sortObjectKeys(obj) {
return Object.keys(obj).sort();
};
/***/ }),
/***/ 63084:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var isArrayOrTypedArray = (__webpack_require__(38116).isArrayOrTypedArray);
/**
* aggNums() returns the result of an aggregate function applied to an array of
* values, where non-numerical values have been tossed out.
*
* @param {function} f - aggregation function (e.g., Math.min)
* @param {Number} v - initial value (continuing from previous calls)
* if there's no continuing value, use null for selector-type
* functions (max,min), or 0 for summations
* @param {Array} a - array to aggregate (may be nested, we will recurse,
* but all elements must have the same dimension)
* @param {Number} len - maximum length of a to aggregate
* @return {Number} - result of f applied to a starting from v
*/
exports.aggNums = function (f, v, a, len) {
var i, b;
if (!len || len > a.length) len = a.length;
if (!isNumeric(v)) v = false;
if (isArrayOrTypedArray(a[0])) {
b = new Array(len);
for (i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
a = b;
}
for (i = 0; i < len; i++) {
if (!isNumeric(v)) v = a[i];else if (isNumeric(a[i])) v = f(+v, +a[i]);
}
return v;
};
/**
* mean & std dev functions using aggNums, so it handles non-numerics nicely
* even need to use aggNums instead of .length, to toss out non-numerics
*/
exports.len = function (data) {
return exports.aggNums(function (a) {
return a + 1;
}, 0, data);
};
exports.mean = function (data, len) {
if (!len) len = exports.len(data);
return exports.aggNums(function (a, b) {
return a + b;
}, 0, data) / len;
};
exports.geometricMean = function (data, len) {
if (!len) len = exports.len(data);
return Math.pow(exports.aggNums(function (a, b) {
return a * b;
}, 1, data), 1 / len);
};
exports.midRange = function (numArr) {
if (numArr === undefined || numArr.length === 0) return undefined;
return (exports.aggNums(Math.max, null, numArr) + exports.aggNums(Math.min, null, numArr)) / 2;
};
exports.variance = function (data, len, mean) {
if (!len) len = exports.len(data);
if (!isNumeric(mean)) mean = exports.mean(data, len);
return exports.aggNums(function (a, b) {
return a + Math.pow(b - mean, 2);
}, 0, data) / len;
};
exports.stdev = function (data, len, mean) {
return Math.sqrt(exports.variance(data, len, mean));
};
/**
* median of a finite set of numbers
* reference page: https://en.wikipedia.org/wiki/Median#Finite_set_of_numbers
**/
exports.median = function (data) {
var b = data.slice().sort();
return exports.interp(b, 0.5);
};
/**
* interp() computes a percentile (quantile) for a given distribution.
* We interpolate the distribution (to compute quantiles, we follow method #10 here:
* http://jse.amstat.org/v14n3/langford.html).
* Typically the index or rank (n * arr.length) may be non-integer.
* For reference: ends are clipped to the extreme values in the array;
* For box plots: index you get is half a point too high (see
* http://en.wikipedia.org/wiki/Percentile#Nearest_rank) but note that this definition
* indexes from 1 rather than 0, so we subtract 1/2 (instead of add).
*
* @param {Array} arr - This array contains the values that make up the distribution.
* @param {Number} n - Between 0 and 1, n = p/100 is such that we compute the p^th percentile.
* For example, the 50th percentile (or median) corresponds to n = 0.5
* @return {Number} - percentile
*/
exports.interp = function (arr, n) {
if (!isNumeric(n)) throw 'n should be a finite number';
n = n * arr.length - 0.5;
if (n < 0) return arr[0];
if (n > arr.length - 1) return arr[arr.length - 1];
var frac = n % 1;
return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
};
/***/ }),
/***/ 43080:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var rgba = __webpack_require__(72160);
function str2RgbaArray(color) {
if (!color) return [0, 0, 0, 1];
return rgba(color);
}
module.exports = str2RgbaArray;
/***/ }),
/***/ 9188:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(2264);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var _supportsPixelated = null;
/**
* Check browser support for pixelated image rendering
*
* @return {boolean}
*/
function supportsPixelatedImage() {
if (_supportsPixelated !== null) {
// only run the feature detection once
return _supportsPixelated;
}
_supportsPixelated = false;
// @see https://github.com/plotly/plotly.js/issues/6604
var unsupportedBrowser = Lib.isIE() || Lib.isSafari() || Lib.isIOS();
if (window.navigator.userAgent && !unsupportedBrowser) {
var declarations = Array.from(constants.CSS_DECLARATIONS).reverse();
var supports = window.CSS && window.CSS.supports || window.supportsCSS;
if (typeof supports === 'function') {
_supportsPixelated = declarations.some(function (d) {
return supports.apply(null, d);
});
} else {
var image3 = Drawing.tester.append('image').attr('style', constants.STYLE);
var cStyles = window.getComputedStyle(image3.node());
var imageRendering = cStyles.imageRendering;
_supportsPixelated = declarations.some(function (d) {
var value = d[1];
return imageRendering === value || imageRendering === value.toLowerCase();
});
image3.remove();
}
}
return _supportsPixelated;
}
module.exports = supportsPixelatedImage;
/***/ }),
/***/ 72736:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/* global MathJax:false */
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var xmlnsNamespaces = __webpack_require__(9616);
var LINE_SPACING = (__webpack_require__(84284).LINE_SPACING);
// text converter
var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/;
exports.convertToTspans = function (_context, gd, _callback) {
var str = _context.text();
// Until we get tex integrated more fully (so it can be used along with non-tex)
// allow some elements to prohibit it by attaching 'data-notex' to the original
var tex = !_context.attr('data-notex') && gd && gd._context.typesetMath && typeof MathJax !== 'undefined' && str.match(FIND_TEX);
var parent = d3.select(_context.node().parentNode);
if (parent.empty()) return;
var svgClass = _context.attr('class') ? _context.attr('class').split(' ')[0] : 'text';
svgClass += '-math';
parent.selectAll('svg.' + svgClass).remove();
parent.selectAll('g.' + svgClass + '-group').remove();
_context.style('display', null).attr({
// some callers use data-unformatted *from the element* in 'cancel'
// so we need it here even if we're going to turn it into math
// these two (plus style and text-anchor attributes) form the key we're
// going to use for Drawing.bBox
'data-unformatted': str,
'data-math': 'N'
});
function showText() {
if (!parent.empty()) {
svgClass = _context.attr('class') + '-math';
parent.select('svg.' + svgClass).remove();
}
_context.text('').style('white-space', 'pre');
var hasLink = buildSVGText(_context.node(), str);
if (hasLink) {
// at least in Chrome, pointer-events does not seem
// to be honored in children of elements
// so if we have an anchor, we have to make the
// whole element respond
_context.style('pointer-events', 'all');
}
exports.positionText(_context);
if (_callback) _callback.call(_context);
}
if (tex) {
(gd && gd._promises || []).push(new Promise(function (resolve) {
_context.style('display', 'none');
var fontSize = parseInt(_context.node().style.fontSize, 10);
var config = {
fontSize: fontSize
};
texToSVG(tex[2], config, function (_svgEl, _glyphDefs, _svgBBox) {
parent.selectAll('svg.' + svgClass).remove();
parent.selectAll('g.' + svgClass + '-group').remove();
var newSvg = _svgEl && _svgEl.select('svg');
if (!newSvg || !newSvg.node()) {
showText();
resolve();
return;
}
var mathjaxGroup = parent.append('g').classed(svgClass + '-group', true).attr({
'pointer-events': 'none',
'data-unformatted': str,
'data-math': 'Y'
});
mathjaxGroup.node().appendChild(newSvg.node());
// stitch the glyph defs
if (_glyphDefs && _glyphDefs.node()) {
newSvg.node().insertBefore(_glyphDefs.node().cloneNode(true), newSvg.node().firstChild);
}
var w0 = _svgBBox.width;
var h0 = _svgBBox.height;
newSvg.attr({
class: svgClass,
height: h0,
preserveAspectRatio: 'xMinYMin meet'
}).style({
overflow: 'visible',
'pointer-events': 'none'
});
var fill = _context.node().style.fill || 'black';
var g = newSvg.select('g');
g.attr({
fill: fill,
stroke: fill
});
var bb = g.node().getBoundingClientRect();
var w = bb.width;
var h = bb.height;
if (w > w0 || h > h0) {
// this happen in firefox v82+ | see https://bugzilla.mozilla.org/show_bug.cgi?id=1709251 addressed
// temporary fix:
newSvg.style('overflow', 'hidden');
bb = newSvg.node().getBoundingClientRect();
w = bb.width;
h = bb.height;
}
var x = +_context.attr('x');
var y = +_context.attr('y');
// font baseline is about 1/4 fontSize below centerline
var textHeight = fontSize || _context.node().getBoundingClientRect().height;
var dy = -textHeight / 4;
if (svgClass[0] === 'y') {
mathjaxGroup.attr({
transform: 'rotate(' + [-90, x, y] + ')' + strTranslate(-w / 2, dy - h / 2)
});
} else if (svgClass[0] === 'l') {
y = dy - h / 2;
} else if (svgClass[0] === 'a' && svgClass.indexOf('atitle') !== 0) {
x = 0;
y = dy;
} else {
var anchor = _context.attr('text-anchor');
x = x - w * (anchor === 'middle' ? 0.5 : anchor === 'end' ? 1 : 0);
y = y + dy - h / 2;
}
newSvg.attr({
x: x,
y: y
});
if (_callback) _callback.call(_context, mathjaxGroup);
resolve(mathjaxGroup);
});
}));
} else showText();
return _context;
};
// MathJax
var LT_MATCH = /(<|<|<)/g;
var GT_MATCH = /(>|>|>)/g;
function cleanEscapesForTex(s) {
return s.replace(LT_MATCH, '\\lt ').replace(GT_MATCH, '\\gt ');
}
var inlineMath = [['$', '$'], ['\\(', '\\)']];
function texToSVG(_texString, _config, _callback) {
var MathJaxVersion = parseInt((MathJax.version || '').split('.')[0]);
if (MathJaxVersion !== 2 && MathJaxVersion !== 3) {
Lib.warn('No MathJax version:', MathJax.version);
return;
}
var originalRenderer, originalConfig, originalProcessSectionDelay, tmpDiv;
var setConfig2 = function () {
originalConfig = Lib.extendDeepAll({}, MathJax.Hub.config);
originalProcessSectionDelay = MathJax.Hub.processSectionDelay;
if (MathJax.Hub.processSectionDelay !== undefined) {
// MathJax 2.5+ but not 3+
MathJax.Hub.processSectionDelay = 0;
}
return MathJax.Hub.Config({
messageStyle: 'none',
tex2jax: {
inlineMath: inlineMath
},
displayAlign: 'left'
});
};
var setConfig3 = function () {
originalConfig = Lib.extendDeepAll({}, MathJax.config);
if (!MathJax.config.tex) {
MathJax.config.tex = {};
}
MathJax.config.tex.inlineMath = inlineMath;
};
var setRenderer2 = function () {
originalRenderer = MathJax.Hub.config.menuSettings.renderer;
if (originalRenderer !== 'SVG') {
return MathJax.Hub.setRenderer('SVG');
}
};
var setRenderer3 = function () {
originalRenderer = MathJax.config.startup.output;
if (originalRenderer !== 'svg') {
MathJax.config.startup.output = 'svg';
}
};
var initiateMathJax = function () {
var randomID = 'math-output-' + Lib.randstr({}, 64);
tmpDiv = d3.select('body').append('div').attr({
id: randomID
}).style({
visibility: 'hidden',
position: 'absolute',
'font-size': _config.fontSize + 'px'
}).text(cleanEscapesForTex(_texString));
var tmpNode = tmpDiv.node();
return MathJaxVersion === 2 ? MathJax.Hub.Typeset(tmpNode) : MathJax.typeset([tmpNode]);
};
var finalizeMathJax = function () {
var sel = tmpDiv.select(MathJaxVersion === 2 ? '.MathJax_SVG' : '.MathJax');
var node = !sel.empty() && tmpDiv.select('svg').node();
if (!node) {
Lib.log('There was an error in the tex syntax.', _texString);
_callback();
} else {
var nodeBBox = node.getBoundingClientRect();
var glyphDefs;
if (MathJaxVersion === 2) {
glyphDefs = d3.select('body').select('#MathJax_SVG_glyphs');
} else {
glyphDefs = sel.select('defs');
}
_callback(sel, glyphDefs, nodeBBox);
}
tmpDiv.remove();
};
var resetRenderer2 = function () {
if (originalRenderer !== 'SVG') {
return MathJax.Hub.setRenderer(originalRenderer);
}
};
var resetRenderer3 = function () {
if (originalRenderer !== 'svg') {
MathJax.config.startup.output = originalRenderer;
}
};
var resetConfig2 = function () {
if (originalProcessSectionDelay !== undefined) {
MathJax.Hub.processSectionDelay = originalProcessSectionDelay;
}
return MathJax.Hub.Config(originalConfig);
};
var resetConfig3 = function () {
MathJax.config = originalConfig;
};
if (MathJaxVersion === 2) {
MathJax.Hub.Queue(setConfig2, setRenderer2, initiateMathJax, finalizeMathJax, resetRenderer2, resetConfig2);
} else if (MathJaxVersion === 3) {
setConfig3();
setRenderer3();
MathJax.startup.defaultReady();
MathJax.startup.promise.then(function () {
initiateMathJax();
finalizeMathJax();
resetRenderer3();
resetConfig3();
});
}
}
var TAG_STYLES = {
// would like to use baseline-shift for sub/sup but FF doesn't support it
// so we need to use dy along with the uber hacky shift-back-to
// baseline below
sup: 'font-size:70%',
sub: 'font-size:70%',
s: 'text-decoration:line-through',
u: 'text-decoration:underline',
b: 'font-weight:bold',
i: 'font-style:italic',
a: 'cursor:pointer',
span: '',
em: 'font-style:italic;font-weight:bold'
};
// baseline shifts for sub and sup
var SHIFT_DY = {
sub: '0.3em',
sup: '-0.6em'
};
// reset baseline by adding a tspan (empty except for a zero-width space)
// with dy of -70% * SHIFT_DY (because font-size=70%)
var RESET_DY = {
sub: '-0.21em',
sup: '0.42em'
};
var ZERO_WIDTH_SPACE = '\u200b';
/*
* Whitelist of protocols in user-supplied urls. Mostly we want to avoid javascript
* and related attack vectors. The empty items are there for IE, that in various
* versions treats relative paths as having different flavors of no protocol, while
* other browsers have these explicitly inherit the protocol of the page they're in.
*/
var PROTOCOLS = ['http:', 'https:', 'mailto:', '', undefined, ':'];
var NEWLINES = exports.NEWLINES = /(\r\n?|\n)/g;
var SPLIT_TAGS = /(<[^<>]*>)/;
var ONE_TAG = /<(\/?)([^ >]*)(\s+(.*))?>/i;
var BR_TAG = / /i;
exports.BR_TAG_ALL = / /gi;
/*
* style and href: pull them out of either single or double quotes. Also
* - target: (_blank|_self|_parent|_top|framename)
* note that you can't use target to get a popup but if you use popup,
* a `framename` will be passed along as the name of the popup window.
* per the spec, cannot contain whitespace.
* for backward compatibility we default to '_blank'
* - popup: a custom one for us to enable popup (new window) links. String
* for window.open -> strWindowFeatures, like 'menubar=yes,width=500,height=550'
* note that at least in Chrome, you need to give at least one property
* in this string or the page will open in a new tab anyway. We follow this
* convention and will not make a popup if this string is empty.
* per the spec, cannot contain whitespace.
*
* Because we hack in other attributes with style (sub & sup), drop any trailing
* semicolon in user-supplied styles so we can consistently append the tag-dependent style
*
* These are for tag attributes; Chrome anyway will convert entities in
* attribute values, but not in attribute names
* you can test this by for example:
* > p = document.createElement('p')
* > p.innerHTML = 'Hi '
* > p.innerHTML
* <- 'Hi '
*/
var STYLEMATCH = /(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i;
var HREFMATCH = /(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i;
var TARGETMATCH = /(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i;
var POPUPMATCH = /(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;
// dedicated matcher for these quoted regexes, that can return their results
// in two different places
function getQuotedMatch(_str, re) {
if (!_str) return null;
var match = _str.match(re);
var result = match && (match[3] || match[4]);
return result && convertEntities(result);
}
var COLORMATCH = /(^|;)\s*color:/;
/**
* Strip string of tags
*
* @param {string} _str : input string
* @param {object} opts :
* - len {number} max length of output string
* - allowedTags {array} list of pseudo-html tags to NOT strip
* @return {string}
*/
exports.plainText = function (_str, opts) {
opts = opts || {};
var len = opts.len !== undefined && opts.len !== -1 ? opts.len : Infinity;
var allowedTags = opts.allowedTags !== undefined ? opts.allowedTags : ['br'];
var ellipsis = '...';
var eLen = ellipsis.length;
var oldParts = _str.split(SPLIT_TAGS);
var newParts = [];
var prevTag = '';
var l = 0;
for (var i = 0; i < oldParts.length; i++) {
var p = oldParts[i];
var match = p.match(ONE_TAG);
var tagType = match && match[2].toLowerCase();
if (tagType) {
// N.B. tags do not count towards string length
if (allowedTags.indexOf(tagType) !== -1) {
newParts.push(p);
prevTag = tagType;
}
} else {
var pLen = p.length;
if (l + pLen < len) {
newParts.push(p);
l += pLen;
} else if (l < len) {
var pLen2 = len - l;
if (prevTag && (prevTag !== 'br' || pLen2 <= eLen || pLen <= eLen)) {
newParts.pop();
}
if (len > eLen) {
newParts.push(p.substr(0, pLen2 - eLen) + ellipsis);
} else {
newParts.push(p.substr(0, pLen2));
}
break;
}
prevTag = '';
}
}
return newParts.join('');
};
/*
* N.B. HTML entities are listed without the leading '&' and trailing ';'
* https://www.freeformatter.com/html-entities.html
*
* FWIW if we wanted to support the full set, it has 2261 entries:
* https://www.w3.org/TR/html5/entities.json
* though I notice that some of these are duplicates and/or are missing ";"
* eg: "&", "&", "&", and "&" all map to "&"
* We no longer need to include numeric entities here, these are now handled
* by String.fromCodePoint/fromCharCode
*
* Anyway the only ones that are really important to allow are the HTML special
* chars <, >, and &, because these ones can trigger special processing if not
* replaced by the corresponding entity.
*/
var entityToUnicode = {
mu: 'μ',
amp: '&',
lt: '<',
gt: '>',
nbsp: ' ',
times: '×',
plusmn: '±',
deg: '°'
};
// NOTE: in general entities can contain uppercase too (so [a-zA-Z]) but all the
// ones we support use only lowercase. If we ever change that, update the regex.
var ENTITY_MATCH = /&(#\d+|#x[\da-fA-F]+|[a-z]+);/g;
function convertEntities(_str) {
return _str.replace(ENTITY_MATCH, function (fullMatch, innerMatch) {
var outChar;
if (innerMatch.charAt(0) === '#') {
// cannot use String.fromCodePoint in IE
outChar = fromCodePoint(innerMatch.charAt(1) === 'x' ? parseInt(innerMatch.substr(2), 16) : parseInt(innerMatch.substr(1), 10));
} else outChar = entityToUnicode[innerMatch];
// as in regular HTML, if we didn't decode the entity just
// leave the raw text in place.
return outChar || fullMatch;
});
}
exports.convertEntities = convertEntities;
function fromCodePoint(code) {
// Don't allow overflow. In Chrome this turns into � but I feel like it's
// more useful to just not convert it at all.
if (code > 0x10FFFF) return;
var stringFromCodePoint = String.fromCodePoint;
if (stringFromCodePoint) return stringFromCodePoint(code);
// IE doesn't have String.fromCodePoint
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
var stringFromCharCode = String.fromCharCode;
if (code <= 0xFFFF) return stringFromCharCode(code);
return stringFromCharCode((code >> 10) + 0xD7C0, code % 0x400 + 0xDC00);
}
/*
* buildSVGText: convert our pseudo-html into SVG tspan elements, and attach these
* to containerNode
*
* @param {svg text element} containerNode: the node to insert this text into
* @param {string} str: the pseudo-html string to convert to svg
*
* @returns {bool}: does the result contain any links? We need to handle the text element
* somewhat differently if it does, so just keep track of this when it happens.
*/
function buildSVGText(containerNode, str) {
/*
* Normalize behavior between IE and others wrt newlines and whitespace:pre
* this combination makes IE barf https://github.com/plotly/plotly.js/issues/746
* Chrome and FF display \n, \r, or \r\n as a space in this mode.
* I feel like at some point we turned these into but currently we don't so
* I'm just going to cement what we do now in Chrome and FF
*/
str = str.replace(NEWLINES, ' ');
var hasLink = false;
// as we're building the text, keep track of what elements we're nested inside
// nodeStack will be an array of {node, type, style, href, target, popup}
// where only type: 'a' gets the last 3 and node is only added when it's created
var nodeStack = [];
var currentNode;
var currentLine = -1;
function newLine() {
currentLine++;
var lineNode = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
d3.select(lineNode).attr({
class: 'line',
dy: currentLine * LINE_SPACING + 'em'
});
containerNode.appendChild(lineNode);
currentNode = lineNode;
var oldNodeStack = nodeStack;
nodeStack = [{
node: lineNode
}];
if (oldNodeStack.length > 1) {
for (var i = 1; i < oldNodeStack.length; i++) {
enterNode(oldNodeStack[i]);
}
}
}
function enterNode(nodeSpec) {
var type = nodeSpec.type;
var nodeAttrs = {};
var nodeType;
if (type === 'a') {
nodeType = 'a';
var target = nodeSpec.target;
var href = nodeSpec.href;
var popup = nodeSpec.popup;
if (href) {
nodeAttrs = {
'xlink:xlink:show': target === '_blank' || target.charAt(0) !== '_' ? 'new' : 'replace',
target: target,
'xlink:xlink:href': href
};
if (popup) {
// security: href and target are not inserted as code but
// as attributes. popup is, but limited to /[A-Za-z0-9_=,]/
nodeAttrs.onclick = 'window.open(this.href.baseVal,this.target.baseVal,"' + popup + '");return false;';
}
}
} else nodeType = 'tspan';
if (nodeSpec.style) nodeAttrs.style = nodeSpec.style;
var newNode = document.createElementNS(xmlnsNamespaces.svg, nodeType);
if (type === 'sup' || type === 'sub') {
addTextNode(currentNode, ZERO_WIDTH_SPACE);
currentNode.appendChild(newNode);
var resetter = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
addTextNode(resetter, ZERO_WIDTH_SPACE);
d3.select(resetter).attr('dy', RESET_DY[type]);
nodeAttrs.dy = SHIFT_DY[type];
currentNode.appendChild(newNode);
currentNode.appendChild(resetter);
} else {
currentNode.appendChild(newNode);
}
d3.select(newNode).attr(nodeAttrs);
currentNode = nodeSpec.node = newNode;
nodeStack.push(nodeSpec);
}
function addTextNode(node, text) {
node.appendChild(document.createTextNode(text));
}
function exitNode(type) {
// A bare closing tag can't close the root node. If we encounter this it
// means there's an extra closing tag that can just be ignored:
if (nodeStack.length === 1) {
Lib.log('Ignoring unexpected end tag ' + type + '>.', str);
return;
}
var innerNode = nodeStack.pop();
if (type !== innerNode.type) {
Lib.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str);
}
currentNode = nodeStack[nodeStack.length - 1].node;
}
var hasLines = BR_TAG.test(str);
if (hasLines) newLine();else {
currentNode = containerNode;
nodeStack = [{
node: containerNode
}];
}
var parts = str.split(SPLIT_TAGS);
for (var i = 0; i < parts.length; i++) {
var parti = parts[i];
var match = parti.match(ONE_TAG);
var tagType = match && match[2].toLowerCase();
var tagStyle = TAG_STYLES[tagType];
if (tagType === 'br') {
newLine();
} else if (tagStyle === undefined) {
addTextNode(currentNode, convertEntities(parti));
} else {
// tag - open or close
if (match[1]) {
exitNode(tagType);
} else {
var extra = match[4];
var nodeSpec = {
type: tagType
};
// now add style, from both the tag name and any extra css
// Most of the svg css that users will care about is just like html,
// but font color is different (uses fill). Let our users ignore this.
var css = getQuotedMatch(extra, STYLEMATCH);
if (css) {
css = css.replace(COLORMATCH, '$1 fill:');
if (tagStyle) css += ';' + tagStyle;
} else if (tagStyle) css = tagStyle;
if (css) nodeSpec.style = css;
if (tagType === 'a') {
hasLink = true;
var href = getQuotedMatch(extra, HREFMATCH);
if (href) {
var safeHref = sanitizeHref(href);
if (safeHref) {
nodeSpec.href = safeHref;
nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || '_blank';
nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH);
}
}
}
enterNode(nodeSpec);
}
}
}
return hasLink;
}
function sanitizeHref(href) {
var decodedHref = encodeURI(decodeURI(href));
var dummyAnchor1 = document.createElement('a');
var dummyAnchor2 = document.createElement('a');
dummyAnchor1.href = href;
dummyAnchor2.href = decodedHref;
var p1 = dummyAnchor1.protocol;
var p2 = dummyAnchor2.protocol;
// check safe protocols
if (PROTOCOLS.indexOf(p1) !== -1 && PROTOCOLS.indexOf(p2) !== -1) {
return decodedHref;
} else {
return '';
}
}
/*
* sanitizeHTML: port of buildSVGText aimed at providing a clean subset of HTML
* @param {string} str: the html string to clean
* @returns {string}: a cleaned and normalized version of the input,
* supporting only a small subset of html
*/
exports.sanitizeHTML = function sanitizeHTML(str) {
str = str.replace(NEWLINES, ' ');
var rootNode = document.createElement('p');
var currentNode = rootNode;
var nodeStack = [];
var parts = str.split(SPLIT_TAGS);
for (var i = 0; i < parts.length; i++) {
var parti = parts[i];
var match = parti.match(ONE_TAG);
var tagType = match && match[2].toLowerCase();
if (tagType in TAG_STYLES) {
if (match[1]) {
if (nodeStack.length) {
currentNode = nodeStack.pop();
}
} else {
var extra = match[4];
var css = getQuotedMatch(extra, STYLEMATCH);
var nodeAttrs = css ? {
style: css
} : {};
if (tagType === 'a') {
var href = getQuotedMatch(extra, HREFMATCH);
if (href) {
var safeHref = sanitizeHref(href);
if (safeHref) {
nodeAttrs.href = safeHref;
var target = getQuotedMatch(extra, TARGETMATCH);
if (target) {
nodeAttrs.target = target;
}
}
}
}
var newNode = document.createElement(tagType);
currentNode.appendChild(newNode);
d3.select(newNode).attr(nodeAttrs);
currentNode = newNode;
nodeStack.push(newNode);
}
} else {
currentNode.appendChild(document.createTextNode(convertEntities(parti)));
}
}
var key = 'innerHTML'; // i.e. to avoid pass test-syntax
return rootNode[key];
};
exports.lineCount = function lineCount(s) {
return s.selectAll('tspan.line').size() || 1;
};
exports.positionText = function positionText(s, x, y) {
return s.each(function () {
var text = d3.select(this);
function setOrGet(attr, val) {
if (val === undefined) {
val = text.attr(attr);
if (val === null) {
text.attr(attr, 0);
val = 0;
}
} else text.attr(attr, val);
return val;
}
var thisX = setOrGet('x', x);
var thisY = setOrGet('y', y);
if (this.nodeName === 'text') {
text.selectAll('tspan.line').attr({
x: thisX,
y: thisY
});
}
});
};
function alignHTMLWith(_base, container, options) {
var alignH = options.horizontalAlign;
var alignV = options.verticalAlign || 'top';
var bRect = _base.node().getBoundingClientRect();
var cRect = container.node().getBoundingClientRect();
var thisRect;
var getTop;
var getLeft;
if (alignV === 'bottom') {
getTop = function () {
return bRect.bottom - thisRect.height;
};
} else if (alignV === 'middle') {
getTop = function () {
return bRect.top + (bRect.height - thisRect.height) / 2;
};
} else {
// default: top
getTop = function () {
return bRect.top;
};
}
if (alignH === 'right') {
getLeft = function () {
return bRect.right - thisRect.width;
};
} else if (alignH === 'center') {
getLeft = function () {
return bRect.left + (bRect.width - thisRect.width) / 2;
};
} else {
// default: left
getLeft = function () {
return bRect.left;
};
}
return function () {
thisRect = this.node().getBoundingClientRect();
var x0 = getLeft() - cRect.left;
var y0 = getTop() - cRect.top;
var gd = options.gd || {};
if (options.gd) {
gd._fullLayout._calcInverseTransform(gd);
var transformedCoords = Lib.apply3DTransform(gd._fullLayout._invTransform)(x0, y0);
x0 = transformedCoords[0];
y0 = transformedCoords[1];
}
this.style({
top: y0 + 'px',
left: x0 + 'px',
'z-index': 1000
});
return this;
};
}
var onePx = '1px ';
exports.makeTextShadow = function (color) {
var x = onePx;
var y = onePx;
var b = onePx;
return x + y + b + color + ', ' + '-' + x + '-' + y + b + color + ', ' + x + '-' + y + b + color + ', ' + '-' + x + y + b + color;
};
/*
* Editable title
* @param {d3.selection} context: the element being edited. Normally text,
* but if it isn't, you should provide the styling options
* @param {object} options:
* @param {div} options.gd: graphDiv
* @param {d3.selection} options.delegate: item to bind events to if not this
* @param {boolean} options.immediate: start editing now (true) or on click (false, default)
* @param {string} options.fill: font color if not as shown
* @param {string} options.background: background color if not as shown
* @param {string} options.text: initial text, if not as shown
* @param {string} options.horizontalAlign: alignment of the edit box wrt. the bound element
* @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element
*/
exports.makeEditable = function (context, options) {
var gd = options.gd;
var _delegate = options.delegate;
var dispatch = d3.dispatch('edit', 'input', 'cancel');
var handlerElement = _delegate || context;
context.style({
'pointer-events': _delegate ? 'none' : 'all'
});
if (context.size() !== 1) throw new Error('boo');
function handleClick() {
appendEditable();
context.style({
opacity: 0
});
// also hide any mathjax svg
var svgClass = handlerElement.attr('class');
var mathjaxClass;
if (svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';else mathjaxClass = '[class*=-math-group]';
if (mathjaxClass) {
d3.select(context.node().parentNode).select(mathjaxClass).style({
opacity: 0
});
}
}
function selectElementContents(_el) {
var el = _el.node();
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
el.focus();
}
function appendEditable() {
var plotDiv = d3.select(gd);
var container = plotDiv.select('.svg-container');
var div = container.append('div');
var cStyle = context.node().style;
var fontSize = parseFloat(cStyle.fontSize || 12);
var initialText = options.text;
if (initialText === undefined) initialText = context.attr('data-unformatted');
div.classed('plugin-editable editable', true).style({
position: 'absolute',
'font-family': cStyle.fontFamily || 'Arial',
'font-size': fontSize,
color: options.fill || cStyle.fill || 'black',
opacity: 1,
'background-color': options.background || 'transparent',
outline: '#ffffff33 1px solid',
margin: [-fontSize / 8 + 1, 0, 0, -1].join('px ') + 'px',
padding: '0',
'box-sizing': 'border-box'
}).attr({
contenteditable: true
}).text(initialText).call(alignHTMLWith(context, container, options)).on('blur', function () {
gd._editing = false;
context.text(this.textContent).style({
opacity: 1
});
var svgClass = d3.select(this).attr('class');
var mathjaxClass;
if (svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';else mathjaxClass = '[class*=-math-group]';
if (mathjaxClass) {
d3.select(context.node().parentNode).select(mathjaxClass).style({
opacity: 0
});
}
var text = this.textContent;
d3.select(this).transition().duration(0).remove();
d3.select(document).on('mouseup', null);
dispatch.edit.call(context, text);
}).on('focus', function () {
var editDiv = this;
gd._editing = true;
d3.select(document).on('mouseup', function () {
if (d3.event.target === editDiv) return false;
if (document.activeElement === div.node()) div.node().blur();
});
}).on('keyup', function () {
if (d3.event.which === 27) {
gd._editing = false;
context.style({
opacity: 1
});
d3.select(this).style({
opacity: 0
}).on('blur', function () {
return false;
}).transition().remove();
dispatch.cancel.call(context, this.textContent);
} else {
dispatch.input.call(context, this.textContent);
d3.select(this).call(alignHTMLWith(context, container, options));
}
}).on('keydown', function () {
if (d3.event.which === 13) this.blur();
}).call(selectElementContents);
}
if (options.immediate) handleClick();else handlerElement.on('click', handleClick);
return d3.rebind(context, dispatch, 'on');
};
/***/ }),
/***/ 91200:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
var timerCache = {};
/**
* Throttle a callback. `callback` executes synchronously only if
* more than `minInterval` milliseconds have already elapsed since the latest
* call (if any). Otherwise we wait until `minInterval` is over and execute the
* last callback received while waiting.
* So the first and last events in a train are always executed (eventually)
* but some of the events in the middle can be dropped.
*
* @param {string} id: an identifier to mark events to throttle together
* @param {number} minInterval: minimum time, in milliseconds, between
* invocations of `callback`
* @param {function} callback: the function to throttle. `callback` itself
* should be a purely synchronous function.
*/
exports.throttle = function throttle(id, minInterval, callback) {
var cache = timerCache[id];
var now = Date.now();
if (!cache) {
/*
* Throw out old items before making a new one, to prevent the cache
* getting overgrown, for example from old plots that have been replaced.
* 1 minute age is arbitrary.
*/
for (var idi in timerCache) {
if (timerCache[idi].ts < now - 60000) {
delete timerCache[idi];
}
}
cache = timerCache[id] = {
ts: 0,
timer: null
};
}
_clearTimeout(cache);
function exec() {
callback();
cache.ts = Date.now();
if (cache.onDone) {
cache.onDone();
cache.onDone = null;
}
}
if (now > cache.ts + minInterval) {
exec();
return;
}
cache.timer = setTimeout(function () {
exec();
cache.timer = null;
}, minInterval);
};
exports.done = function (id) {
var cache = timerCache[id];
if (!cache || !cache.timer) return Promise.resolve();
return new Promise(function (resolve) {
var previousOnDone = cache.onDone;
cache.onDone = function onDone() {
if (previousOnDone) previousOnDone();
resolve();
cache.onDone = null;
};
});
};
/**
* Clear the throttle cache for one or all timers
* @param {optional string} id:
* if provided, clear just this timer
* if omitted, clear all timers (mainly useful for testing)
*/
exports.clear = function (id) {
if (id) {
_clearTimeout(timerCache[id]);
delete timerCache[id];
} else {
for (var idi in timerCache) exports.clear(idi);
}
};
function _clearTimeout(cache) {
if (cache && cache.timer !== null) {
clearTimeout(cache.timer);
cache.timer = null;
}
}
/***/ }),
/***/ 36896:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
/**
* convert a linear value into a logged value, folding negative numbers into
* the given range
*/
module.exports = function toLogRange(val, range) {
if (val > 0) return Math.log(val) / Math.LN10;
// move a negative value reference to a log axis - just put the
// result at the lowest range value on the plot (or if the range also went negative,
// one millionth of the top of the range)
var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10;
if (!isNumeric(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6;
return newVal;
};
/***/ }),
/***/ 59972:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var topojsonUtils = module.exports = {};
var locationmodeToLayer = (__webpack_require__(79552).locationmodeToLayer);
var topojsonFeature = (__webpack_require__(55712)/* .feature */ .NO);
topojsonUtils.getTopojsonName = function (geoLayout) {
return [geoLayout.scope.replace(/ /g, '-'), '_', geoLayout.resolution.toString(), 'm'].join('');
};
topojsonUtils.getTopojsonPath = function (topojsonURL, topojsonName) {
return topojsonURL + topojsonName + '.json';
};
topojsonUtils.getTopojsonFeatures = function (trace, topojson) {
var layer = locationmodeToLayer[trace.locationmode];
var obj = topojson.objects[layer];
return topojsonFeature(topojson, obj).features;
};
/***/ }),
/***/ 11680:
/***/ (function(module) {
"use strict";
module.exports = {
moduleType: 'locale',
name: 'en-US',
dictionary: {
'Click to enter Colorscale title': 'Click to enter Colorscale title'
},
format: {
date: '%m/%d/%Y'
}
};
/***/ }),
/***/ 6580:
/***/ (function(module) {
"use strict";
module.exports = {
moduleType: 'locale',
name: 'en',
dictionary: {
'Click to enter Colorscale title': 'Click to enter Colourscale title'
},
format: {
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'],
periods: ['AM', 'PM'],
dateTime: '%a %b %e %X %Y',
date: '%d/%m/%Y',
time: '%H:%M:%S',
decimal: '.',
thousands: ',',
grouping: [3],
currency: ['$', ''],
year: '%Y',
month: '%b %Y',
dayMonth: '%b %-d',
dayMonthYear: '%b %-d, %Y'
}
};
/***/ }),
/***/ 69820:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
/*
* containerArrayMatch: does this attribute string point into a
* layout container array?
*
* @param {String} astr: an attribute string, like *annotations[2].text*
*
* @returns {Object | false} Returns false if `astr` doesn't match a container
* array. If it does, returns:
* {array: {String}, index: {Number}, property: {String}}
* ie the attribute string for the array, the index within the array (or ''
* if the whole array) and the property within that (or '' if the whole array
* or the whole object)
*/
module.exports = function containerArrayMatch(astr) {
var rootContainers = Registry.layoutArrayContainers;
var regexpContainers = Registry.layoutArrayRegexes;
var rootPart = astr.split('[')[0];
var arrayStr;
var match;
// look for regexp matches first, because they may be nested inside root matches
// eg updatemenus[i].buttons is nested inside updatemenus
for (var i = 0; i < regexpContainers.length; i++) {
match = astr.match(regexpContainers[i]);
if (match && match.index === 0) {
arrayStr = match[0];
break;
}
}
// now look for root matches
if (!arrayStr) arrayStr = rootContainers[rootContainers.indexOf(rootPart)];
if (!arrayStr) return false;
var tail = astr.substr(arrayStr.length);
if (!tail) return {
array: arrayStr,
index: '',
property: ''
};
match = tail.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/);
if (!match) return false;
return {
array: arrayStr,
index: Number(match[1]),
property: match[3] || ''
};
};
/***/ }),
/***/ 67824:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var extendFlat = (__webpack_require__(92880).extendFlat);
var isPlainObject = __webpack_require__(63620);
var traceOpts = {
valType: 'flaglist',
extras: ['none'],
flags: ['calc', 'clearAxisTypes', 'plot', 'style', 'markerSize', 'colorbars']
};
var layoutOpts = {
valType: 'flaglist',
extras: ['none'],
flags: ['calc', 'plot', 'legend', 'ticks', 'axrange', 'layoutstyle', 'modebar', 'camera', 'arraydraw', 'colorbars']
};
// flags for inside restyle/relayout include a few extras
// that shouldn't be used in attributes, to deal with certain
// combinations and conditionals efficiently
var traceEditTypeFlags = traceOpts.flags.slice().concat(['fullReplot']);
var layoutEditTypeFlags = layoutOpts.flags.slice().concat('layoutReplot');
module.exports = {
traces: traceOpts,
layout: layoutOpts,
/*
* default (all false) edit flags for restyle (traces)
* creates a new object each call, so the caller can mutate freely
*/
traceFlags: function () {
return falseObj(traceEditTypeFlags);
},
/*
* default (all false) edit flags for relayout
* creates a new object each call, so the caller can mutate freely
*/
layoutFlags: function () {
return falseObj(layoutEditTypeFlags);
},
/*
* update `flags` with the `editType` values found in `attr`
*/
update: function (flags, attr) {
var editType = attr.editType;
if (editType && editType !== 'none') {
var editTypeParts = editType.split('+');
for (var i = 0; i < editTypeParts.length; i++) {
flags[editTypeParts[i]] = true;
}
}
},
overrideAll: overrideAll
};
function falseObj(keys) {
var out = {};
for (var i = 0; i < keys.length; i++) out[keys[i]] = false;
return out;
}
/**
* For attributes that are largely copied from elsewhere into a plot type that doesn't
* support partial redraws - overrides the editType field of all attributes in the object
*
* @param {object} attrs: the attributes to override. Will not be mutated.
* @param {string} editTypeOverride: the new editType to use
* @param {'nested'|'from-root'} overrideContainers:
* - 'nested' will override editType for nested containers but not the root.
* - 'from-root' will also override editType of the root container.
* Containers below the absolute top level (trace or layout root) DO need an
* editType even if they are not `valObject`s themselves (eg `scatter.marker`)
* to handle the case where you edit the whole container.
*
* @return {object} a new attributes object with `editType` modified as directed
*/
function overrideAll(attrs, editTypeOverride, overrideContainers) {
var out = extendFlat({}, attrs);
for (var key in out) {
var attr = out[key];
if (isPlainObject(attr)) {
out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key);
}
}
if (overrideContainers === 'from-root') out.editType = editTypeOverride;
return out;
}
function overrideOne(attr, editTypeOverride, overrideContainers, key) {
if (attr.valType) {
var out = extendFlat({}, attr);
out.editType = editTypeOverride;
if (Array.isArray(attr.items)) {
out.items = new Array(attr.items.length);
for (var i = 0; i < attr.items.length; i++) {
out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root');
}
}
return out;
} else {
// don't provide an editType for the _deprecated container
return overrideAll(attr, editTypeOverride, key.charAt(0) === '_' ? 'nested' : 'from-root');
}
}
/***/ }),
/***/ 93404:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var m4FromQuat = __webpack_require__(61784);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var Plots = __webpack_require__(7316);
var AxisIds = __webpack_require__(79811);
var Color = __webpack_require__(76308);
var cleanId = AxisIds.cleanId;
var getFromTrace = AxisIds.getFromTrace;
var traceIs = Registry.traceIs;
// clear the promise queue if one of them got rejected
exports.clearPromiseQueue = function (gd) {
if (Array.isArray(gd._promises) && gd._promises.length > 0) {
Lib.log('Clearing previous rejected promises from queue.');
}
gd._promises = [];
};
// make a few changes to the layout right away
// before it gets used for anything
// backward compatibility and cleanup of nonstandard options
exports.cleanLayout = function (layout) {
var i, j;
if (!layout) layout = {};
// cannot have (x|y)axis1, numbering goes axis, axis2, axis3...
if (layout.xaxis1) {
if (!layout.xaxis) layout.xaxis = layout.xaxis1;
delete layout.xaxis1;
}
if (layout.yaxis1) {
if (!layout.yaxis) layout.yaxis = layout.yaxis1;
delete layout.yaxis1;
}
if (layout.scene1) {
if (!layout.scene) layout.scene = layout.scene1;
delete layout.scene1;
}
var axisAttrRegex = (Plots.subplotsRegistry.cartesian || {}).attrRegex;
var polarAttrRegex = (Plots.subplotsRegistry.polar || {}).attrRegex;
var ternaryAttrRegex = (Plots.subplotsRegistry.ternary || {}).attrRegex;
var sceneAttrRegex = (Plots.subplotsRegistry.gl3d || {}).attrRegex;
var keys = Object.keys(layout);
for (i = 0; i < keys.length; i++) {
var key = keys[i];
if (axisAttrRegex && axisAttrRegex.test(key)) {
// modifications to cartesian axes
var ax = layout[key];
if (ax.anchor && ax.anchor !== 'free') {
ax.anchor = cleanId(ax.anchor);
}
if (ax.overlaying) ax.overlaying = cleanId(ax.overlaying);
// old method of axis type - isdate and islog (before category existed)
if (!ax.type) {
if (ax.isdate) ax.type = 'date';else if (ax.islog) ax.type = 'log';else if (ax.isdate === false && ax.islog === false) ax.type = 'linear';
}
if (ax.autorange === 'withzero' || ax.autorange === 'tozero') {
ax.autorange = true;
ax.rangemode = 'tozero';
}
if (ax.insiderange) delete ax.range;
delete ax.islog;
delete ax.isdate;
delete ax.categories; // replaced by _categories
// prune empty domain arrays made before the new nestedProperty
if (emptyContainer(ax, 'domain')) delete ax.domain;
// autotick -> tickmode
if (ax.autotick !== undefined) {
if (ax.tickmode === undefined) {
ax.tickmode = ax.autotick ? 'auto' : 'linear';
}
delete ax.autotick;
}
cleanTitle(ax);
} else if (polarAttrRegex && polarAttrRegex.test(key)) {
// modifications for polar
var polar = layout[key];
cleanTitle(polar.radialaxis);
} else if (ternaryAttrRegex && ternaryAttrRegex.test(key)) {
// modifications for ternary
var ternary = layout[key];
cleanTitle(ternary.aaxis);
cleanTitle(ternary.baxis);
cleanTitle(ternary.caxis);
} else if (sceneAttrRegex && sceneAttrRegex.test(key)) {
// modifications for 3D scenes
var scene = layout[key];
// clean old Camera coords
var cameraposition = scene.cameraposition;
if (Array.isArray(cameraposition) && cameraposition[0].length === 4) {
var rotation = cameraposition[0];
var center = cameraposition[1];
var radius = cameraposition[2];
var mat = m4FromQuat([], rotation);
var eye = [];
for (j = 0; j < 3; ++j) {
eye[j] = center[j] + radius * mat[2 + 4 * j];
}
scene.camera = {
eye: {
x: eye[0],
y: eye[1],
z: eye[2]
},
center: {
x: center[0],
y: center[1],
z: center[2]
},
up: {
x: 0,
y: 0,
z: 1
} // we just ignore calculating camera z up in this case
};
delete scene.cameraposition;
}
// clean axis titles
cleanTitle(scene.xaxis);
cleanTitle(scene.yaxis);
cleanTitle(scene.zaxis);
}
}
var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0;
for (i = 0; i < annotationsLen; i++) {
var ann = layout.annotations[i];
if (!Lib.isPlainObject(ann)) continue;
if (ann.ref) {
if (ann.ref === 'paper') {
ann.xref = 'paper';
ann.yref = 'paper';
} else if (ann.ref === 'data') {
ann.xref = 'x';
ann.yref = 'y';
}
delete ann.ref;
}
cleanAxRef(ann, 'xref');
cleanAxRef(ann, 'yref');
}
var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0;
for (i = 0; i < shapesLen; i++) {
var shape = layout.shapes[i];
if (!Lib.isPlainObject(shape)) continue;
cleanAxRef(shape, 'xref');
cleanAxRef(shape, 'yref');
}
var imagesLen = Array.isArray(layout.images) ? layout.images.length : 0;
for (i = 0; i < imagesLen; i++) {
var image = layout.images[i];
if (!Lib.isPlainObject(image)) continue;
cleanAxRef(image, 'xref');
cleanAxRef(image, 'yref');
}
var legend = layout.legend;
if (legend) {
// check for old-style legend positioning (x or y is +/- 100)
if (legend.x > 3) {
legend.x = 1.02;
legend.xanchor = 'left';
} else if (legend.x < -2) {
legend.x = -0.02;
legend.xanchor = 'right';
}
if (legend.y > 3) {
legend.y = 1.02;
legend.yanchor = 'bottom';
} else if (legend.y < -2) {
legend.y = -0.02;
legend.yanchor = 'top';
}
}
// clean plot title
cleanTitle(layout);
/*
* Moved from rotate -> orbit for dragmode
*/
if (layout.dragmode === 'rotate') layout.dragmode = 'orbit';
// sanitize rgb(fractions) and rgba(fractions) that old tinycolor
// supported, but new tinycolor does not because they're not valid css
Color.clean(layout);
// clean the layout container in layout.template
if (layout.template && layout.template.layout) {
exports.cleanLayout(layout.template.layout);
}
return layout;
};
function cleanAxRef(container, attr) {
var valIn = container[attr];
var axLetter = attr.charAt(0);
if (valIn && valIn !== 'paper') {
container[attr] = cleanId(valIn, axLetter, true);
}
}
/**
* Cleans up old title attribute structure (flat) in favor of the new one (nested).
*
* @param {Object} titleContainer - an object potentially including deprecated title attributes
*/
function cleanTitle(titleContainer) {
if (titleContainer) {
// title -> title.text
// (although title used to be a string attribute,
// numbers are accepted as well)
if (typeof titleContainer.title === 'string' || typeof titleContainer.title === 'number') {
titleContainer.title = {
text: titleContainer.title
};
}
rewireAttr('titlefont', 'font');
rewireAttr('titleposition', 'position');
rewireAttr('titleside', 'side');
rewireAttr('titleoffset', 'offset');
}
function rewireAttr(oldAttrName, newAttrName) {
var oldAttrSet = titleContainer[oldAttrName];
var newAttrSet = titleContainer.title && titleContainer.title[newAttrName];
if (oldAttrSet && !newAttrSet) {
// Ensure title object exists
if (!titleContainer.title) {
titleContainer.title = {};
}
titleContainer.title[newAttrName] = titleContainer[oldAttrName];
delete titleContainer[oldAttrName];
}
}
}
/*
* cleanData: Make a few changes to the data for backward compatibility
* before it gets used for anything. Modifies the data traces users provide.
*
* Important: if you're going to add something here that modifies a data array,
* update it in place so the new array === the old one.
*/
exports.cleanData = function (data) {
for (var tracei = 0; tracei < data.length; tracei++) {
var trace = data[tracei];
var i;
// use xbins to bin data in x, and ybins to bin data in y
if (trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) {
trace.ybins = trace.xbins;
delete trace.xbins;
}
// error_y.opacity is obsolete - merge into color
if (trace.error_y && 'opacity' in trace.error_y) {
var dc = Color.defaults;
var yeColor = trace.error_y.color || (traceIs(trace, 'bar') ? Color.defaultLine : dc[tracei % dc.length]);
trace.error_y.color = Color.addOpacity(Color.rgb(yeColor), Color.opacity(yeColor) * trace.error_y.opacity);
delete trace.error_y.opacity;
}
// convert bardir to orientation, and put the data into
// the axes it's eventually going to be used with
if ('bardir' in trace) {
if (trace.bardir === 'h' && (traceIs(trace, 'bar') || trace.type.substr(0, 9) === 'histogram')) {
trace.orientation = 'h';
exports.swapXYData(trace);
}
delete trace.bardir;
}
// now we have only one 1D histogram type, and whether
// it uses x or y data depends on trace.orientation
if (trace.type === 'histogramy') exports.swapXYData(trace);
if (trace.type === 'histogramx' || trace.type === 'histogramy') {
trace.type = 'histogram';
}
// scl->scale, reversescl->reversescale
if ('scl' in trace && !('colorscale' in trace)) {
trace.colorscale = trace.scl;
delete trace.scl;
}
if ('reversescl' in trace && !('reversescale' in trace)) {
trace.reversescale = trace.reversescl;
delete trace.reversescl;
}
// axis ids x1 -> x, y1-> y
if (trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x');
if (trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y');
// scene ids scene1 -> scene
if (traceIs(trace, 'gl3d') && trace.scene) {
trace.scene = Plots.subplotsRegistry.gl3d.cleanId(trace.scene);
}
if (!traceIs(trace, 'pie-like') && !traceIs(trace, 'bar-like')) {
if (Array.isArray(trace.textposition)) {
for (i = 0; i < trace.textposition.length; i++) {
trace.textposition[i] = cleanTextPosition(trace.textposition[i]);
}
} else if (trace.textposition) {
trace.textposition = cleanTextPosition(trace.textposition);
}
}
// fix typo in colorscale definition
var _module = Registry.getModule(trace);
if (_module && _module.colorbar) {
var containerName = _module.colorbar.container;
var container = containerName ? trace[containerName] : trace;
if (container && container.colorscale) {
if (container.colorscale === 'YIGnBu') container.colorscale = 'YlGnBu';
if (container.colorscale === 'YIOrRd') container.colorscale = 'YlOrRd';
}
}
// fix typo in surface 'highlight*' definitions
if (trace.type === 'surface' && Lib.isPlainObject(trace.contours)) {
var dims = ['x', 'y', 'z'];
for (i = 0; i < dims.length; i++) {
var opts = trace.contours[dims[i]];
if (!Lib.isPlainObject(opts)) continue;
if (opts.highlightColor) {
opts.highlightcolor = opts.highlightColor;
delete opts.highlightColor;
}
if (opts.highlightWidth) {
opts.highlightwidth = opts.highlightWidth;
delete opts.highlightWidth;
}
}
}
// fixes from converting finance from transforms to real trace types
if (trace.type === 'candlestick' || trace.type === 'ohlc') {
var increasingShowlegend = (trace.increasing || {}).showlegend !== false;
var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false;
var increasingName = cleanFinanceDir(trace.increasing);
var decreasingName = cleanFinanceDir(trace.decreasing);
// now figure out something smart to do with the separate direction
// names we removed
if (increasingName !== false && decreasingName !== false) {
// both sub-names existed: base name previously had no effect
// so ignore it and try to find a shared part of the sub-names
var newName = commonPrefix(increasingName, decreasingName, increasingShowlegend, decreasingShowlegend);
// if no common part, leave whatever name was (or wasn't) there
if (newName) trace.name = newName;
} else if ((increasingName || decreasingName) && !trace.name) {
// one sub-name existed but not the base name - just use the sub-name
trace.name = increasingName || decreasingName;
}
}
// transforms backward compatibility fixes
if (Array.isArray(trace.transforms)) {
var transforms = trace.transforms;
for (i = 0; i < transforms.length; i++) {
var transform = transforms[i];
if (!Lib.isPlainObject(transform)) continue;
switch (transform.type) {
case 'filter':
if (transform.filtersrc) {
transform.target = transform.filtersrc;
delete transform.filtersrc;
}
if (transform.calendar) {
if (!transform.valuecalendar) {
transform.valuecalendar = transform.calendar;
}
delete transform.calendar;
}
break;
case 'groupby':
// Name has changed from `style` to `styles`, so use `style` but prefer `styles`:
transform.styles = transform.styles || transform.style;
if (transform.styles && !Array.isArray(transform.styles)) {
var prevStyles = transform.styles;
var styleKeys = Object.keys(prevStyles);
transform.styles = [];
for (var j = 0; j < styleKeys.length; j++) {
transform.styles.push({
target: styleKeys[j],
value: prevStyles[styleKeys[j]]
});
}
}
break;
}
}
}
// prune empty containers made before the new nestedProperty
if (emptyContainer(trace, 'line')) delete trace.line;
if ('marker' in trace) {
if (emptyContainer(trace.marker, 'line')) delete trace.marker.line;
if (emptyContainer(trace, 'marker')) delete trace.marker;
}
// sanitize rgb(fractions) and rgba(fractions) that old tinycolor
// supported, but new tinycolor does not because they're not valid css
Color.clean(trace);
// remove obsolete autobin(x|y) attributes, but only if true
// if false, this needs to happen in Histogram.calc because it
// can be a one-time autobin so we need to know the results before
// we can push them back into the trace.
if (trace.autobinx) {
delete trace.autobinx;
delete trace.xbins;
}
if (trace.autobiny) {
delete trace.autobiny;
delete trace.ybins;
}
cleanTitle(trace);
if (trace.colorbar) cleanTitle(trace.colorbar);
if (trace.marker && trace.marker.colorbar) cleanTitle(trace.marker.colorbar);
if (trace.line && trace.line.colorbar) cleanTitle(trace.line.colorbar);
if (trace.aaxis) cleanTitle(trace.aaxis);
if (trace.baxis) cleanTitle(trace.baxis);
}
};
function cleanFinanceDir(dirContainer) {
if (!Lib.isPlainObject(dirContainer)) return false;
var dirName = dirContainer.name;
delete dirContainer.name;
delete dirContainer.showlegend;
return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName);
}
function commonPrefix(name1, name2, show1, show2) {
// if only one is shown in the legend, use that
if (show1 && !show2) return name1;
if (show2 && !show1) return name2;
// if both or neither are in the legend, check if one is blank (or whitespace)
// and use the other one
// note that hover labels can still use the name even if the legend doesn't
if (!name1.trim()) return name2;
if (!name2.trim()) return name1;
var minLen = Math.min(name1.length, name2.length);
var i;
for (i = 0; i < minLen; i++) {
if (name1.charAt(i) !== name2.charAt(i)) break;
}
var out = name1.substr(0, i);
return out.trim();
}
// textposition - support partial attributes (ie just 'top')
// and incorrect use of middle / center etc.
function cleanTextPosition(textposition) {
var posY = 'middle';
var posX = 'center';
if (typeof textposition === 'string') {
if (textposition.indexOf('top') !== -1) posY = 'top';else if (textposition.indexOf('bottom') !== -1) posY = 'bottom';
if (textposition.indexOf('left') !== -1) posX = 'left';else if (textposition.indexOf('right') !== -1) posX = 'right';
}
return posY + ' ' + posX;
}
function emptyContainer(outer, innerStr) {
return innerStr in outer && typeof outer[innerStr] === 'object' && Object.keys(outer[innerStr]).length === 0;
}
// swap all the data and data attributes associated with x and y
exports.swapXYData = function (trace) {
var i;
Lib.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']);
if (Array.isArray(trace.z) && Array.isArray(trace.z[0])) {
if (trace.transpose) delete trace.transpose;else trace.transpose = true;
}
if (trace.error_x && trace.error_y) {
var errorY = trace.error_y;
var copyYstyle = 'copy_ystyle' in errorY ? errorY.copy_ystyle : !(errorY.color || errorY.thickness || errorY.width);
Lib.swapAttrs(trace, ['error_?.copy_ystyle']);
if (copyYstyle) {
Lib.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']);
}
}
if (typeof trace.hoverinfo === 'string') {
var hoverInfoParts = trace.hoverinfo.split('+');
for (i = 0; i < hoverInfoParts.length; i++) {
if (hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y';else if (hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x';
}
trace.hoverinfo = hoverInfoParts.join('+');
}
};
// coerce traceIndices input to array of trace indices
exports.coerceTraceIndices = function (gd, traceIndices) {
if (isNumeric(traceIndices)) {
return [traceIndices];
} else if (!Array.isArray(traceIndices) || !traceIndices.length) {
return gd.data.map(function (_, i) {
return i;
});
} else if (Array.isArray(traceIndices)) {
var traceIndicesOut = [];
for (var i = 0; i < traceIndices.length; i++) {
if (Lib.isIndex(traceIndices[i], gd.data.length)) {
traceIndicesOut.push(traceIndices[i]);
} else {
Lib.warn('trace index (', traceIndices[i], ') is not a number or is out of bounds');
}
}
return traceIndicesOut;
}
return traceIndices;
};
/**
* Manages logic around array container item creation / deletion / update
* that nested property alone can't handle.
*
* @param {Object} np
* nested property of update attribute string about trace or layout object
* @param {*} newVal
* update value passed to restyle / relayout / update
* @param {Object} undoit
* undo hash (N.B. undoit may be mutated here).
*
*/
exports.manageArrayContainers = function (np, newVal, undoit) {
var obj = np.obj;
var parts = np.parts;
var pLength = parts.length;
var pLast = parts[pLength - 1];
var pLastIsNumber = isNumeric(pLast);
if (pLastIsNumber && newVal === null) {
// delete item
// Clear item in array container when new value is null
var contPath = parts.slice(0, pLength - 1).join('.');
var cont = Lib.nestedProperty(obj, contPath).get();
cont.splice(pLast, 1);
// Note that nested property clears null / undefined at end of
// array container, but not within them.
} else if (pLastIsNumber && np.get() === undefined) {
// create item
// When adding a new item, make sure undo command will remove it
if (np.get() === undefined) undoit[np.astr] = null;
np.set(newVal);
} else {
// update item
// If the last part of attribute string isn't a number,
// np.set is all we need.
np.set(newVal);
}
};
/*
* Match the part to strip off to turn an attribute into its parent
* really it should be either '.some_characters' or '[number]'
* but we're a little more permissive here and match either
* '.not_brackets_or_dot' or '[not_brackets_or_dot]'
*/
var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;
function getParent(attr) {
var tail = attr.search(ATTR_TAIL_RE);
if (tail > 0) return attr.substr(0, tail);
}
/*
* hasParent: does an attribute object contain a parent of the given attribute?
* for example, given 'images[2].x' do we also have 'images' or 'images[2]'?
*
* @param {Object} aobj
* update object, whose keys are attribute strings and values are their new settings
* @param {string} attr
* the attribute string to test against
* @returns {Boolean}
* is a parent of attr present in aobj?
*/
exports.hasParent = function (aobj, attr) {
var attrParent = getParent(attr);
while (attrParent) {
if (attrParent in aobj) return true;
attrParent = getParent(attrParent);
}
return false;
};
/**
* Empty out types for all axes containing these traces so we auto-set them again
*
* @param {object} gd
* @param {[integer]} traces: trace indices to search for axes to clear the types of
* @param {object} layoutUpdate: any update being done concurrently to the layout,
* which may supercede clearing the axis types
*/
var axLetters = ['x', 'y', 'z'];
exports.clearAxisTypes = function (gd, traces, layoutUpdate) {
for (var i = 0; i < traces.length; i++) {
var trace = gd._fullData[i];
for (var j = 0; j < 3; j++) {
var ax = getFromTrace(gd, trace, axLetters[j]);
// do not clear log type - that's never an auto result so must have been intentional
if (ax && ax.type !== 'log') {
var axAttr = ax._name;
var sceneName = ax._id.substr(1);
if (sceneName.substr(0, 5) === 'scene') {
if (layoutUpdate[sceneName] !== undefined) continue;
axAttr = sceneName + '.' + axAttr;
}
var typeAttr = axAttr + '.type';
if (layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) {
Lib.nestedProperty(gd.layout, typeAttr).set(null);
}
}
}
}
};
/***/ }),
/***/ 22448:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var main = __webpack_require__(36424);
exports._doPlot = main._doPlot;
exports.newPlot = main.newPlot;
exports.restyle = main.restyle;
exports.relayout = main.relayout;
exports.redraw = main.redraw;
exports.update = main.update;
exports._guiRestyle = main._guiRestyle;
exports._guiRelayout = main._guiRelayout;
exports._guiUpdate = main._guiUpdate;
exports._storeDirectGUIEdit = main._storeDirectGUIEdit;
exports.react = main.react;
exports.extendTraces = main.extendTraces;
exports.prependTraces = main.prependTraces;
exports.addTraces = main.addTraces;
exports.deleteTraces = main.deleteTraces;
exports.moveTraces = main.moveTraces;
exports.purge = main.purge;
exports.addFrames = main.addFrames;
exports.deleteFrames = main.deleteFrames;
exports.animate = main.animate;
exports.setPlotConfig = main.setPlotConfig;
var getGraphDiv = (__webpack_require__(52200).getGraphDiv);
var eraseActiveShape = (__webpack_require__(4016).eraseActiveShape);
exports.deleteActiveShape = function (gd) {
return eraseActiveShape(getGraphDiv(gd));
};
exports.toImage = __webpack_require__(67024);
exports.validate = __webpack_require__(21480);
exports.downloadImage = __webpack_require__(39792);
var templateApi = __webpack_require__(94828);
exports.makeTemplate = templateApi.makeTemplate;
exports.validateTemplate = templateApi.validateTemplate;
/***/ }),
/***/ 17680:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isPlainObject = __webpack_require__(63620);
var noop = __webpack_require__(16628);
var Loggers = __webpack_require__(24248);
var sorterAsc = (__webpack_require__(14952).sorterAsc);
var Registry = __webpack_require__(24040);
exports.containerArrayMatch = __webpack_require__(69820);
var isAddVal = exports.isAddVal = function isAddVal(val) {
return val === 'add' || isPlainObject(val);
};
var isRemoveVal = exports.isRemoveVal = function isRemoveVal(val) {
return val === null || val === 'remove';
};
/*
* applyContainerArrayChanges: for managing arrays of layout components in relayout
* handles them all with a consistent interface.
*
* Here are the supported actions -> relayout calls -> edits we get here
* (as prepared in _relayout):
*
* add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}}
* add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}}
* delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}}
* -> {'annotations[2]': null} -> {2: {'': null}}
* delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}}
* -> {'annotations': null} -> {'': {'': null}}
* edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}}
*
* You can combine many edits to different objects. Objects are added and edited
* in ascending order, then removed in descending order.
* For example, starting with [a, b, c], if you want to:
* - replace b with d:
* {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d)
* - add a new item d between a and b, and edit b:
* {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d)
* - delete b and edit c:
* {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed)
*
* You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i`
* You CANNOT combine replacing/deleting the whole array with anything else (for the same array).
*
* @param {HTMLDivElement} gd
* the DOM element of the graph container div
* @param {Lib.nestedProperty} componentType: the array we are editing
* @param {Object} edits
* the changes to make; keys are indices to edit, values are themselves objects:
* {attr: newValue} of changes to make to that index (with add/remove behavior
* in special values of the empty attr)
* @param {Object} flags
* the flags for which actions we're going to perform to display these (and
* any other) changes. If we're already `recalc`ing, we don't need to redraw
* individual items
* @param {function} _nestedProperty
* a (possibly modified for gui edits) nestedProperty constructor
* The modified version takes a 3rd argument, for a prefix to the attribute
* string necessary for storing GUI edits
*
* @returns {bool} `true` if it managed to complete drawing of the changes
* `false` would mean the parent should replot.
*/
exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags, _nestedProperty) {
var componentType = np.astr;
var supplyComponentDefaults = Registry.getComponentMethod(componentType, 'supplyLayoutDefaults');
var draw = Registry.getComponentMethod(componentType, 'draw');
var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
var replotLater = flags.replot || flags.recalc || supplyComponentDefaults === noop || draw === noop;
var layout = gd.layout;
var fullLayout = gd._fullLayout;
if (edits['']) {
if (Object.keys(edits).length > 1) {
Loggers.warn('Full array edits are incompatible with other edits', componentType);
}
var fullVal = edits[''][''];
if (isRemoveVal(fullVal)) np.set(null);else if (Array.isArray(fullVal)) np.set(fullVal);else {
Loggers.warn('Unrecognized full array edit value', componentType, fullVal);
return true;
}
if (replotLater) return false;
supplyComponentDefaults(layout, fullLayout);
draw(gd);
return true;
}
var componentNums = Object.keys(edits).map(Number).sort(sorterAsc);
var componentArrayIn = np.get();
var componentArray = componentArrayIn || [];
// componentArrayFull is used just to keep splices in line between
// full and input arrays, so private keys can be copied over after
// redoing supplyDefaults
// TODO: this assumes componentArray is in gd.layout - which will not be
// true after we extend this to restyle
var componentArrayFull = _nestedProperty(fullLayout, componentType).get();
var deletes = [];
var firstIndexChange = -1;
var maxIndex = componentArray.length;
var i;
var j;
var componentNum;
var objEdits;
var objKeys;
var objVal;
var adding, prefix;
// first make the add and edit changes
for (i = 0; i < componentNums.length; i++) {
componentNum = componentNums[i];
objEdits = edits[componentNum];
objKeys = Object.keys(objEdits);
objVal = objEdits[''], adding = isAddVal(objVal);
if (componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) {
Loggers.warn('index out of range', componentType, componentNum);
continue;
}
if (objVal !== undefined) {
if (objKeys.length > 1) {
Loggers.warn('Insertion & removal are incompatible with edits to the same index.', componentType, componentNum);
}
if (isRemoveVal(objVal)) {
deletes.push(componentNum);
} else if (adding) {
if (objVal === 'add') objVal = {};
componentArray.splice(componentNum, 0, objVal);
if (componentArrayFull) componentArrayFull.splice(componentNum, 0, {});
} else {
Loggers.warn('Unrecognized full object edit value', componentType, componentNum, objVal);
}
if (firstIndexChange === -1) firstIndexChange = componentNum;
} else {
for (j = 0; j < objKeys.length; j++) {
prefix = componentType + '[' + componentNum + '].';
_nestedProperty(componentArray[componentNum], objKeys[j], prefix).set(objEdits[objKeys[j]]);
}
}
}
// now do deletes
for (i = deletes.length - 1; i >= 0; i--) {
componentArray.splice(deletes[i], 1);
// TODO: this drops private keys that had been stored in componentArrayFull
// does this have any ill effects?
if (componentArrayFull) componentArrayFull.splice(deletes[i], 1);
}
if (!componentArray.length) np.set(null);else if (!componentArrayIn) np.set(componentArray);
if (replotLater) return false;
supplyComponentDefaults(layout, fullLayout);
// finally draw all the components we need to
// if we added or removed any, redraw all after it
if (drawOne !== noop) {
var indicesToDraw;
if (firstIndexChange === -1) {
// there's no re-indexing to do, so only redraw components that changed
indicesToDraw = componentNums;
} else {
// in case the component array was shortened, we still need do call
// drawOne on the latter items so they get properly removed
maxIndex = Math.max(componentArray.length, maxIndex);
indicesToDraw = [];
for (i = 0; i < componentNums.length; i++) {
componentNum = componentNums[i];
if (componentNum >= firstIndexChange) break;
indicesToDraw.push(componentNum);
}
for (i = firstIndexChange; i < maxIndex; i++) {
indicesToDraw.push(i);
}
}
for (i = 0; i < indicesToDraw.length; i++) {
drawOne(gd, indicesToDraw[i]);
}
} else draw(gd);
return true;
};
/***/ }),
/***/ 36424:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var isNumeric = __webpack_require__(38248);
var hasHover = __webpack_require__(52264);
var Lib = __webpack_require__(3400);
var nestedProperty = Lib.nestedProperty;
var Events = __webpack_require__(95924);
var Queue = __webpack_require__(94552);
var Registry = __webpack_require__(24040);
var PlotSchema = __webpack_require__(73060);
var Plots = __webpack_require__(7316);
var Axes = __webpack_require__(54460);
var handleRangeDefaults = __webpack_require__(96312);
var cartesianLayoutAttributes = __webpack_require__(94724);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var initInteractions = (__webpack_require__(42464).initInteractions);
var xmlnsNamespaces = __webpack_require__(9616);
var clearOutline = (__webpack_require__(22676).clearOutline);
var dfltConfig = (__webpack_require__(20556).dfltConfig);
var manageArrays = __webpack_require__(17680);
var helpers = __webpack_require__(93404);
var subroutines = __webpack_require__(39172);
var editTypes = __webpack_require__(67824);
var AX_NAME_PATTERN = (__webpack_require__(33816).AX_NAME_PATTERN);
var numericNameWarningCount = 0;
var numericNameWarningCountLimit = 5;
/**
* Internal plot-creation function
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
* @param {array of objects} data
* array of traces, containing the data and display information for each trace
* @param {object} layout
* object describing the overall display of the plot,
* all the stuff that doesn't pertain to any individual trace
* @param {object} config
* configuration options (see ./plot_config.js for more info)
*
* OR
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
* @param {object} figure
* object containing `data`, `layout`, `config`, and `frames` members
*
*/
function _doPlot(gd, data, layout, config) {
var frames;
gd = Lib.getGraphDiv(gd);
// Events.init is idempotent and bails early if gd has already been init'd
Events.init(gd);
if (Lib.isPlainObject(data)) {
var obj = data;
data = obj.data;
layout = obj.layout;
config = obj.config;
frames = obj.frames;
}
var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]);
if (okToPlot === false) return Promise.reject();
// if there's no data or layout, and this isn't yet a plotly plot
// container, log a warning to help plotly.js users debug
if (!data && !layout && !Lib.isPlotDiv(gd)) {
Lib.warn('Calling _doPlot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd);
}
function addFrames() {
if (frames) {
return exports.addFrames(gd, frames);
}
}
// transfer configuration options to gd until we move over to
// a more OO like model
setPlotContext(gd, config);
if (!layout) layout = {};
// hook class for plots main container (in case of plotly.js
// this won't be #embedded-graph or .js-tab-contents)
d3.select(gd).classed('js-plotly-plot', true);
// off-screen getBoundingClientRect testing space,
// in #js-plotly-tester (and stored as Drawing.tester)
// so we can share cached text across tabs
Drawing.makeTester();
// collect promises for any async actions during plotting
// any part of the plotting code can push to gd._promises, then
// before we move to the next step, we check that they're all
// complete, and empty out the promise list again.
if (!Array.isArray(gd._promises)) gd._promises = [];
var graphWasEmpty = (gd.data || []).length === 0 && Array.isArray(data);
// if there is already data on the graph, append the new data
// if you only want to redraw, pass a non-array for data
if (Array.isArray(data)) {
helpers.cleanData(data);
if (graphWasEmpty) gd.data = data;else gd.data.push.apply(gd.data, data);
// for routines outside graph_obj that want a clean tab
// (rather than appending to an existing one) gd.empty
// is used to determine whether to make a new tab
gd.empty = false;
}
if (!gd.layout || graphWasEmpty) {
gd.layout = helpers.cleanLayout(layout);
}
Plots.supplyDefaults(gd);
var fullLayout = gd._fullLayout;
var hasCartesian = fullLayout._has('cartesian');
// so we don't try to re-call _doPlot from inside
// legend and colorbar, if margins changed
fullLayout._replotting = true;
// make or remake the framework if we need to
if (graphWasEmpty || fullLayout._shouldCreateBgLayer) {
makePlotFramework(gd);
if (fullLayout._shouldCreateBgLayer) {
delete fullLayout._shouldCreateBgLayer;
}
}
// clear gradient and pattern defs on each .plot call, because we know we'll loop through all traces
Drawing.initGradients(gd);
Drawing.initPatterns(gd);
// save initial show spikes once per graph
if (graphWasEmpty) Axes.saveShowSpikeInitial(gd);
// prepare the data and find the autorange
// generate calcdata, if we need to
// to force redoing calcdata, just delete it before calling _doPlot
var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length;
if (recalc) Plots.doCalcdata(gd);
// in case it has changed, attach fullData traces to calcdata
for (var i = 0; i < gd.calcdata.length; i++) {
gd.calcdata[i][0].trace = gd._fullData[i];
}
// make the figure responsive
if (gd._context.responsive) {
if (!gd._responsiveChartHandler) {
// Keep a reference to the resize handler to purge it down the road
gd._responsiveChartHandler = function () {
if (!Lib.isHidden(gd)) Plots.resize(gd);
};
// Listen to window resize
window.addEventListener('resize', gd._responsiveChartHandler);
}
} else {
Lib.clearResponsive(gd);
}
/*
* start async-friendly code - now we're actually drawing things
*/
var oldMargins = Lib.extendFlat({}, fullLayout._size);
// draw framework first so that margin-pushing
// components can position themselves correctly
var drawFrameworkCalls = 0;
function drawFramework() {
var basePlotModules = fullLayout._basePlotModules;
for (var i = 0; i < basePlotModules.length; i++) {
if (basePlotModules[i].drawFramework) {
basePlotModules[i].drawFramework(gd);
}
}
if (!fullLayout._glcanvas && fullLayout._has('gl')) {
fullLayout._glcanvas = fullLayout._glcontainer.selectAll('.gl-canvas').data([{
key: 'contextLayer',
context: true,
pick: false
}, {
key: 'focusLayer',
context: false,
pick: false
}, {
key: 'pickLayer',
context: false,
pick: true
}], function (d) {
return d.key;
});
fullLayout._glcanvas.enter().append('canvas').attr('class', function (d) {
return 'gl-canvas gl-canvas-' + d.key.replace('Layer', '');
}).style({
position: 'absolute',
top: 0,
left: 0,
overflow: 'visible',
'pointer-events': 'none'
});
}
var plotGlPixelRatio = gd._context.plotGlPixelRatio;
if (fullLayout._glcanvas) {
fullLayout._glcanvas.attr('width', fullLayout.width * plotGlPixelRatio).attr('height', fullLayout.height * plotGlPixelRatio).style('width', fullLayout.width + 'px').style('height', fullLayout.height + 'px');
var regl = fullLayout._glcanvas.data()[0].regl;
if (regl) {
// Unfortunately, this can happen when relayouting to large
// width/height on some browsers.
if (Math.floor(fullLayout.width * plotGlPixelRatio) !== regl._gl.drawingBufferWidth || Math.floor(fullLayout.height * plotGlPixelRatio) !== regl._gl.drawingBufferHeight) {
var msg = 'WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug.';
if (drawFrameworkCalls) {
Lib.error(msg);
} else {
Lib.log(msg + ' Clearing graph and plotting again.');
Plots.cleanPlot([], {}, gd._fullData, fullLayout);
Plots.supplyDefaults(gd);
fullLayout = gd._fullLayout;
Plots.doCalcdata(gd);
drawFrameworkCalls++;
return drawFramework();
}
}
}
}
if (fullLayout.modebar.orientation === 'h') {
fullLayout._modebardiv.style('height', null).style('width', '100%');
} else {
fullLayout._modebardiv.style('width', null).style('height', fullLayout.height + 'px');
}
return Plots.previousPromises(gd);
}
// draw anything that can affect margins.
function marginPushers() {
// First reset the list of things that are allowed to change the margins
// So any deleted traces or components will be wiped out of the
// automargin calculation.
// This means *every* margin pusher must be listed here, even if it
// doesn't actually try to push the margins until later.
Plots.clearAutoMarginIds(gd);
subroutines.drawMarginPushers(gd);
Axes.allowAutoMargin(gd);
if (gd._fullLayout.title.text && gd._fullLayout.title.automargin) Plots.allowAutoMargin(gd, 'title.automargin');
// TODO can this be moved elsewhere?
if (fullLayout._has('pie')) {
var fullData = gd._fullData;
for (var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (trace.type === 'pie' && trace.automargin) {
Plots.allowAutoMargin(gd, 'pie.' + trace.uid + '.automargin');
}
}
}
Plots.doAutoMargin(gd);
return Plots.previousPromises(gd);
}
// in case the margins changed, draw margin pushers again
function marginPushersAgain() {
if (!Plots.didMarginChange(oldMargins, fullLayout._size)) return;
return Lib.syncOrAsync([marginPushers, subroutines.layoutStyles], gd);
}
function positionAndAutorange() {
if (!recalc) {
doAutoRangeAndConstraints();
return;
}
// TODO: autosize extra for text markers and images
// see https://github.com/plotly/plotly.js/issues/1111
return Lib.syncOrAsync([Registry.getComponentMethod('shapes', 'calcAutorange'), Registry.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints], gd);
}
function doAutoRangeAndConstraints() {
if (gd._transitioning) return;
subroutines.doAutoRangeAndConstraints(gd);
// store initial ranges *after* enforcing constraints, otherwise
// we will never look like we're at the initial ranges
if (graphWasEmpty) Axes.saveRangeInitial(gd);
// this one is different from shapes/annotations calcAutorange
// the others incorporate those components into ax._extremes,
// this one actually sets the ranges in rangesliders.
Registry.getComponentMethod('rangeslider', 'calcAutorange')(gd);
}
// draw ticks, titles, and calculate axis scaling (._b, ._m)
function drawAxes() {
return Axes.draw(gd, graphWasEmpty ? '' : 'redraw');
}
var seq = [Plots.previousPromises, addFrames, drawFramework, marginPushers, marginPushersAgain];
if (hasCartesian) seq.push(positionAndAutorange);
seq.push(subroutines.layoutStyles);
if (hasCartesian) {
seq.push(drawAxes, function insideTickLabelsAutorange(gd) {
var insideTickLabelsUpdaterange = gd._fullLayout._insideTickLabelsUpdaterange;
if (insideTickLabelsUpdaterange) {
gd._fullLayout._insideTickLabelsUpdaterange = undefined;
return relayout(gd, insideTickLabelsUpdaterange).then(function () {
Axes.saveRangeInitial(gd, true);
});
}
});
}
seq.push(subroutines.drawData, subroutines.finalDraw, initInteractions, Plots.addLinks, Plots.rehover, Plots.redrag, Plots.reselect,
// TODO: doAutoMargin is only needed here for axis automargin, which
// happens outside of marginPushers where all the other automargins are
// calculated. Would be much better to separate margin calculations from
// component drawing - see https://github.com/plotly/plotly.js/issues/2704
Plots.doAutoMargin, Plots.previousPromises);
// even if everything we did was synchronous, return a promise
// so that the caller doesn't care which route we took
var plotDone = Lib.syncOrAsync(seq, gd);
if (!plotDone || !plotDone.then) plotDone = Promise.resolve();
return plotDone.then(function () {
emitAfterPlot(gd);
return gd;
});
}
function emitAfterPlot(gd) {
var fullLayout = gd._fullLayout;
if (fullLayout._redrawFromAutoMarginCount) {
fullLayout._redrawFromAutoMarginCount--;
} else {
gd.emit('plotly_afterplot');
}
}
function setPlotConfig(obj) {
return Lib.extendFlat(dfltConfig, obj);
}
function setBackground(gd, bgColor) {
try {
gd._fullLayout._paper.style('background', bgColor);
} catch (e) {
Lib.error(e);
}
}
function opaqueSetBackground(gd, bgColor) {
var blend = Color.combine(bgColor, 'white');
setBackground(gd, blend);
}
function setPlotContext(gd, config) {
if (!gd._context) {
gd._context = Lib.extendDeep({}, dfltConfig);
// stash href, used to make robust clipPath URLs
var base = d3.select('base');
gd._context._baseUrl = base.size() && base.attr('href') ? window.location.href.split('#')[0] : '';
}
var context = gd._context;
var i, keys, key;
if (config) {
keys = Object.keys(config);
for (i = 0; i < keys.length; i++) {
key = keys[i];
if (key === 'editable' || key === 'edits') continue;
if (key in context) {
if (key === 'setBackground' && config[key] === 'opaque') {
context[key] = opaqueSetBackground;
} else {
context[key] = config[key];
}
}
}
// map plot3dPixelRatio to plotGlPixelRatio for backward compatibility
if (config.plot3dPixelRatio && !context.plotGlPixelRatio) {
context.plotGlPixelRatio = context.plot3dPixelRatio;
}
// now deal with editable and edits - first editable overrides
// everything, then edits refines
var editable = config.editable;
if (editable !== undefined) {
// we're not going to *use* context.editable, we're only going to
// use context.edits... but keep it for the record
context.editable = editable;
keys = Object.keys(context.edits);
for (i = 0; i < keys.length; i++) {
context.edits[keys[i]] = editable;
}
}
if (config.edits) {
keys = Object.keys(config.edits);
for (i = 0; i < keys.length; i++) {
key = keys[i];
if (key in context.edits) {
context.edits[key] = config.edits[key];
}
}
}
// not part of the user-facing config options
context._exportedPlot = config._exportedPlot;
}
// staticPlot forces a bunch of others:
if (context.staticPlot) {
context.editable = false;
context.edits = {};
context.autosizable = false;
context.scrollZoom = false;
context.doubleClick = false;
context.showTips = false;
context.showLink = false;
context.displayModeBar = false;
}
// make sure hover-only devices have mode bar visible
if (context.displayModeBar === 'hover' && !hasHover) {
context.displayModeBar = true;
}
// default and fallback for setBackground
if (context.setBackground === 'transparent' || typeof context.setBackground !== 'function') {
context.setBackground = setBackground;
}
// Check if gd has a specified widht/height to begin with
context._hasZeroHeight = context._hasZeroHeight || gd.clientHeight === 0;
context._hasZeroWidth = context._hasZeroWidth || gd.clientWidth === 0;
// fill context._scrollZoom helper to help manage scrollZoom flaglist
var szIn = context.scrollZoom;
var szOut = context._scrollZoom = {};
if (szIn === true) {
szOut.cartesian = 1;
szOut.gl3d = 1;
szOut.geo = 1;
szOut.mapbox = 1;
} else if (typeof szIn === 'string') {
var parts = szIn.split('+');
for (i = 0; i < parts.length; i++) {
szOut[parts[i]] = 1;
}
} else if (szIn !== false) {
szOut.gl3d = 1;
szOut.geo = 1;
szOut.mapbox = 1;
}
}
// convenience function to force a full redraw, mostly for use by plotly.js
function redraw(gd) {
gd = Lib.getGraphDiv(gd);
if (!Lib.isPlotDiv(gd)) {
throw new Error('This element is not a Plotly plot: ' + gd);
}
helpers.cleanData(gd.data);
helpers.cleanLayout(gd.layout);
gd.calcdata = undefined;
return exports._doPlot(gd).then(function () {
gd.emit('plotly_redraw');
return gd;
});
}
/**
* Convenience function to make idempotent plot option obvious to users.
*
* @param gd
* @param {Object[]} data
* @param {Object} layout
* @param {Object} config
*/
function newPlot(gd, data, layout, config) {
gd = Lib.getGraphDiv(gd);
// remove gl contexts
Plots.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {});
Plots.purge(gd);
return exports._doPlot(gd, data, layout, config);
}
/**
* Wrap negative indicies to their positive counterparts.
*
* @param {Number[]} indices An array of indices
* @param {Number} maxIndex The maximum index allowable (arr.length - 1)
*/
function positivifyIndices(indices, maxIndex) {
var parentLength = maxIndex + 1;
var positiveIndices = [];
var i;
var index;
for (i = 0; i < indices.length; i++) {
index = indices[i];
if (index < 0) {
positiveIndices.push(parentLength + index);
} else {
positiveIndices.push(index);
}
}
return positiveIndices;
}
/**
* Ensures that an index array for manipulating gd.data is valid.
*
* Intended for use with addTraces, deleteTraces, and moveTraces.
*
* @param gd
* @param indices
* @param arrayName
*/
function assertIndexArray(gd, indices, arrayName) {
var i, index;
for (i = 0; i < indices.length; i++) {
index = indices[i];
// validate that indices are indeed integers
if (index !== parseInt(index, 10)) {
throw new Error('all values in ' + arrayName + ' must be integers');
}
// check that all indices are in bounds for given gd.data array length
if (index >= gd.data.length || index < -gd.data.length) {
throw new Error(arrayName + ' must be valid indices for gd.data.');
}
// check that indices aren't repeated
if (indices.indexOf(index, i + 1) > -1 || index >= 0 && indices.indexOf(-gd.data.length + index) > -1 || index < 0 && indices.indexOf(gd.data.length + index) > -1) {
throw new Error('each index in ' + arrayName + ' must be unique.');
}
}
}
/**
* Private function used by Plotly.moveTraces to check input args
*
* @param gd
* @param currentIndices
* @param newIndices
*/
function checkMoveTracesArgs(gd, currentIndices, newIndices) {
// check that gd has attribute 'data' and 'data' is array
if (!Array.isArray(gd.data)) {
throw new Error('gd.data must be an array.');
}
// validate currentIndices array
if (typeof currentIndices === 'undefined') {
throw new Error('currentIndices is a required argument.');
} else if (!Array.isArray(currentIndices)) {
currentIndices = [currentIndices];
}
assertIndexArray(gd, currentIndices, 'currentIndices');
// validate newIndices array if it exists
if (typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
newIndices = [newIndices];
}
if (typeof newIndices !== 'undefined') {
assertIndexArray(gd, newIndices, 'newIndices');
}
// check currentIndices and newIndices are the same length if newIdices exists
if (typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
throw new Error('current and new indices must be of equal length.');
}
}
/**
* A private function to reduce the type checking clutter in addTraces.
*
* @param gd
* @param traces
* @param newIndices
*/
function checkAddTracesArgs(gd, traces, newIndices) {
var i, value;
// check that gd has attribute 'data' and 'data' is array
if (!Array.isArray(gd.data)) {
throw new Error('gd.data must be an array.');
}
// make sure traces exists
if (typeof traces === 'undefined') {
throw new Error('traces must be defined.');
}
// make sure traces is an array
if (!Array.isArray(traces)) {
traces = [traces];
}
// make sure each value in traces is an object
for (i = 0; i < traces.length; i++) {
value = traces[i];
if (typeof value !== 'object' || Array.isArray(value) || value === null) {
throw new Error('all values in traces array must be non-array objects');
}
}
// make sure we have an index for each trace
if (typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
newIndices = [newIndices];
}
if (typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {
throw new Error('if indices is specified, traces.length must equal indices.length');
}
}
/**
* A private function to reduce the type checking clutter in spliceTraces.
* Get all update Properties from gd.data. Validate inputs and outputs.
* Used by prependTrace and extendTraces
*
* @param gd
* @param update
* @param indices
* @param maxPoints
*/
function assertExtendTracesArgs(gd, update, indices, maxPoints) {
var maxPointsIsObject = Lib.isPlainObject(maxPoints);
if (!Array.isArray(gd.data)) {
throw new Error('gd.data must be an array');
}
if (!Lib.isPlainObject(update)) {
throw new Error('update must be a key:value object');
}
if (typeof indices === 'undefined') {
throw new Error('indices must be an integer or array of integers');
}
assertIndexArray(gd, indices, 'indices');
for (var key in update) {
/*
* Verify that the attribute to be updated contains as many trace updates
* as indices. Failure must result in throw and no-op
*/
if (!Array.isArray(update[key]) || update[key].length !== indices.length) {
throw new Error('attribute ' + key + ' must be an array of length equal to indices array length');
}
/*
* if maxPoints is an object it must match keys and array lengths of 'update' 1:1
*/
if (maxPointsIsObject && (!(key in maxPoints) || !Array.isArray(maxPoints[key]) || maxPoints[key].length !== update[key].length)) {
throw new Error('when maxPoints is set as a key:value object it must contain a 1:1 ' + 'corrispondence with the keys and number of traces in the update object');
}
}
}
/**
* A private function to reduce the type checking clutter in spliceTraces.
*
* @param {Object|HTMLDivElement} gd
* @param {Object} update
* @param {Number[]} indices
* @param {Number||Object} maxPoints
* @return {Object[]}
*/
function getExtendProperties(gd, update, indices, maxPoints) {
var maxPointsIsObject = Lib.isPlainObject(maxPoints);
var updateProps = [];
var trace, target, prop, insert, maxp;
// allow scalar index to represent a single trace position
if (!Array.isArray(indices)) indices = [indices];
// negative indices are wrapped around to their positive value. Equivalent to python indexing.
indices = positivifyIndices(indices, gd.data.length - 1);
// loop through all update keys and traces and harvest validated data.
for (var key in update) {
for (var j = 0; j < indices.length; j++) {
/*
* Choose the trace indexed by the indices map argument and get the prop setter-getter
* instance that references the key and value for this particular trace.
*/
trace = gd.data[indices[j]];
prop = nestedProperty(trace, key);
/*
* Target is the existing gd.data.trace.dataArray value like "x" or "marker.size"
* Target must exist as an Array to allow the extend operation to be performed.
*/
target = prop.get();
insert = update[key][j];
if (!Lib.isArrayOrTypedArray(insert)) {
throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array');
}
if (!Lib.isArrayOrTypedArray(target)) {
throw new Error('cannot extend missing or non-array attribute: ' + key);
}
if (target.constructor !== insert.constructor) {
throw new Error('cannot extend array with an array of a different type: ' + key);
}
/*
* maxPoints may be an object map or a scalar. If object select the key:value, else
* Use the scalar maxPoints for all key and trace combinations.
*/
maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints;
// could have chosen null here, -1 just tells us to not take a window
if (!isNumeric(maxp)) maxp = -1;
/*
* Wrap the nestedProperty in an object containing required data
* for lengthening and windowing this particular trace - key combination.
* Flooring maxp mirrors the behaviour of floats in the Array.slice JSnative function.
*/
updateProps.push({
prop: prop,
target: target,
insert: insert,
maxp: Math.floor(maxp)
});
}
}
// all target and insertion data now validated
return updateProps;
}
/**
* A private function to key Extend and Prepend traces DRY
*
* @param {Object|HTMLDivElement} gd
* @param {Object} update
* @param {Number[]} indices
* @param {Number||Object} maxPoints
* @param {Function} updateArray
* @return {Object}
*/
function spliceTraces(gd, update, indices, maxPoints, updateArray) {
assertExtendTracesArgs(gd, update, indices, maxPoints);
var updateProps = getExtendProperties(gd, update, indices, maxPoints);
var undoUpdate = {};
var undoPoints = {};
for (var i = 0; i < updateProps.length; i++) {
var prop = updateProps[i].prop;
var maxp = updateProps[i].maxp;
// return new array and remainder
var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp);
prop.set(out[0]);
// build the inverse update object for the undo operation
if (!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = [];
undoUpdate[prop.astr].push(out[1]);
// build the matching maxPoints undo object containing original trace lengths
if (!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = [];
undoPoints[prop.astr].push(updateProps[i].target.length);
}
return {
update: undoUpdate,
maxPoints: undoPoints
};
}
function concatTypedArray(arr0, arr1) {
var arr2 = new arr0.constructor(arr0.length + arr1.length);
arr2.set(arr0);
arr2.set(arr1, arr0.length);
return arr2;
}
/**
* extend && prepend traces at indices with update arrays, window trace lengths to maxPoints
*
* Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend
* inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints
* from the head, whereas Extend truncates the head of the array, counting backward maxPoints
* from the tail.
*
* If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no
* truncation / windowing will be performed. If its zero, well the whole trace is truncated.
*
* @param {Object|HTMLDivElement} gd The graph div
* @param {Object} update The key:array map of target attributes to extend
* @param {Number|Number[]} indices The locations of traces to be extended
* @param {Number|Object} [maxPoints] Number of points for trace window after lengthening.
*
*/
function extendTraces(gd, update, indices, maxPoints) {
gd = Lib.getGraphDiv(gd);
function updateArray(target, insert, maxp) {
var newArray, remainder;
if (Lib.isTypedArray(target)) {
if (maxp < 0) {
var none = new target.constructor(0);
var both = concatTypedArray(target, insert);
if (maxp < 0) {
newArray = both;
remainder = none;
} else {
newArray = none;
remainder = both;
}
} else {
newArray = new target.constructor(maxp);
remainder = new target.constructor(target.length + insert.length - maxp);
if (maxp === insert.length) {
newArray.set(insert);
remainder.set(target);
} else if (maxp < insert.length) {
var numberOfItemsFromInsert = insert.length - maxp;
newArray.set(insert.subarray(numberOfItemsFromInsert));
remainder.set(target);
remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length);
} else {
var numberOfItemsFromTarget = maxp - insert.length;
var targetBegin = target.length - numberOfItemsFromTarget;
newArray.set(target.subarray(targetBegin));
newArray.set(insert, numberOfItemsFromTarget);
remainder.set(target.subarray(0, targetBegin));
}
}
} else {
newArray = target.concat(insert);
remainder = maxp >= 0 && maxp < newArray.length ? newArray.splice(0, newArray.length - maxp) : [];
}
return [newArray, remainder];
}
var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
var promise = exports.redraw(gd);
var undoArgs = [gd, undo.update, indices, undo.maxPoints];
Queue.add(gd, exports.prependTraces, undoArgs, extendTraces, arguments);
return promise;
}
function prependTraces(gd, update, indices, maxPoints) {
gd = Lib.getGraphDiv(gd);
function updateArray(target, insert, maxp) {
var newArray, remainder;
if (Lib.isTypedArray(target)) {
if (maxp <= 0) {
var none = new target.constructor(0);
var both = concatTypedArray(insert, target);
if (maxp < 0) {
newArray = both;
remainder = none;
} else {
newArray = none;
remainder = both;
}
} else {
newArray = new target.constructor(maxp);
remainder = new target.constructor(target.length + insert.length - maxp);
if (maxp === insert.length) {
newArray.set(insert);
remainder.set(target);
} else if (maxp < insert.length) {
var numberOfItemsFromInsert = insert.length - maxp;
newArray.set(insert.subarray(0, numberOfItemsFromInsert));
remainder.set(insert.subarray(numberOfItemsFromInsert));
remainder.set(target, numberOfItemsFromInsert);
} else {
var numberOfItemsFromTarget = maxp - insert.length;
newArray.set(insert);
newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length);
remainder.set(target.subarray(numberOfItemsFromTarget));
}
}
} else {
newArray = insert.concat(target);
remainder = maxp >= 0 && maxp < newArray.length ? newArray.splice(maxp, newArray.length) : [];
}
return [newArray, remainder];
}
var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
var promise = exports.redraw(gd);
var undoArgs = [gd, undo.update, indices, undo.maxPoints];
Queue.add(gd, exports.extendTraces, undoArgs, prependTraces, arguments);
return promise;
}
/**
* Add data traces to an existing graph div.
*
* @param {Object|HTMLDivElement} gd The graph div
* @param {Object[]} gd.data The array of traces we're adding to
* @param {Object[]|Object} traces The object or array of objects to add
* @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces
*
*/
function addTraces(gd, traces, newIndices) {
gd = Lib.getGraphDiv(gd);
var currentIndices = [];
var undoFunc = exports.deleteTraces;
var redoFunc = addTraces;
var undoArgs = [gd, currentIndices];
var redoArgs = [gd, traces]; // no newIndices here
var i;
var promise;
// all validation is done elsewhere to remove clutter here
checkAddTracesArgs(gd, traces, newIndices);
// make sure traces is an array
if (!Array.isArray(traces)) {
traces = [traces];
}
// make sure traces do not repeat existing ones
traces = traces.map(function (trace) {
return Lib.extendFlat({}, trace);
});
helpers.cleanData(traces);
// add the traces to gd.data (no redrawing yet!)
for (i = 0; i < traces.length; i++) {
gd.data.push(traces[i]);
}
// to continue, we need to call moveTraces which requires currentIndices
for (i = 0; i < traces.length; i++) {
currentIndices.push(-traces.length + i);
}
// if the user didn't define newIndices, they just want the traces appended
// i.e., we can simply redraw and be done
if (typeof newIndices === 'undefined') {
promise = exports.redraw(gd);
Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
return promise;
}
// make sure indices is property defined
if (!Array.isArray(newIndices)) {
newIndices = [newIndices];
}
try {
// this is redundant, but necessary to not catch later possible errors!
checkMoveTracesArgs(gd, currentIndices, newIndices);
} catch (error) {
// something went wrong, reset gd to be safe and rethrow error
gd.data.splice(gd.data.length - traces.length, traces.length);
throw error;
}
// if we're here, the user has defined specific places to place the new traces
// this requires some extra work that moveTraces will do
Queue.startSequence(gd);
Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
promise = exports.moveTraces(gd, currentIndices, newIndices);
Queue.stopSequence(gd);
return promise;
}
/**
* Delete traces at `indices` from gd.data array.
*
* @param {Object|HTMLDivElement} gd The graph div
* @param {Object[]} gd.data The array of traces we're removing from
* @param {Number|Number[]} indices The indices
*/
function deleteTraces(gd, indices) {
gd = Lib.getGraphDiv(gd);
var traces = [];
var undoFunc = exports.addTraces;
var redoFunc = deleteTraces;
var undoArgs = [gd, traces, indices];
var redoArgs = [gd, indices];
var i;
var deletedTrace;
// make sure indices are defined
if (typeof indices === 'undefined') {
throw new Error('indices must be an integer or array of integers.');
} else if (!Array.isArray(indices)) {
indices = [indices];
}
assertIndexArray(gd, indices, 'indices');
// convert negative indices to positive indices
indices = positivifyIndices(indices, gd.data.length - 1);
// we want descending here so that splicing later doesn't affect indexing
indices.sort(Lib.sorterDes);
for (i = 0; i < indices.length; i += 1) {
deletedTrace = gd.data.splice(indices[i], 1)[0];
traces.push(deletedTrace);
}
var promise = exports.redraw(gd);
Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
return promise;
}
/**
* Move traces at currentIndices array to locations in newIndices array.
*
* If newIndices is omitted, currentIndices will be moved to the end. E.g.,
* these are equivalent:
*
* Plotly.moveTraces(gd, [1, 2, 3], [-3, -2, -1])
* Plotly.moveTraces(gd, [1, 2, 3])
*
* @param {Object|HTMLDivElement} gd The graph div
* @param {Object[]} gd.data The array of traces we're removing from
* @param {Number|Number[]} currentIndices The locations of traces to be moved
* @param {Number|Number[]} [newIndices] The locations to move traces to
*
* Example calls:
*
* // move trace i to location x
* Plotly.moveTraces(gd, i, x)
*
* // move trace i to end of array
* Plotly.moveTraces(gd, i)
*
* // move traces i, j, k to end of array (i != j != k)
* Plotly.moveTraces(gd, [i, j, k])
*
* // move traces [i, j, k] to [x, y, z] (i != j != k) (x != y != z)
* Plotly.moveTraces(gd, [i, j, k], [x, y, z])
*
* // reorder all traces (assume there are 5--a, b, c, d, e)
* Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end'
*/
function moveTraces(gd, currentIndices, newIndices) {
gd = Lib.getGraphDiv(gd);
var newData = [];
var movingTraceMap = [];
var undoFunc = moveTraces;
var redoFunc = moveTraces;
var undoArgs = [gd, newIndices, currentIndices];
var redoArgs = [gd, currentIndices, newIndices];
var i;
// to reduce complexity here, check args elsewhere
// this throws errors where appropriate
checkMoveTracesArgs(gd, currentIndices, newIndices);
// make sure currentIndices is an array
currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices];
// if undefined, define newIndices to point to the end of gd.data array
if (typeof newIndices === 'undefined') {
newIndices = [];
for (i = 0; i < currentIndices.length; i++) {
newIndices.push(-currentIndices.length + i);
}
}
// make sure newIndices is an array if it's user-defined
newIndices = Array.isArray(newIndices) ? newIndices : [newIndices];
// convert negative indices to positive indices (they're the same length)
currentIndices = positivifyIndices(currentIndices, gd.data.length - 1);
newIndices = positivifyIndices(newIndices, gd.data.length - 1);
// at this point, we've coerced the index arrays into predictable forms
// get the traces that aren't being moved around
for (i = 0; i < gd.data.length; i++) {
// if index isn't in currentIndices, include it in ignored!
if (currentIndices.indexOf(i) === -1) {
newData.push(gd.data[i]);
}
}
// get a mapping of indices to moving traces
for (i = 0; i < currentIndices.length; i++) {
movingTraceMap.push({
newIndex: newIndices[i],
trace: gd.data[currentIndices[i]]
});
}
// reorder this mapping by newIndex, ascending
movingTraceMap.sort(function (a, b) {
return a.newIndex - b.newIndex;
});
// now, add the moving traces back in, in order!
for (i = 0; i < movingTraceMap.length; i += 1) {
newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace);
}
gd.data = newData;
var promise = exports.redraw(gd);
Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
return promise;
}
/**
* restyle: update trace attributes of an existing plot
*
* Can be called two ways.
*
* Signature 1:
* @param {String | HTMLDivElement} gd
* the id or DOM element of the graph container div
* @param {String} astr
* attribute string (like `'marker.symbol'`) to update
* @param {*} val
* value to give this attribute
* @param {Number[] | Number} [traces]
* integer or array of integers for the traces to alter (all if omitted)
*
* Signature 2:
* @param {String | HTMLDivElement} gd
* (as in signature 1)
* @param {Object} aobj
* attribute object `{astr1: val1, astr2: val2 ...}`
* allows setting multiple attributes simultaneously
* @param {Number[] | Number} [traces]
* (as in signature 1)
*
* `val` (or `val1`, `val2` ... in the object form) can be an array,
* to apply different values to each trace.
*
* If the array is too short, it will wrap around (useful for
* style files that want to specify cyclical default values).
*/
function restyle(gd, astr, val, _traces) {
gd = Lib.getGraphDiv(gd);
helpers.clearPromiseQueue(gd);
var aobj = {};
if (typeof astr === 'string') aobj[astr] = val;else if (Lib.isPlainObject(astr)) {
// the 3-arg form
aobj = Lib.extendFlat({}, astr);
if (_traces === undefined) _traces = val;
} else {
Lib.warn('Restyle fail.', astr, val, _traces);
return Promise.reject();
}
if (Object.keys(aobj).length) gd.changed = true;
var traces = helpers.coerceTraceIndices(gd, _traces);
var specs = _restyle(gd, aobj, traces);
var flags = specs.flags;
// clear calcdata and/or axis types if required so they get regenerated
if (flags.calc) gd.calcdata = undefined;
if (flags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, {});
// fill in redraw sequence
var seq = [];
if (flags.fullReplot) {
seq.push(exports._doPlot);
} else {
seq.push(Plots.previousPromises);
// maybe only call Plots.supplyDataDefaults in the splom case,
// to skip over long and slow axes defaults
Plots.supplyDefaults(gd);
if (flags.markerSize) {
Plots.doCalcdata(gd);
addAxRangeSequence(seq);
// TODO
// if all axes have autorange:false, then
// proceed to subroutines.doTraceStyle(),
// otherwise we must go through addAxRangeSequence,
// which in general must redraws 'all' axes
}
if (flags.style) seq.push(subroutines.doTraceStyle);
if (flags.colorbars) seq.push(subroutines.doColorBars);
seq.push(emitAfterPlot);
}
seq.push(Plots.rehover, Plots.redrag, Plots.reselect);
Queue.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces]);
var plotDone = Lib.syncOrAsync(seq, gd);
if (!plotDone || !plotDone.then) plotDone = Promise.resolve();
return plotDone.then(function () {
gd.emit('plotly_restyle', specs.eventData);
return gd;
});
}
// for undo: undefined initial vals must be turned into nulls
// so that we unset rather than ignore them
function undefinedToNull(val) {
if (val === undefined) return null;
return val;
}
/**
* Factory function to wrap nestedProperty with GUI edits if necessary
* with GUI edits we add an optional prefix to the nestedProperty constructor
* to prepend to the attribute string in the preGUI store.
*/
function makeNP(preGUI, guiEditFlag) {
if (!guiEditFlag) return nestedProperty;
return function (container, attr, prefix) {
var np = nestedProperty(container, attr);
var npSet = np.set;
np.set = function (val) {
var fullAttr = (prefix || '') + attr;
storeCurrent(fullAttr, np.get(), val, preGUI);
npSet(val);
};
return np;
};
}
function storeCurrent(attr, val, newVal, preGUI) {
if (Array.isArray(val) || Array.isArray(newVal)) {
var arrayVal = Array.isArray(val) ? val : [];
var arrayNew = Array.isArray(newVal) ? newVal : [];
var maxLen = Math.max(arrayVal.length, arrayNew.length);
for (var i = 0; i < maxLen; i++) {
storeCurrent(attr + '[' + i + ']', arrayVal[i], arrayNew[i], preGUI);
}
} else if (Lib.isPlainObject(val) || Lib.isPlainObject(newVal)) {
var objVal = Lib.isPlainObject(val) ? val : {};
var objNew = Lib.isPlainObject(newVal) ? newVal : {};
var objBoth = Lib.extendFlat({}, objVal, objNew);
for (var key in objBoth) {
storeCurrent(attr + '.' + key, objVal[key], objNew[key], preGUI);
}
} else if (preGUI[attr] === undefined) {
preGUI[attr] = undefinedToNull(val);
}
}
/**
* storeDirectGUIEdit: for routines that skip restyle/relayout and mock it
* by emitting a plotly_restyle or plotly_relayout event, this routine
* keeps track of the initial state in _preGUI for use by uirevision
* Does *not* apply these changes to data/layout - that's the responsibility
* of the calling routine.
*
* @param {object} container: the input attributes container (eg `layout` or a `trace`)
* @param {object} preGUI: where original values should be stored, either
* `layout._preGUI` or `layout._tracePreGUI[uid]`
* @param {object} edits: the {attr: val} object as normally passed to `relayout` etc
*/
function _storeDirectGUIEdit(container, preGUI, edits) {
for (var attr in edits) {
var np = nestedProperty(container, attr);
storeCurrent(attr, np.get(), edits[attr], preGUI);
}
}
function _restyle(gd, aobj, traces) {
var fullLayout = gd._fullLayout;
var fullData = gd._fullData;
var data = gd.data;
var guiEditFlag = fullLayout._guiEditing;
var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
var eventData = Lib.extendDeepAll({}, aobj);
var i;
cleanDeprecatedAttributeKeys(aobj);
// initialize flags
var flags = editTypes.traceFlags();
// copies of the change (and previous values of anything affected)
// for the undo / redo queue
var redoit = {};
var undoit = {};
var axlist;
// make a new empty vals array for undoit
function a0() {
return traces.map(function () {
return undefined;
});
}
// for autoranging multiple axes
function addToAxlist(axid) {
var axName = Axes.id2name(axid);
if (axlist.indexOf(axName) === -1) axlist.push(axName);
}
function autorangeAttr(axName) {
return 'LAYOUT' + axName + '.autorange';
}
function rangeAttr(axName) {
return 'LAYOUT' + axName + '.range';
}
function getFullTrace(traceIndex) {
// usually fullData maps 1:1 onto data, but with groupby transforms
// the fullData index can be greater. Take the *first* matching trace.
for (var j = traceIndex; j < fullData.length; j++) {
if (fullData[j]._input === data[traceIndex]) return fullData[j];
}
// should never get here - and if we *do* it should cause an error
// later on undefined fullTrace is passed to nestedProperty.
}
// for attrs that interact (like scales & autoscales), save the
// old vals before making the change
// val=undefined will not set a value, just record what the value was.
// val=null will delete the attribute
// attr can be an array to set several at once (all to the same val)
function doextra(attr, val, i) {
if (Array.isArray(attr)) {
attr.forEach(function (a) {
doextra(a, val, i);
});
return;
}
// quit if explicitly setting this elsewhere
if (attr in aobj || helpers.hasParent(aobj, attr)) return;
var extraparam;
if (attr.substr(0, 6) === 'LAYOUT') {
extraparam = layoutNP(gd.layout, attr.replace('LAYOUT', ''));
} else {
var tracei = traces[i];
var preGUI = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid];
extraparam = makeNP(preGUI, guiEditFlag)(data[tracei], attr);
}
if (!(attr in undoit)) {
undoit[attr] = a0();
}
if (undoit[attr][i] === undefined) {
undoit[attr][i] = undefinedToNull(extraparam.get());
}
if (val !== undefined) {
extraparam.set(val);
}
}
function allBins(binAttr) {
return function (j) {
return fullData[j][binAttr];
};
}
function arrayBins(binAttr) {
return function (vij, j) {
return vij === false ? fullData[traces[j]][binAttr] : null;
};
}
// now make the changes to gd.data (and occasionally gd.layout)
// and figure out what kind of graphics update we need to do
for (var ai in aobj) {
if (helpers.hasParent(aobj, ai)) {
throw new Error('cannot set ' + ai + ' and a parent attribute simultaneously');
}
var vi = aobj[ai];
var cont;
var contFull;
var param;
var oldVal;
var newVal;
var valObject;
// Backward compatibility shim for turning histogram autobin on,
// or freezing previous autobinned values.
// Replace obsolete `autobin(x|y): true` with `(x|y)bins: null`
// and `autobin(x|y): false` with the `(x|y)bins` in `fullData`
if (ai === 'autobinx' || ai === 'autobiny') {
ai = ai.charAt(ai.length - 1) + 'bins';
if (Array.isArray(vi)) vi = vi.map(arrayBins(ai));else if (vi === false) vi = traces.map(allBins(ai));else vi = null;
}
redoit[ai] = vi;
if (ai.substr(0, 6) === 'LAYOUT') {
param = layoutNP(gd.layout, ai.replace('LAYOUT', ''));
undoit[ai] = [undefinedToNull(param.get())];
// since we're allowing val to be an array, allow it here too,
// even though that's meaningless
param.set(Array.isArray(vi) ? vi[0] : vi);
// ironically, the layout attrs in restyle only require replot,
// not relayout
flags.calc = true;
continue;
}
// set attribute in gd.data
undoit[ai] = a0();
for (i = 0; i < traces.length; i++) {
cont = data[traces[i]];
contFull = getFullTrace(traces[i]);
var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid];
param = makeNP(preGUI, guiEditFlag)(cont, ai);
oldVal = param.get();
newVal = Array.isArray(vi) ? vi[i % vi.length] : vi;
if (newVal === undefined) continue;
var finalPart = param.parts[param.parts.length - 1];
var prefix = ai.substr(0, ai.length - finalPart.length - 1);
var prefixDot = prefix ? prefix + '.' : '';
var innerContFull = prefix ? nestedProperty(contFull, prefix).get() : contFull;
valObject = PlotSchema.getTraceValObject(contFull, param.parts);
if (valObject && valObject.impliedEdits && newVal !== null) {
for (var impliedKey in valObject.impliedEdits) {
doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i);
}
} else if ((finalPart === 'thicknessmode' || finalPart === 'lenmode') && oldVal !== newVal && (newVal === 'fraction' || newVal === 'pixels') && innerContFull) {
// changing colorbar size modes,
// make the resulting size not change
// note that colorbar fractional sizing is based on the
// original plot size, before anything (like a colorbar)
// increases the margins
var gs = fullLayout._size;
var orient = innerContFull.orient;
var topOrBottom = orient === 'top' || orient === 'bottom';
if (finalPart === 'thicknessmode') {
var thicknorm = topOrBottom ? gs.h : gs.w;
doextra(prefixDot + 'thickness', innerContFull.thickness * (newVal === 'fraction' ? 1 / thicknorm : thicknorm), i);
} else {
var lennorm = topOrBottom ? gs.w : gs.h;
doextra(prefixDot + 'len', innerContFull.len * (newVal === 'fraction' ? 1 / lennorm : lennorm), i);
}
} else if (ai === 'type' && (newVal === 'pie' !== (oldVal === 'pie') || newVal === 'funnelarea' !== (oldVal === 'funnelarea'))) {
var labelsTo = 'x';
var valuesTo = 'y';
if ((newVal === 'bar' || oldVal === 'bar') && cont.orientation === 'h') {
labelsTo = 'y';
valuesTo = 'x';
}
Lib.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo);
Lib.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo);
Lib.swapAttrs(cont, ['?', '?src'], 'values', valuesTo);
if (oldVal === 'pie' || oldVal === 'funnelarea') {
nestedProperty(cont, 'marker.color').set(nestedProperty(cont, 'marker.colors').get());
// super kludgy - but if all pies are gone we won't remove them otherwise
fullLayout._pielayer.selectAll('g.trace').remove();
} else if (Registry.traceIs(cont, 'cartesian')) {
nestedProperty(cont, 'marker.colors').set(nestedProperty(cont, 'marker.color').get());
}
}
undoit[ai][i] = undefinedToNull(oldVal);
// set the new value - if val is an array, it's one el per trace
// first check for attributes that get more complex alterations
var swapAttrs = ['swapxy', 'swapxyaxes', 'orientation', 'orientationaxes'];
if (swapAttrs.indexOf(ai) !== -1) {
// setting an orientation: make sure it's changing
// before we swap everything else
if (ai === 'orientation') {
param.set(newVal);
// obnoxious that we need this level of coupling... but in order to
// properly handle setting orientation to `null` we need to mimic
// the logic inside Bars.supplyDefaults for default orientation
var defaultOrientation = cont.x && !cont.y ? 'h' : 'v';
if ((param.get() || defaultOrientation) === contFull.orientation) {
continue;
}
} else if (ai === 'orientationaxes') {
// orientationaxes has no value,
// it flips everything and the axes
cont.orientation = {
v: 'h',
h: 'v'
}[contFull.orientation];
}
helpers.swapXYData(cont);
flags.calc = flags.clearAxisTypes = true;
} else if (Plots.dataArrayContainers.indexOf(param.parts[0]) !== -1) {
// TODO: use manageArrays.applyContainerArrayChanges here too
helpers.manageArrayContainers(param, newVal, undoit);
flags.calc = true;
} else {
if (valObject) {
// must redo calcdata when restyling array values of arrayOk attributes
// ... but no need to this for regl-based traces
if (valObject.arrayOk && !Registry.traceIs(contFull, 'regl') && (Lib.isArrayOrTypedArray(newVal) || Lib.isArrayOrTypedArray(oldVal))) {
flags.calc = true;
} else editTypes.update(flags, valObject);
} else {
/*
* if we couldn't find valObject, assume a full recalc.
* This can happen if you're changing type and making
* some other edits too, so the modules we're
* looking at don't have these attributes in them.
*/
flags.calc = true;
}
// all the other ones, just modify that one attribute
param.set(newVal);
}
}
// swap the data attributes of the relevant x and y axes?
if (['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) {
Axes.swap(gd, traces);
}
// swap hovermode if set to "compare x/y data"
if (ai === 'orientationaxes') {
var hovermode = nestedProperty(gd.layout, 'hovermode');
var h = hovermode.get();
if (h === 'x') {
hovermode.set('y');
} else if (h === 'y') {
hovermode.set('x');
} else if (h === 'x unified') {
hovermode.set('y unified');
} else if (h === 'y unified') {
hovermode.set('x unified');
}
}
// Major enough changes deserve autoscale and
// non-reversed axes so people don't get confused
//
// Note: autobin (or its new analog bin clearing) is not included here
// since we're not pushing bins back to gd.data, so if we have bin
// info it was explicitly provided by the user.
if (['orientation', 'type'].indexOf(ai) !== -1) {
axlist = [];
for (i = 0; i < traces.length; i++) {
var trace = data[traces[i]];
if (Registry.traceIs(trace, 'cartesian')) {
addToAxlist(trace.xaxis || 'x');
addToAxlist(trace.yaxis || 'y');
}
}
doextra(axlist.map(autorangeAttr), true, 0);
doextra(axlist.map(rangeAttr), [0, 1], 0);
}
}
if (flags.calc || flags.plot) {
flags.fullReplot = true;
}
return {
flags: flags,
undoit: undoit,
redoit: redoit,
traces: traces,
eventData: Lib.extendDeepNoArrays([], [eventData, traces])
};
}
/**
* Converts deprecated attribute keys to
* the current API to ensure backwards compatibility.
*
* This is needed for the update mechanism to determine which
* subroutines to run based on the actual attribute
* definitions (that don't include the deprecated ones).
*
* E.g. Maps {'xaxis.title': 'A chart'} to {'xaxis.title.text': 'A chart'}
* and {titlefont: {...}} to {'title.font': {...}}.
*
* @param aobj
*/
function cleanDeprecatedAttributeKeys(aobj) {
var oldAxisTitleRegex = Lib.counterRegex('axis', '\.title', false, false);
var colorbarRegex = /colorbar\.title$/;
var keys = Object.keys(aobj);
var i, key, value;
for (i = 0; i < keys.length; i++) {
key = keys[i];
value = aobj[key];
if ((key === 'title' || oldAxisTitleRegex.test(key) || colorbarRegex.test(key)) && (typeof value === 'string' || typeof value === 'number')) {
replace(key, key.replace('title', 'title.text'));
} else if (key.indexOf('titlefont') > -1 && key.indexOf('grouptitlefont') === -1) {
replace(key, key.replace('titlefont', 'title.font'));
} else if (key.indexOf('titleposition') > -1) {
replace(key, key.replace('titleposition', 'title.position'));
} else if (key.indexOf('titleside') > -1) {
replace(key, key.replace('titleside', 'title.side'));
} else if (key.indexOf('titleoffset') > -1) {
replace(key, key.replace('titleoffset', 'title.offset'));
}
}
function replace(oldAttrStr, newAttrStr) {
aobj[newAttrStr] = aobj[oldAttrStr];
delete aobj[oldAttrStr];
}
}
/**
* relayout: update layout attributes of an existing plot
*
* Can be called two ways:
*
* Signature 1:
* @param {String | HTMLDivElement} gd
* the id or dom element of the graph container div
* @param {String} astr
* attribute string (like `'xaxis.range[0]'`) to update
* @param {*} val
* value to give this attribute
*
* Signature 2:
* @param {String | HTMLDivElement} gd
* (as in signature 1)
* @param {Object} aobj
* attribute object `{astr1: val1, astr2: val2 ...}`
* allows setting multiple attributes simultaneously
*/
function relayout(gd, astr, val) {
gd = Lib.getGraphDiv(gd);
helpers.clearPromiseQueue(gd);
var aobj = {};
if (typeof astr === 'string') {
aobj[astr] = val;
} else if (Lib.isPlainObject(astr)) {
aobj = Lib.extendFlat({}, astr);
} else {
Lib.warn('Relayout fail.', astr, val);
return Promise.reject();
}
if (Object.keys(aobj).length) gd.changed = true;
var specs = _relayout(gd, aobj);
var flags = specs.flags;
// clear calcdata if required
if (flags.calc) gd.calcdata = undefined;
// fill in redraw sequence
// even if we don't have anything left in aobj,
// something may have happened within relayout that we
// need to wait for
var seq = [Plots.previousPromises];
if (flags.layoutReplot) {
seq.push(subroutines.layoutReplot);
} else if (Object.keys(aobj).length) {
axRangeSupplyDefaultsByPass(gd, flags, specs) || Plots.supplyDefaults(gd);
if (flags.legend) seq.push(subroutines.doLegend);
if (flags.layoutstyle) seq.push(subroutines.layoutStyles);
if (flags.axrange) addAxRangeSequence(seq, specs.rangesAltered);
if (flags.ticks) seq.push(subroutines.doTicksRelayout);
if (flags.modebar) seq.push(subroutines.doModeBar);
if (flags.camera) seq.push(subroutines.doCamera);
if (flags.colorbars) seq.push(subroutines.doColorBars);
seq.push(emitAfterPlot);
}
seq.push(Plots.rehover, Plots.redrag, Plots.reselect);
Queue.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit]);
var plotDone = Lib.syncOrAsync(seq, gd);
if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
return plotDone.then(function () {
gd.emit('plotly_relayout', specs.eventData);
return gd;
});
}
// Optimization mostly for large splom traces where
// Plots.supplyDefaults can take > 100ms
function axRangeSupplyDefaultsByPass(gd, flags, specs) {
var fullLayout = gd._fullLayout;
if (!flags.axrange) return false;
for (var k in flags) {
if (k !== 'axrange' && flags[k]) return false;
}
var axIn, axOut;
var coerce = function (attr, dflt) {
return Lib.coerce(axIn, axOut, cartesianLayoutAttributes, attr, dflt);
};
var options = {}; // passing empty options for now!
for (var axId in specs.rangesAltered) {
var axName = Axes.id2name(axId);
axIn = gd.layout[axName];
axOut = fullLayout[axName];
handleRangeDefaults(axIn, axOut, coerce, options);
if (axOut._matchGroup) {
for (var axId2 in axOut._matchGroup) {
if (axId2 !== axId) {
var ax2 = fullLayout[Axes.id2name(axId2)];
ax2.autorange = axOut.autorange;
ax2.range = axOut.range.slice();
ax2._input.range = axOut.range.slice();
}
}
}
}
return true;
}
function addAxRangeSequence(seq, rangesAltered) {
// N.B. leave as sequence of subroutines (for now) instead of
// subroutine of its own so that finalDraw always gets
// executed after drawData
var drawAxes = rangesAltered ? function (gd) {
var axIds = [];
var skipTitle = true;
for (var id in rangesAltered) {
var ax = Axes.getFromId(gd, id);
axIds.push(id);
if ((ax.ticklabelposition || '').indexOf('inside') !== -1) {
if (ax._anchorAxis) {
axIds.push(ax._anchorAxis._id);
}
}
if (ax._matchGroup) {
for (var id2 in ax._matchGroup) {
if (!rangesAltered[id2]) {
axIds.push(id2);
}
}
}
}
return Axes.draw(gd, axIds, {
skipTitle: skipTitle
});
} : function (gd) {
return Axes.draw(gd, 'redraw');
};
seq.push(clearOutline, subroutines.doAutoRangeAndConstraints, drawAxes, subroutines.drawData, subroutines.finalDraw);
}
var AX_RANGE_RE = /^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/;
var AX_AUTORANGE_RE = /^[xyz]axis[0-9]*\.autorange$/;
var AX_DOMAIN_RE = /^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/;
function _relayout(gd, aobj) {
var layout = gd.layout;
var fullLayout = gd._fullLayout;
var guiEditFlag = fullLayout._guiEditing;
var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
var keys = Object.keys(aobj);
var axes = Axes.list(gd);
var eventData = Lib.extendDeepAll({}, aobj);
var arrayEdits = {};
var arrayStr, i, j;
cleanDeprecatedAttributeKeys(aobj);
keys = Object.keys(aobj);
// look for 'allaxes', split out into all axes
// in case of 3D the axis are nested within a scene which is held in _id
for (i = 0; i < keys.length; i++) {
if (keys[i].indexOf('allaxes') === 0) {
for (j = 0; j < axes.length; j++) {
var scene = axes[j]._id.substr(1);
var axisAttr = scene.indexOf('scene') !== -1 ? scene + '.' : '';
var newkey = keys[i].replace('allaxes', axisAttr + axes[j]._name);
if (!aobj[newkey]) aobj[newkey] = aobj[keys[i]];
}
delete aobj[keys[i]];
}
}
// initialize flags
var flags = editTypes.layoutFlags();
// copies of the change (and previous values of anything affected)
// for the undo / redo queue
var redoit = {};
var undoit = {};
// for attrs that interact (like scales & autoscales), save the
// old vals before making the change
// val=undefined will not set a value, just record what the value was.
// attr can be an array to set several at once (all to the same val)
function doextra(attr, val) {
if (Array.isArray(attr)) {
attr.forEach(function (a) {
doextra(a, val);
});
return;
}
// if we have another value for this attribute (explicitly or
// via a parent) do not override with this auto-generated extra
if (attr in aobj || helpers.hasParent(aobj, attr)) return;
var p = layoutNP(layout, attr);
if (!(attr in undoit)) {
undoit[attr] = undefinedToNull(p.get());
}
if (val !== undefined) p.set(val);
}
// for constraint enforcement: keep track of all axes (as {id: name})
// we're editing the (auto)range of, so we can tell the others constrained
// to scale with them that it's OK for them to shrink
var rangesAltered = {};
var ax;
function recordAlteredAxis(pleafPlus) {
var axId = Axes.name2id(pleafPlus.split('.')[0]);
rangesAltered[axId] = 1;
return axId;
}
// alter gd.layout
for (var ai in aobj) {
if (helpers.hasParent(aobj, ai)) {
throw new Error('cannot set ' + ai + ' and a parent attribute simultaneously');
}
var p = layoutNP(layout, ai);
var vi = aobj[ai];
var plen = p.parts.length;
// p.parts may end with an index integer if the property is an array
var pend = plen - 1;
while (pend > 0 && typeof p.parts[pend] !== 'string') pend--;
// last property in chain (leaf node)
var pleaf = p.parts[pend];
// leaf plus immediate parent
var pleafPlus = p.parts[pend - 1] + '.' + pleaf;
// trunk nodes (everything except the leaf)
var ptrunk = p.parts.slice(0, pend).join('.');
var parentIn = nestedProperty(gd.layout, ptrunk).get();
var parentFull = nestedProperty(fullLayout, ptrunk).get();
var vOld = p.get();
if (vi === undefined) continue;
redoit[ai] = vi;
// axis reverse is special - it is its own inverse
// op and has no flag.
undoit[ai] = pleaf === 'reverse' ? vi : undefinedToNull(vOld);
var valObject = PlotSchema.getLayoutValObject(fullLayout, p.parts);
if (valObject && valObject.impliedEdits && vi !== null) {
for (var impliedKey in valObject.impliedEdits) {
doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]);
}
}
// Setting width or height to null must reset the graph's width / height
// back to its initial value as computed during the first pass in Plots.plotAutoSize.
//
// To do so, we must manually set them back here using the _initialAutoSize cache.
// can't use impliedEdits for this because behavior depends on vi
if (['width', 'height'].indexOf(ai) !== -1) {
if (vi) {
doextra('autosize', null);
// currently we don't support autosize one dim only - so
// explicitly set the other one. Note that doextra will
// ignore this if the same relayout call also provides oppositeAttr
var oppositeAttr = ai === 'height' ? 'width' : 'height';
doextra(oppositeAttr, fullLayout[oppositeAttr]);
} else {
fullLayout[ai] = gd._initialAutoSize[ai];
}
} else if (ai === 'autosize') {
// depends on vi here too, so again can't use impliedEdits
doextra('width', vi ? null : fullLayout.width);
doextra('height', vi ? null : fullLayout.height);
} else if (pleafPlus.match(AX_RANGE_RE)) {
// check autorange vs range
recordAlteredAxis(pleafPlus);
nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
} else if (pleafPlus.match(AX_AUTORANGE_RE)) {
recordAlteredAxis(pleafPlus);
nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
var axFull = nestedProperty(fullLayout, ptrunk).get();
if (axFull._inputDomain) {
// if we're autoranging and this axis has a constrained domain,
// reset it so we don't get locked into a shrunken size
axFull._input.domain = axFull._inputDomain.slice();
}
} else if (pleafPlus.match(AX_DOMAIN_RE)) {
nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null);
}
// toggling axis type between log and linear: we need to convert
// positions for components that are still using linearized values,
// not data values like newer components.
// previously we did this for log <-> not-log, but now only do it
// for log <-> linear
if (pleaf === 'type') {
ax = parentIn;
var toLog = parentFull.type === 'linear' && vi === 'log';
var fromLog = parentFull.type === 'log' && vi === 'linear';
if (toLog || fromLog) {
if (!ax || !ax.range) {
// 2D never gets here, but 3D does
// I don't think this is needed, but left here in case there
// are edge cases I'm not thinking of.
doextra(ptrunk + '.autorange', true);
} else if (!parentFull.autorange) {
// toggling log without autorange: need to also recalculate ranges
// because log axes use linearized values for range endpoints
var r0 = ax.range[0];
var r1 = ax.range[1];
if (toLog) {
// if both limits are negative, autorange
if (r0 <= 0 && r1 <= 0) {
doextra(ptrunk + '.autorange', true);
}
// if one is negative, set it 6 orders below the other.
if (r0 <= 0) r0 = r1 / 1e6;else if (r1 <= 0) r1 = r0 / 1e6;
// now set the range values as appropriate
doextra(ptrunk + '.range[0]', Math.log(r0) / Math.LN10);
doextra(ptrunk + '.range[1]', Math.log(r1) / Math.LN10);
} else {
doextra(ptrunk + '.range[0]', Math.pow(10, r0));
doextra(ptrunk + '.range[1]', Math.pow(10, r1));
}
} else if (toLog) {
// just make sure the range is positive and in the right
// order, it'll get recalculated later
ax.range = ax.range[1] > ax.range[0] ? [1, 2] : [2, 1];
}
// clear polar view initial stash for radial range so that
// value get recomputed in correct units
if (Array.isArray(fullLayout._subplots.polar) && fullLayout._subplots.polar.length && fullLayout[p.parts[0]] && p.parts[1] === 'radialaxis') {
delete fullLayout[p.parts[0]]._subplot.viewInitial['radialaxis.range'];
}
// Annotations and images also need to convert to/from linearized coords
// Shapes do not need this :)
Registry.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra);
Registry.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra);
} else {
// any other type changes: the range from the previous type
// will not make sense, so autorange it.
doextra(ptrunk + '.autorange', true);
doextra(ptrunk + '.range', null);
}
nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
} else if (pleaf.match(AX_NAME_PATTERN)) {
var fullProp = nestedProperty(fullLayout, ai).get();
var newType = (vi || {}).type;
// This can potentially cause strange behavior if the autotype is not
// numeric (linear, because we don't auto-log) but the previous type
// was log. That's a very strange edge case though
if (!newType || newType === '-') newType = 'linear';
Registry.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra);
Registry.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra);
}
// alter gd.layout
// collect array component edits for execution all together
// so we can ensure consistent behavior adding/removing items
// and order-independence for add/remove/edit all together in
// one relayout call
var containerArrayMatch = manageArrays.containerArrayMatch(ai);
if (containerArrayMatch) {
arrayStr = containerArrayMatch.array;
i = containerArrayMatch.index;
var propStr = containerArrayMatch.property;
var updateValObject = valObject || {
editType: 'calc'
};
if (i !== '' && propStr === '') {
// special handling of undoit if we're adding or removing an element
// ie 'annotations[2]' which can be {...} (add) or null,
// does not work when replacing the entire array
if (manageArrays.isAddVal(vi)) {
undoit[ai] = null;
} else if (manageArrays.isRemoveVal(vi)) {
undoit[ai] = (nestedProperty(layout, arrayStr).get() || [])[i];
} else {
Lib.warn('unrecognized full object value', aobj);
}
}
editTypes.update(flags, updateValObject);
// prepare the edits object we'll send to applyContainerArrayChanges
if (!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {};
var objEdits = arrayEdits[arrayStr][i];
if (!objEdits) objEdits = arrayEdits[arrayStr][i] = {};
objEdits[propStr] = vi;
delete aobj[ai];
} else if (pleaf === 'reverse') {
// handle axis reversal explicitly, as there's no 'reverse' attribute
if (parentIn.range) parentIn.range.reverse();else {
doextra(ptrunk + '.autorange', true);
parentIn.range = [1, 0];
}
if (parentFull.autorange) flags.calc = true;else flags.plot = true;
} else {
if (ai === 'dragmode' && (vi === false && vOld !== false || vi !== false && vOld === false)) {
flags.plot = true;
} else if (fullLayout._has('scatter-like') && fullLayout._has('regl') && ai === 'dragmode' && (vi === 'lasso' || vi === 'select') && !(vOld === 'lasso' || vOld === 'select')) {
flags.plot = true;
} else if (fullLayout._has('gl2d')) {
flags.plot = true;
} else if (valObject) editTypes.update(flags, valObject);else flags.calc = true;
p.set(vi);
}
}
// now we've collected component edits - execute them all together
for (arrayStr in arrayEdits) {
var finished = manageArrays.applyContainerArrayChanges(gd, layoutNP(layout, arrayStr), arrayEdits[arrayStr], flags, layoutNP);
if (!finished) flags.plot = true;
}
// figure out if we need to recalculate axis constraints
for (var axId in rangesAltered) {
ax = Axes.getFromId(gd, axId);
var group = ax && ax._constraintGroup;
if (group) {
// Always recalc if we're changing constrained ranges.
// Otherwise it's possible to violate the constraints by
// specifying arbitrary ranges for all axes in the group.
// this way some ranges may expand beyond what's specified,
// as they do at first draw, to satisfy the constraints.
flags.calc = true;
for (var groupAxId in group) {
if (!rangesAltered[groupAxId]) {
Axes.getFromId(gd, groupAxId)._constraintShrinkable = true;
}
}
}
}
// If the autosize changed or height or width was explicitly specified,
// this triggers a redraw
// TODO: do we really need special aobj.height/width handling here?
// couldn't editType do this?
if (updateAutosize(gd) || aobj.height || aobj.width) flags.plot = true;
// update shape legends
var shapes = fullLayout.shapes;
for (i = 0; i < shapes.length; i++) {
if (shapes[i].showlegend) {
flags.calc = true;
break;
}
}
if (flags.plot || flags.calc) {
flags.layoutReplot = true;
}
// now all attribute mods are done, as are
// redo and undo so we can save them
return {
flags: flags,
rangesAltered: rangesAltered,
undoit: undoit,
redoit: redoit,
eventData: eventData
};
}
/*
* updateAutosize: we made a change, does it change the autosize result?
* puts the new size into fullLayout
* returns true if either height or width changed
*/
function updateAutosize(gd) {
var fullLayout = gd._fullLayout;
var oldWidth = fullLayout.width;
var oldHeight = fullLayout.height;
// calculate autosizing
if (gd.layout.autosize) Plots.plotAutoSize(gd, gd.layout, fullLayout);
return fullLayout.width !== oldWidth || fullLayout.height !== oldHeight;
}
/**
* update: update trace and layout attributes of an existing plot
*
* @param {String | HTMLDivElement} gd
* the id or DOM element of the graph container div
* @param {Object} traceUpdate
* attribute object `{astr1: val1, astr2: val2 ...}`
* corresponding to updates in the plot's traces
* @param {Object} layoutUpdate
* attribute object `{astr1: val1, astr2: val2 ...}`
* corresponding to updates in the plot's layout
* @param {Number[] | Number} [traces]
* integer or array of integers for the traces to alter (all if omitted)
*
*/
function update(gd, traceUpdate, layoutUpdate, _traces) {
gd = Lib.getGraphDiv(gd);
helpers.clearPromiseQueue(gd);
if (!Lib.isPlainObject(traceUpdate)) traceUpdate = {};
if (!Lib.isPlainObject(layoutUpdate)) layoutUpdate = {};
if (Object.keys(traceUpdate).length) gd.changed = true;
if (Object.keys(layoutUpdate).length) gd.changed = true;
var traces = helpers.coerceTraceIndices(gd, _traces);
var restyleSpecs = _restyle(gd, Lib.extendFlat({}, traceUpdate), traces);
var restyleFlags = restyleSpecs.flags;
var relayoutSpecs = _relayout(gd, Lib.extendFlat({}, layoutUpdate));
var relayoutFlags = relayoutSpecs.flags;
// clear calcdata and/or axis types if required
if (restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
if (restyleFlags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, layoutUpdate);
// fill in redraw sequence
var seq = [];
if (relayoutFlags.layoutReplot) {
// N.B. works fine when both
// relayoutFlags.layoutReplot and restyleFlags.fullReplot are true
seq.push(subroutines.layoutReplot);
} else if (restyleFlags.fullReplot) {
seq.push(exports._doPlot);
} else {
seq.push(Plots.previousPromises);
axRangeSupplyDefaultsByPass(gd, relayoutFlags, relayoutSpecs) || Plots.supplyDefaults(gd);
if (restyleFlags.style) seq.push(subroutines.doTraceStyle);
if (restyleFlags.colorbars || relayoutFlags.colorbars) seq.push(subroutines.doColorBars);
if (relayoutFlags.legend) seq.push(subroutines.doLegend);
if (relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
if (relayoutFlags.axrange) addAxRangeSequence(seq, relayoutSpecs.rangesAltered);
if (relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
if (relayoutFlags.modebar) seq.push(subroutines.doModeBar);
if (relayoutFlags.camera) seq.push(subroutines.doCamera);
seq.push(emitAfterPlot);
}
seq.push(Plots.rehover, Plots.redrag, Plots.reselect);
Queue.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces]);
var plotDone = Lib.syncOrAsync(seq, gd);
if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
return plotDone.then(function () {
gd.emit('plotly_update', {
data: restyleSpecs.eventData,
layout: relayoutSpecs.eventData
});
return gd;
});
}
/*
* internal-use-only restyle/relayout/update variants that record the initial
* values in (fullLayout|fullTrace)._preGUI so changes can be persisted across
* Plotly.react data updates, dependent on uirevision attributes
*/
function guiEdit(func) {
return function wrappedEdit(gd) {
gd._fullLayout._guiEditing = true;
var p = func.apply(null, arguments);
gd._fullLayout._guiEditing = false;
return p;
};
}
// For connecting edited layout attributes to uirevision attrs
// If no `attr` we use `match[1] + '.uirevision'`
// Ordered by most common edits first, to minimize our search time
var layoutUIControlPatterns = [{
pattern: /^hiddenlabels/,
attr: 'legend.uirevision'
}, {
pattern: /^((x|y)axis\d*)\.((auto)?range|title\.text)/
},
// showspikes and modes include those nested inside scenes
{
pattern: /axis\d*\.showspikes$/,
attr: 'modebar.uirevision'
}, {
pattern: /(hover|drag)mode$/,
attr: 'modebar.uirevision'
}, {
pattern: /^(scene\d*)\.camera/
}, {
pattern: /^(geo\d*)\.(projection|center|fitbounds)/
}, {
pattern: /^(ternary\d*\.[abc]axis)\.(min|title\.text)$/
}, {
pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/
}, {
pattern: /^(polar\d*\.angularaxis)\.rotation/
}, {
pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/
}, {
pattern: /^legend\.(x|y)$/,
attr: 'editrevision'
}, {
pattern: /^(shapes|annotations)/,
attr: 'editrevision'
}, {
pattern: /^title\.text$/,
attr: 'editrevision'
}];
// same for trace attributes: if `attr` is given it's in layout,
// or with no `attr` we use `trace.uirevision`
var traceUIControlPatterns = [{
pattern: /^selectedpoints$/,
attr: 'selectionrevision'
},
// "visible" includes trace.transforms[i].styles[j].value.visible
{
pattern: /(^|value\.)visible$/,
attr: 'legend.uirevision'
}, {
pattern: /^dimensions\[\d+\]\.constraintrange/
}, {
pattern: /^node\.(x|y|groups)/
},
// for Sankey nodes
{
pattern: /^level$/
},
// for Sunburst, Treemap and Icicle traces
// below this you must be in editable: true mode
// TODO: I still put name and title with `trace.uirevision`
// reasonable or should these be `editrevision`?
// Also applies to axis titles up in the layout section
// "name" also includes transform.styles
{
pattern: /(^|value\.)name$/
},
// including nested colorbar attributes (ie marker.colorbar)
{
pattern: /colorbar\.title\.text$/
}, {
pattern: /colorbar\.(x|y)$/,
attr: 'editrevision'
}];
function findUIPattern(key, patternSpecs) {
for (var i = 0; i < patternSpecs.length; i++) {
var spec = patternSpecs[i];
var match = key.match(spec.pattern);
if (match) {
var head = match[1] || '';
return {
head: head,
tail: key.substr(head.length + 1),
attr: spec.attr
};
}
}
}
// We're finding the new uirevision before supplyDefaults, so do the
// inheritance manually. Note that only `undefined` inherits - other
// falsy values are returned.
function getNewRev(revAttr, container) {
var newRev = nestedProperty(container, revAttr).get();
if (newRev !== undefined) return newRev;
var parts = revAttr.split('.');
parts.pop();
while (parts.length > 1) {
parts.pop();
newRev = nestedProperty(container, parts.join('.') + '.uirevision').get();
if (newRev !== undefined) return newRev;
}
return container.uirevision;
}
function getFullTraceIndexFromUid(uid, fullData) {
for (var i = 0; i < fullData.length; i++) {
if (fullData[i]._fullInput.uid === uid) return i;
}
return -1;
}
function getTraceIndexFromUid(uid, data, tracei) {
for (var i = 0; i < data.length; i++) {
if (data[i].uid === uid) return i;
}
// fall back on trace order, but only if user didn't provide a uid for that trace
return !data[tracei] || data[tracei].uid ? -1 : tracei;
}
function valsMatch(v1, v2) {
var v1IsObj = Lib.isPlainObject(v1);
var v1IsArray = Array.isArray(v1);
if (v1IsObj || v1IsArray) {
return (v1IsObj && Lib.isPlainObject(v2) || v1IsArray && Array.isArray(v2)) && JSON.stringify(v1) === JSON.stringify(v2);
}
return v1 === v2;
}
function applyUIRevisions(data, layout, oldFullData, oldFullLayout) {
var layoutPreGUI = oldFullLayout._preGUI;
var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal, head, tail;
var bothInheritAutorange = [];
var newAutorangeIn = {};
var newRangeAccepted = {};
for (key in layoutPreGUI) {
match = findUIPattern(key, layoutUIControlPatterns);
if (match) {
head = match.head;
tail = match.tail;
revAttr = match.attr || head + '.uirevision';
oldRev = nestedProperty(oldFullLayout, revAttr).get();
newRev = oldRev && getNewRev(revAttr, layout);
if (newRev && newRev === oldRev) {
preGUIVal = layoutPreGUI[key];
if (preGUIVal === null) preGUIVal = undefined;
newNP = nestedProperty(layout, key);
newVal = newNP.get();
if (valsMatch(newVal, preGUIVal)) {
if (newVal === undefined && tail === 'autorange') {
bothInheritAutorange.push(head);
}
newNP.set(undefinedToNull(nestedProperty(oldFullLayout, key).get()));
continue;
} else if (tail === 'autorange' || tail.substr(0, 6) === 'range[') {
// Special case for (auto)range since we push it back into the layout
// so all null should be treated equivalently to autorange: true with any range
var pre0 = layoutPreGUI[head + '.range[0]'];
var pre1 = layoutPreGUI[head + '.range[1]'];
var preAuto = layoutPreGUI[head + '.autorange'];
if (preAuto || preAuto === null && pre0 === null && pre1 === null) {
// Only read the input layout once and stash the result,
// so we get it before we start modifying it
if (!(head in newAutorangeIn)) {
var newContainer = nestedProperty(layout, head).get();
newAutorangeIn[head] = newContainer && (newContainer.autorange || newContainer.autorange !== false && (!newContainer.range || newContainer.range.length !== 2));
}
if (newAutorangeIn[head]) {
newNP.set(undefinedToNull(nestedProperty(oldFullLayout, key).get()));
continue;
}
}
}
}
} else {
Lib.warn('unrecognized GUI edit: ' + key);
}
// if we got this far, the new value was accepted as the new starting
// point (either because it changed or revision changed)
// so remove it from _preGUI for next time.
delete layoutPreGUI[key];
if (match && match.tail.substr(0, 6) === 'range[') {
newRangeAccepted[match.head] = 1;
}
}
// More special logic for `autorange`, since it interacts with `range`:
// If the new figure's matching `range` was kept, and `autorange`
// wasn't supplied explicitly in either the original or the new figure,
// we shouldn't alter that - but we may just have done that, so fix it.
for (var i = 0; i < bothInheritAutorange.length; i++) {
var axAttr = bothInheritAutorange[i];
if (newRangeAccepted[axAttr]) {
var newAx = nestedProperty(layout, axAttr).get();
if (newAx) delete newAx.autorange;
}
}
// Now traces - try to match them up by uid (in case we added/deleted in
// the middle), then fall back on index.
var allTracePreGUI = oldFullLayout._tracePreGUI;
for (var uid in allTracePreGUI) {
var tracePreGUI = allTracePreGUI[uid];
var newTrace = null;
var fullInput;
for (key in tracePreGUI) {
// wait until we know we have preGUI values to look for traces
// but if we don't find both, stop looking at this uid
if (!newTrace) {
var fulli = getFullTraceIndexFromUid(uid, oldFullData);
if (fulli < 0) {
// Somehow we didn't even have this trace in oldFullData...
// I guess this could happen with `deleteTraces` or something
delete allTracePreGUI[uid];
break;
}
var fullTrace = oldFullData[fulli];
fullInput = fullTrace._fullInput;
var newTracei = getTraceIndexFromUid(uid, data, fullInput.index);
if (newTracei < 0) {
// No match in new data
delete allTracePreGUI[uid];
break;
}
newTrace = data[newTracei];
}
match = findUIPattern(key, traceUIControlPatterns);
if (match) {
if (match.attr) {
oldRev = nestedProperty(oldFullLayout, match.attr).get();
newRev = oldRev && getNewRev(match.attr, layout);
} else {
oldRev = fullInput.uirevision;
// inheritance for trace.uirevision is simple, just layout.uirevision
newRev = newTrace.uirevision;
if (newRev === undefined) newRev = layout.uirevision;
}
if (newRev && newRev === oldRev) {
preGUIVal = tracePreGUI[key];
if (preGUIVal === null) preGUIVal = undefined;
newNP = nestedProperty(newTrace, key);
newVal = newNP.get();
if (valsMatch(newVal, preGUIVal)) {
newNP.set(undefinedToNull(nestedProperty(fullInput, key).get()));
continue;
}
}
} else {
Lib.warn('unrecognized GUI edit: ' + key + ' in trace uid ' + uid);
}
delete tracePreGUI[key];
}
}
}
/**
* Plotly.react:
* A plot/update method that takes the full plot state (same API as plot/newPlot)
* and diffs to determine the minimal update pathway
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
* @param {array of objects} data
* array of traces, containing the data and display information for each trace
* @param {object} layout
* object describing the overall display of the plot,
* all the stuff that doesn't pertain to any individual trace
* @param {object} config
* configuration options (see ./plot_config.js for more info)
*
* OR
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
* @param {object} figure
* object containing `data`, `layout`, `config`, and `frames` members
*
*/
function react(gd, data, layout, config) {
var frames, plotDone;
function addFrames() {
return exports.addFrames(gd, frames);
}
gd = Lib.getGraphDiv(gd);
helpers.clearPromiseQueue(gd);
var oldFullData = gd._fullData;
var oldFullLayout = gd._fullLayout;
// you can use this as the initial draw as well as to update
if (!Lib.isPlotDiv(gd) || !oldFullData || !oldFullLayout) {
plotDone = exports.newPlot(gd, data, layout, config);
} else {
if (Lib.isPlainObject(data)) {
var obj = data;
data = obj.data;
layout = obj.layout;
config = obj.config;
frames = obj.frames;
}
var configChanged = false;
// assume that if there's a config at all, we're reacting to it too,
// and completely replace the previous config
if (config) {
var oldConfig = Lib.extendDeep({}, gd._context);
gd._context = undefined;
setPlotContext(gd, config);
configChanged = diffConfig(oldConfig, gd._context);
}
gd.data = data || [];
helpers.cleanData(gd.data);
gd.layout = layout || {};
helpers.cleanLayout(gd.layout);
applyUIRevisions(gd.data, gd.layout, oldFullData, oldFullLayout);
// "true" skips updating calcdata and remapping arrays from calcTransforms,
// which supplyDefaults usually does at the end, but we may need to NOT do
// if the diff (which we haven't determined yet) says we'll recalc
Plots.supplyDefaults(gd, {
skipUpdateCalc: true
});
var newFullData = gd._fullData;
var newFullLayout = gd._fullLayout;
var immutable = newFullLayout.datarevision === undefined;
var transition = newFullLayout.transition;
var relayoutFlags = diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition);
var newDataRevision = relayoutFlags.newDataRevision;
var restyleFlags = diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision);
// TODO: how to translate this part of relayout to Plotly.react?
// // Setting width or height to null must reset the graph's width / height
// // back to its initial value as computed during the first pass in Plots.plotAutoSize.
// //
// // To do so, we must manually set them back here using the _initialAutoSize cache.
// if(['width', 'height'].indexOf(ai) !== -1 && vi === null) {
// fullLayout[ai] = gd._initialAutoSize[ai];
// }
if (updateAutosize(gd)) relayoutFlags.layoutReplot = true;
// clear calcdata and empty categories if required
if (restyleFlags.calc || relayoutFlags.calc) {
gd.calcdata = undefined;
var allNames = Object.getOwnPropertyNames(newFullLayout);
for (var q = 0; q < allNames.length; q++) {
var name = allNames[q];
var start = name.substring(0, 5);
if (start === 'xaxis' || start === 'yaxis') {
var emptyCategories = newFullLayout[name]._emptyCategories;
if (emptyCategories) emptyCategories();
}
}
// otherwise do the calcdata updates and calcTransform array remaps that we skipped earlier
} else {
Plots.supplyDefaultsUpdateCalc(gd.calcdata, newFullData);
}
// Note: what restyle/relayout use impliedEdits and clearAxisTypes for
// must be handled by the user when using Plotly.react.
// fill in redraw sequence
var seq = [];
if (frames) {
gd._transitionData = {};
Plots.createTransitionData(gd);
seq.push(addFrames);
}
// Transition pathway,
// only used when 'transition' is set by user and
// when at least one animatable attribute has changed,
// N.B. config changed aren't animatable
if (newFullLayout.transition && !configChanged && (restyleFlags.anim || relayoutFlags.anim)) {
if (relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
Plots.doCalcdata(gd);
subroutines.doAutoRangeAndConstraints(gd);
seq.push(function () {
return Plots.transitionFromReact(gd, restyleFlags, relayoutFlags, oldFullLayout);
});
} else if (restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) {
gd._fullLayout._skipDefaults = true;
seq.push(exports._doPlot);
} else {
for (var componentType in relayoutFlags.arrays) {
var indices = relayoutFlags.arrays[componentType];
if (indices.length) {
var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
if (drawOne !== Lib.noop) {
for (var i = 0; i < indices.length; i++) {
drawOne(gd, indices[i]);
}
} else {
var draw = Registry.getComponentMethod(componentType, 'draw');
if (draw === Lib.noop) {
throw new Error('cannot draw components: ' + componentType);
}
draw(gd);
}
}
}
seq.push(Plots.previousPromises);
if (restyleFlags.style) seq.push(subroutines.doTraceStyle);
if (restyleFlags.colorbars || relayoutFlags.colorbars) seq.push(subroutines.doColorBars);
if (relayoutFlags.legend) seq.push(subroutines.doLegend);
if (relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
if (relayoutFlags.axrange) addAxRangeSequence(seq);
if (relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
if (relayoutFlags.modebar) seq.push(subroutines.doModeBar);
if (relayoutFlags.camera) seq.push(subroutines.doCamera);
seq.push(emitAfterPlot);
}
seq.push(Plots.rehover, Plots.redrag, Plots.reselect);
plotDone = Lib.syncOrAsync(seq, gd);
if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
}
return plotDone.then(function () {
gd.emit('plotly_react', {
data: data,
layout: layout
});
return gd;
});
}
function diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision) {
var sameTraceLength = oldFullData.length === newFullData.length;
if (!transition && !sameTraceLength) {
return {
fullReplot: true,
calc: true
};
}
var flags = editTypes.traceFlags();
flags.arrays = {};
flags.nChanges = 0;
flags.nChangesAnim = 0;
var i, trace;
function getTraceValObject(parts) {
var out = PlotSchema.getTraceValObject(trace, parts);
if (!trace._module.animatable && out.anim) {
out.anim = false;
}
return out;
}
var diffOpts = {
getValObject: getTraceValObject,
flags: flags,
immutable: immutable,
transition: transition,
newDataRevision: newDataRevision,
gd: gd
};
var seenUIDs = {};
for (i = 0; i < oldFullData.length; i++) {
if (newFullData[i]) {
trace = newFullData[i]._fullInput;
if (Plots.hasMakesDataTransform(trace)) trace = newFullData[i];
if (seenUIDs[trace.uid]) continue;
seenUIDs[trace.uid] = 1;
getDiffFlags(oldFullData[i]._fullInput, trace, [], diffOpts);
}
}
if (flags.calc || flags.plot) {
flags.fullReplot = true;
}
if (transition && flags.nChanges && flags.nChangesAnim) {
flags.anim = flags.nChanges === flags.nChangesAnim && sameTraceLength ? 'all' : 'some';
}
return flags;
}
function diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition) {
var flags = editTypes.layoutFlags();
flags.arrays = {};
flags.rangesAltered = {};
flags.nChanges = 0;
flags.nChangesAnim = 0;
function getLayoutValObject(parts) {
return PlotSchema.getLayoutValObject(newFullLayout, parts);
}
var diffOpts = {
getValObject: getLayoutValObject,
flags: flags,
immutable: immutable,
transition: transition,
gd: gd
};
getDiffFlags(oldFullLayout, newFullLayout, [], diffOpts);
if (flags.plot || flags.calc) {
flags.layoutReplot = true;
}
if (transition && flags.nChanges && flags.nChangesAnim) {
flags.anim = flags.nChanges === flags.nChangesAnim ? 'all' : 'some';
}
return flags;
}
function getDiffFlags(oldContainer, newContainer, outerparts, opts) {
var valObject, key, astr;
var getValObject = opts.getValObject;
var flags = opts.flags;
var immutable = opts.immutable;
var inArray = opts.inArray;
var arrayIndex = opts.arrayIndex;
function changed() {
var editType = valObject.editType;
if (inArray && editType.indexOf('arraydraw') !== -1) {
Lib.pushUnique(flags.arrays[inArray], arrayIndex);
return;
}
editTypes.update(flags, valObject);
if (editType !== 'none') {
flags.nChanges++;
}
// track animatable changes
if (opts.transition && valObject.anim) {
flags.nChangesAnim++;
}
// track cartesian axes with altered ranges
if (AX_RANGE_RE.test(astr) || AX_AUTORANGE_RE.test(astr)) {
flags.rangesAltered[outerparts[0]] = 1;
}
// clear _inputDomain on cartesian axes with altered domains
if (AX_DOMAIN_RE.test(astr)) {
nestedProperty(newContainer, '_inputDomain').set(null);
}
// track datarevision changes
if (key === 'datarevision') {
flags.newDataRevision = 1;
}
}
function valObjectCanBeDataArray(valObject) {
return valObject.valType === 'data_array' || valObject.arrayOk;
}
for (key in oldContainer) {
// short-circuit based on previous calls or previous keys that already maximized the pathway
if (flags.calc && !opts.transition) return;
var oldVal = oldContainer[key];
var newVal = newContainer[key];
var parts = outerparts.concat(key);
astr = parts.join('.');
if (key.charAt(0) === '_' || typeof oldVal === 'function' || oldVal === newVal) continue;
// FIXME: ax.tick0 and dtick get filled in during plotting (except for geo subplots),
// and unlike other auto values they don't make it back into the input,
// so newContainer won't have them.
if ((key === 'tick0' || key === 'dtick') && outerparts[0] !== 'geo') {
var tickMode = newContainer.tickmode;
if (tickMode === 'auto' || tickMode === 'array' || !tickMode) continue;
}
// FIXME: Similarly for axis ranges for 3D
// contourcarpet doesn't HAVE zmin/zmax, they're just auto-added. It needs them.
if (key === 'range' && newContainer.autorange) continue;
if ((key === 'zmin' || key === 'zmax') && newContainer.type === 'contourcarpet') continue;
valObject = getValObject(parts);
// in case type changed, we may not even *have* a valObject.
if (!valObject) continue;
if (valObject._compareAsJSON && JSON.stringify(oldVal) === JSON.stringify(newVal)) continue;
var valType = valObject.valType;
var i;
var canBeDataArray = valObjectCanBeDataArray(valObject);
var wasArray = Array.isArray(oldVal);
var nowArray = Array.isArray(newVal);
// hack for traces that modify the data in supplyDefaults, like
// converting 1D to 2D arrays, which will always create new objects
if (wasArray && nowArray) {
var inputKey = '_input_' + key;
var oldValIn = oldContainer[inputKey];
var newValIn = newContainer[inputKey];
if (Array.isArray(oldValIn) && oldValIn === newValIn) continue;
}
if (newVal === undefined) {
if (canBeDataArray && wasArray) flags.calc = true;else changed();
} else if (valObject._isLinkedToArray) {
var arrayEditIndices = [];
var extraIndices = false;
if (!inArray) flags.arrays[key] = arrayEditIndices;
var minLen = Math.min(oldVal.length, newVal.length);
var maxLen = Math.max(oldVal.length, newVal.length);
if (minLen !== maxLen) {
if (valObject.editType === 'arraydraw') {
extraIndices = true;
} else {
changed();
continue;
}
}
for (i = 0; i < minLen; i++) {
getDiffFlags(oldVal[i], newVal[i], parts.concat(i),
// add array indices, but not if we're already in an array
Lib.extendFlat({
inArray: key,
arrayIndex: i
}, opts));
}
// put this at the end so that we know our collected array indices are sorted
// but the check for length changes happens up front so we can short-circuit
// diffing if appropriate
if (extraIndices) {
for (i = minLen; i < maxLen; i++) {
arrayEditIndices.push(i);
}
}
} else if (!valType && Lib.isPlainObject(oldVal)) {
getDiffFlags(oldVal, newVal, parts, opts);
} else if (canBeDataArray) {
if (wasArray && nowArray) {
// don't try to diff two data arrays. If immutable we know the data changed,
// if not, assume it didn't and let `layout.datarevision` tell us if it did
if (immutable) {
flags.calc = true;
}
// look for animatable attributes when the data changed
if (immutable || opts.newDataRevision) {
changed();
}
} else if (wasArray !== nowArray) {
flags.calc = true;
} else changed();
} else if (wasArray && nowArray) {
// info array, colorscale, 'any' - these are short, just stringify.
// I don't *think* that covers up any real differences post-validation, does it?
// otherwise we need to dive in 1 (info_array) or 2 (colorscale) levels and compare
// all elements.
if (oldVal.length !== newVal.length || String(oldVal) !== String(newVal)) {
changed();
}
} else {
changed();
}
}
for (key in newContainer) {
if (!(key in oldContainer || key.charAt(0) === '_' || typeof newContainer[key] === 'function')) {
valObject = getValObject(outerparts.concat(key));
if (valObjectCanBeDataArray(valObject) && Array.isArray(newContainer[key])) {
flags.calc = true;
return;
} else changed();
}
}
}
/*
* simple diff for config - for now, just treat all changes as equivalent
*/
function diffConfig(oldConfig, newConfig) {
var key;
for (key in oldConfig) {
if (key.charAt(0) === '_') continue;
var oldVal = oldConfig[key];
var newVal = newConfig[key];
if (oldVal !== newVal) {
if (Lib.isPlainObject(oldVal) && Lib.isPlainObject(newVal)) {
if (diffConfig(oldVal, newVal)) {
return true;
}
} else if (Array.isArray(oldVal) && Array.isArray(newVal)) {
if (oldVal.length !== newVal.length) {
return true;
}
for (var i = 0; i < oldVal.length; i++) {
if (oldVal[i] !== newVal[i]) {
if (Lib.isPlainObject(oldVal[i]) && Lib.isPlainObject(newVal[i])) {
if (diffConfig(oldVal[i], newVal[i])) {
return true;
}
} else {
return true;
}
}
}
} else {
return true;
}
}
}
}
/**
* Animate to a frame, sequence of frame, frame group, or frame definition
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
*
* @param {string or object or array of strings or array of objects} frameOrGroupNameOrFrameList
* a single frame, array of frames, or group to which to animate. The intent is
* inferred by the type of the input. Valid inputs are:
*
* - string, e.g. 'groupname': animate all frames of a given `group` in the order
* in which they are defined via `Plotly.addFrames`.
*
* - array of strings, e.g. ['frame1', frame2']: a list of frames by name to which
* to animate in sequence
*
* - object: {data: ...}: a frame definition to which to animate. The frame is not
* and does not need to be added via `Plotly.addFrames`. It may contain any of
* the properties of a frame, including `data`, `layout`, and `traces`. The
* frame is used as provided and does not use the `baseframe` property.
*
* - array of objects, e.g. [{data: ...}, {data: ...}]: a list of frame objects,
* each following the same rules as a single `object`.
*
* @param {object} animationOpts
* configuration for the animation
*/
function animate(gd, frameOrGroupNameOrFrameList, animationOpts) {
gd = Lib.getGraphDiv(gd);
if (!Lib.isPlotDiv(gd)) {
throw new Error('This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + 'https://plotly.com/javascript/animations/');
}
var trans = gd._transitionData;
// This is the queue of frames that will be animated as soon as possible. They
// are popped immediately upon the *start* of a transition:
if (!trans._frameQueue) {
trans._frameQueue = [];
}
animationOpts = Plots.supplyAnimationDefaults(animationOpts);
var transitionOpts = animationOpts.transition;
var frameOpts = animationOpts.frame;
// Since frames are popped immediately, an empty queue only means all frames have
// *started* to transition, not that the animation is complete. To solve that,
// track a separate counter that increments at the same time as frames are added
// to the queue, but decrements only when the transition is complete.
if (trans._frameWaitingCnt === undefined) {
trans._frameWaitingCnt = 0;
}
function getTransitionOpts(i) {
if (Array.isArray(transitionOpts)) {
if (i >= transitionOpts.length) {
return transitionOpts[0];
} else {
return transitionOpts[i];
}
} else {
return transitionOpts;
}
}
function getFrameOpts(i) {
if (Array.isArray(frameOpts)) {
if (i >= frameOpts.length) {
return frameOpts[0];
} else {
return frameOpts[i];
}
} else {
return frameOpts;
}
}
// Execute a callback after the wrapper function has been called n times.
// This is used to defer the resolution until a transition has resolved *and*
// the frame has completed. If it's not done this way, then we get a race
// condition in which the animation might resolve before a transition is complete
// or vice versa.
function callbackOnNthTime(cb, n) {
var cnt = 0;
return function () {
if (cb && ++cnt === n) {
return cb();
}
};
}
return new Promise(function (resolve, reject) {
function discardExistingFrames() {
if (trans._frameQueue.length === 0) {
return;
}
while (trans._frameQueue.length) {
var next = trans._frameQueue.pop();
if (next.onInterrupt) {
next.onInterrupt();
}
}
gd.emit('plotly_animationinterrupted', []);
}
function queueFrames(frameList) {
if (frameList.length === 0) return;
for (var i = 0; i < frameList.length; i++) {
var computedFrame;
if (frameList[i].type === 'byname') {
// If it's a named frame, compute it:
computedFrame = Plots.computeFrame(gd, frameList[i].name);
} else {
// Otherwise we must have been given a simple object, so treat
// the input itself as the computed frame.
computedFrame = frameList[i].data;
}
var frameOpts = getFrameOpts(i);
var transitionOpts = getTransitionOpts(i);
// It doesn't make much sense for the transition duration to be greater than
// the frame duration, so limit it:
transitionOpts.duration = Math.min(transitionOpts.duration, frameOpts.duration);
var nextFrame = {
frame: computedFrame,
name: frameList[i].name,
frameOpts: frameOpts,
transitionOpts: transitionOpts
};
if (i === frameList.length - 1) {
// The last frame in this .animate call stores the promise resolve
// and reject callbacks. This is how we ensure that the animation
// loop (which may exist as a result of a *different* .animate call)
// still resolves or rejecdts this .animate call's promise. once it's
// complete.
nextFrame.onComplete = callbackOnNthTime(resolve, 2);
nextFrame.onInterrupt = reject;
}
trans._frameQueue.push(nextFrame);
}
// Set it as never having transitioned to a frame. This will cause the animation
// loop to immediately transition to the next frame (which, for immediate mode,
// is the first frame in the list since all others would have been discarded
// below)
if (animationOpts.mode === 'immediate') {
trans._lastFrameAt = -Infinity;
}
// Only it's not already running, start a RAF loop. This could be avoided in the
// case that there's only one frame, but it significantly complicated the logic
// and only sped things up by about 5% or so for a lorenz attractor simulation.
// It would be a fine thing to implement, but the benefit of that optimization
// doesn't seem worth the extra complexity.
if (!trans._animationRaf) {
beginAnimationLoop();
}
}
function stopAnimationLoop() {
gd.emit('plotly_animated');
// Be sure to unset also since it's how we know whether a loop is already running:
window.cancelAnimationFrame(trans._animationRaf);
trans._animationRaf = null;
}
function nextFrame() {
if (trans._currentFrame && trans._currentFrame.onComplete) {
// Execute the callback and unset it to ensure it doesn't
// accidentally get called twice
trans._currentFrame.onComplete();
}
var newFrame = trans._currentFrame = trans._frameQueue.shift();
if (newFrame) {
// Since it's sometimes necessary to do deep digging into frame data,
// we'll consider it not 100% impossible for nulls or numbers to sneak through,
// so check when casting the name, just to be absolutely certain:
var stringName = newFrame.name ? newFrame.name.toString() : null;
gd._fullLayout._currentFrame = stringName;
trans._lastFrameAt = Date.now();
trans._timeToNext = newFrame.frameOpts.duration;
// This is simply called and it's left to .transition to decide how to manage
// interrupting current transitions. That means we don't need to worry about
// how it resolves or what happens after this:
Plots.transition(gd, newFrame.frame.data, newFrame.frame.layout, helpers.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts).then(function () {
if (newFrame.onComplete) {
newFrame.onComplete();
}
});
gd.emit('plotly_animatingframe', {
name: stringName,
frame: newFrame.frame,
animation: {
frame: newFrame.frameOpts,
transition: newFrame.transitionOpts
}
});
} else {
// If there are no more frames, then stop the RAF loop:
stopAnimationLoop();
}
}
function beginAnimationLoop() {
gd.emit('plotly_animating');
// If no timer is running, then set last frame = long ago so that the next
// frame is immediately transitioned:
trans._lastFrameAt = -Infinity;
trans._timeToNext = 0;
trans._runningTransitions = 0;
trans._currentFrame = null;
var doFrame = function () {
// This *must* be requested before nextFrame since nextFrame may decide
// to cancel it if there's nothing more to animated:
trans._animationRaf = window.requestAnimationFrame(doFrame);
// Check if we're ready for a new frame:
if (Date.now() - trans._lastFrameAt > trans._timeToNext) {
nextFrame();
}
};
doFrame();
}
// This is an animate-local counter that helps match up option input list
// items with the particular frame.
var configCounter = 0;
function setTransitionConfig(frame) {
if (Array.isArray(transitionOpts)) {
if (configCounter >= transitionOpts.length) {
frame.transitionOpts = transitionOpts[configCounter];
} else {
frame.transitionOpts = transitionOpts[0];
}
} else {
frame.transitionOpts = transitionOpts;
}
configCounter++;
return frame;
}
// Disambiguate what's sort of frames have been received
var i, frame;
var frameList = [];
var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null;
var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList);
var isSingleFrame = !allFrames && !isFrameArray && Lib.isPlainObject(frameOrGroupNameOrFrameList);
if (isSingleFrame) {
// In this case, a simple object has been passed to animate.
frameList.push({
type: 'object',
data: setTransitionConfig(Lib.extendFlat({}, frameOrGroupNameOrFrameList))
});
} else if (allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) {
// In this case, null or undefined has been passed so that we want to
// animate *all* currently defined frames
for (i = 0; i < trans._frames.length; i++) {
frame = trans._frames[i];
if (!frame) continue;
if (allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) {
frameList.push({
type: 'byname',
name: String(frame.name),
data: setTransitionConfig({
name: frame.name
})
});
}
}
} else if (isFrameArray) {
for (i = 0; i < frameOrGroupNameOrFrameList.length; i++) {
var frameOrName = frameOrGroupNameOrFrameList[i];
if (['number', 'string'].indexOf(typeof frameOrName) !== -1) {
frameOrName = String(frameOrName);
// In this case, there's an array and this frame is a string name:
frameList.push({
type: 'byname',
name: frameOrName,
data: setTransitionConfig({
name: frameOrName
})
});
} else if (Lib.isPlainObject(frameOrName)) {
frameList.push({
type: 'object',
data: setTransitionConfig(Lib.extendFlat({}, frameOrName))
});
}
}
}
// Verify that all of these frames actually exist; return and reject if not:
for (i = 0; i < frameList.length; i++) {
frame = frameList[i];
if (frame.type === 'byname' && !trans._frameHash[frame.data.name]) {
Lib.warn('animate failure: frame not found: "' + frame.data.name + '"');
reject();
return;
}
}
// If the mode is either next or immediate, then all currently queued frames must
// be dumped and the corresponding .animate promises rejected.
if (['next', 'immediate'].indexOf(animationOpts.mode) !== -1) {
discardExistingFrames();
}
if (animationOpts.direction === 'reverse') {
frameList.reverse();
}
var currentFrame = gd._fullLayout._currentFrame;
if (currentFrame && animationOpts.fromcurrent) {
var idx = -1;
for (i = 0; i < frameList.length; i++) {
frame = frameList[i];
if (frame.type === 'byname' && frame.name === currentFrame) {
idx = i;
break;
}
}
if (idx > 0 && idx < frameList.length - 1) {
var filteredFrameList = [];
for (i = 0; i < frameList.length; i++) {
frame = frameList[i];
if (frameList[i].type !== 'byname' || i > idx) {
filteredFrameList.push(frame);
}
}
frameList = filteredFrameList;
}
}
if (frameList.length > 0) {
queueFrames(frameList);
} else {
// This is the case where there were simply no frames. It's a little strange
// since there's not much to do:
gd.emit('plotly_animated');
resolve();
}
});
}
/**
* Register new frames
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
*
* @param {array of objects} frameList
* list of frame definitions, in which each object includes any of:
* - name: {string} name of frame to add
* - data: {array of objects} trace data
* - layout {object} layout definition
* - traces {array} trace indices
* - baseframe {string} name of frame from which this frame gets defaults
*
* @param {array of integers} indices
* an array of integer indices matching the respective frames in `frameList`. If not
* provided, an index will be provided in serial order. If already used, the frame
* will be overwritten.
*/
function addFrames(gd, frameList, indices) {
gd = Lib.getGraphDiv(gd);
if (frameList === null || frameList === undefined) {
return Promise.resolve();
}
if (!Lib.isPlotDiv(gd)) {
throw new Error('This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + 'https://plotly.com/javascript/animations/');
}
var i, frame, j, idx;
var _frames = gd._transitionData._frames;
var _frameHash = gd._transitionData._frameHash;
if (!Array.isArray(frameList)) {
throw new Error('addFrames failure: frameList must be an Array of frame definitions' + frameList);
}
// Create a sorted list of insertions since we run into lots of problems if these
// aren't in ascending order of index:
//
// Strictly for sorting. Make sure this is guaranteed to never collide with any
// already-exisisting indices:
var bigIndex = _frames.length + frameList.length * 2;
var insertions = [];
var _frameHashLocal = {};
for (i = frameList.length - 1; i >= 0; i--) {
if (!Lib.isPlainObject(frameList[i])) continue;
// The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and
// use a Map instead of an Object instance, as Map keys aren't converted to strings.
var lookupName = frameList[i].name;
var name = (_frameHash[lookupName] || _frameHashLocal[lookupName] || {}).name;
var newName = frameList[i].name;
var collisionPresent = _frameHash[name] || _frameHashLocal[name];
if (name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) {
numericNameWarningCount++;
Lib.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.');
if (numericNameWarningCount === numericNameWarningCountLimit) {
Lib.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.');
}
}
_frameHashLocal[lookupName] = {
name: lookupName
};
insertions.push({
frame: Plots.supplyFrameDefaults(frameList[i]),
index: indices && indices[i] !== undefined && indices[i] !== null ? indices[i] : bigIndex + i
});
}
// Sort this, taking note that undefined insertions end up at the end:
insertions.sort(function (a, b) {
if (a.index > b.index) return -1;
if (a.index < b.index) return 1;
return 0;
});
var ops = [];
var revops = [];
var frameCount = _frames.length;
for (i = insertions.length - 1; i >= 0; i--) {
frame = insertions[i].frame;
if (typeof frame.name === 'number') {
Lib.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings');
}
if (!frame.name) {
// Repeatedly assign a default name, incrementing the counter each time until
// we get a name that's not in the hashed lookup table:
while (_frameHash[frame.name = 'frame ' + gd._transitionData._counter++]);
}
if (_frameHash[frame.name]) {
// If frame is present, overwrite its definition:
for (j = 0; j < _frames.length; j++) {
if ((_frames[j] || {}).name === frame.name) break;
}
ops.push({
type: 'replace',
index: j,
value: frame
});
revops.unshift({
type: 'replace',
index: j,
value: _frames[j]
});
} else {
// Otherwise insert it at the end of the list:
idx = Math.max(0, Math.min(insertions[i].index, frameCount));
ops.push({
type: 'insert',
index: idx,
value: frame
});
revops.unshift({
type: 'delete',
index: idx
});
frameCount++;
}
}
var undoFunc = Plots.modifyFrames;
var redoFunc = Plots.modifyFrames;
var undoArgs = [gd, revops];
var redoArgs = [gd, ops];
if (Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
return Plots.modifyFrames(gd, ops);
}
/**
* Delete frame
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
*
* @param {array of integers} frameList
* list of integer indices of frames to be deleted
*/
function deleteFrames(gd, frameList) {
gd = Lib.getGraphDiv(gd);
if (!Lib.isPlotDiv(gd)) {
throw new Error('This element is not a Plotly plot: ' + gd);
}
var i, idx;
var _frames = gd._transitionData._frames;
var ops = [];
var revops = [];
if (!frameList) {
frameList = [];
for (i = 0; i < _frames.length; i++) {
frameList.push(i);
}
}
frameList = frameList.slice();
frameList.sort();
for (i = frameList.length - 1; i >= 0; i--) {
idx = frameList[i];
ops.push({
type: 'delete',
index: idx
});
revops.unshift({
type: 'insert',
index: idx,
value: _frames[idx]
});
}
var undoFunc = Plots.modifyFrames;
var redoFunc = Plots.modifyFrames;
var undoArgs = [gd, revops];
var redoArgs = [gd, ops];
if (Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
return Plots.modifyFrames(gd, ops);
}
/**
* Purge a graph container div back to its initial pre-_doPlot state
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
*/
function purge(gd) {
gd = Lib.getGraphDiv(gd);
var fullLayout = gd._fullLayout || {};
var fullData = gd._fullData || [];
// remove gl contexts
Plots.cleanPlot([], {}, fullData, fullLayout);
// purge properties
Plots.purge(gd);
// purge event emitter methods
Events.purge(gd);
// remove plot container
if (fullLayout._container) fullLayout._container.remove();
// in contrast to _doPlots.purge which does NOT clear _context!
delete gd._context;
return gd;
}
// determines if the graph div requires a recalculation of its inverse matrix transforms by comparing old + new bounding boxes.
function calcInverseTransform(gd) {
var fullLayout = gd._fullLayout;
var newBBox = gd.getBoundingClientRect();
if (Lib.equalDomRects(newBBox, fullLayout._lastBBox)) return;
var m = fullLayout._invTransform = Lib.inverseTransformMatrix(Lib.getFullTransformMatrix(gd));
fullLayout._invScaleX = Math.sqrt(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]);
fullLayout._invScaleY = Math.sqrt(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]);
fullLayout._lastBBox = newBBox;
}
// -------------------------------------------------------
// makePlotFramework: Create the plot container and axes
// -------------------------------------------------------
function makePlotFramework(gd) {
var gd3 = d3.select(gd);
var fullLayout = gd._fullLayout;
fullLayout._calcInverseTransform = calcInverseTransform;
fullLayout._calcInverseTransform(gd);
// Plot container
fullLayout._container = gd3.selectAll('.plot-container').data([0]);
fullLayout._container.enter().insert('div', ':first-child').classed('plot-container', true).classed('plotly', true);
// Make the svg container
fullLayout._paperdiv = fullLayout._container.selectAll('.svg-container').data([0]);
fullLayout._paperdiv.enter().append('div').classed('user-select-none', true).classed('svg-container', true).style('position', 'relative');
// Make the graph containers
// start fresh each time we get here, so we know the order comes out
// right, rather than enter/exit which can muck up the order
// TODO: sort out all the ordering so we don't have to
// explicitly delete anything
// FIXME: parcoords reuses this object, not the best pattern
fullLayout._glcontainer = fullLayout._paperdiv.selectAll('.gl-container').data([{}]);
fullLayout._glcontainer.enter().append('div').classed('gl-container', true);
fullLayout._paperdiv.selectAll('.main-svg').remove();
fullLayout._paperdiv.select('.modebar-container').remove();
fullLayout._paper = fullLayout._paperdiv.insert('svg', ':first-child').classed('main-svg', true);
fullLayout._toppaper = fullLayout._paperdiv.append('svg').classed('main-svg', true);
fullLayout._modebardiv = fullLayout._paperdiv.append('div');
delete fullLayout._modeBar;
fullLayout._hoverpaper = fullLayout._paperdiv.append('svg').classed('main-svg', true);
if (!fullLayout._uid) {
var otherUids = {};
d3.selectAll('defs').each(function () {
if (this.id) otherUids[this.id.split('-')[1]] = 1;
});
fullLayout._uid = Lib.randstr(otherUids);
}
fullLayout._paperdiv.selectAll('.main-svg').attr(xmlnsNamespaces.svgAttrs);
fullLayout._defs = fullLayout._paper.append('defs').attr('id', 'defs-' + fullLayout._uid);
fullLayout._clips = fullLayout._defs.append('g').classed('clips', true);
fullLayout._topdefs = fullLayout._toppaper.append('defs').attr('id', 'topdefs-' + fullLayout._uid);
fullLayout._topclips = fullLayout._topdefs.append('g').classed('clips', true);
fullLayout._bgLayer = fullLayout._paper.append('g').classed('bglayer', true);
fullLayout._draggers = fullLayout._paper.append('g').classed('draglayer', true);
// lower shape/image layer - note that this is behind
// all subplots data/grids but above the backgrounds
// except inset subplots, whose backgrounds are drawn
// inside their own group so that they appear above
// the data for the main subplot
// lower shapes and images which are fully referenced to
// a subplot still get drawn within the subplot's group
// so they will work correctly on insets
var layerBelow = fullLayout._paper.append('g').classed('layer-below', true);
fullLayout._imageLowerLayer = layerBelow.append('g').classed('imagelayer', true);
fullLayout._shapeLowerLayer = layerBelow.append('g').classed('shapelayer', true);
// single cartesian layer for the whole plot
fullLayout._cartesianlayer = fullLayout._paper.append('g').classed('cartesianlayer', true);
// single polar layer for the whole plot
fullLayout._polarlayer = fullLayout._paper.append('g').classed('polarlayer', true);
// single smith layer for the whole plot
fullLayout._smithlayer = fullLayout._paper.append('g').classed('smithlayer', true);
// single ternary layer for the whole plot
fullLayout._ternarylayer = fullLayout._paper.append('g').classed('ternarylayer', true);
// single geo layer for the whole plot
fullLayout._geolayer = fullLayout._paper.append('g').classed('geolayer', true);
// single funnelarea layer for the whole plot
fullLayout._funnelarealayer = fullLayout._paper.append('g').classed('funnelarealayer', true);
// single pie layer for the whole plot
fullLayout._pielayer = fullLayout._paper.append('g').classed('pielayer', true);
// single treemap layer for the whole plot
fullLayout._iciclelayer = fullLayout._paper.append('g').classed('iciclelayer', true);
// single treemap layer for the whole plot
fullLayout._treemaplayer = fullLayout._paper.append('g').classed('treemaplayer', true);
// single sunburst layer for the whole plot
fullLayout._sunburstlayer = fullLayout._paper.append('g').classed('sunburstlayer', true);
// single indicator layer for the whole plot
fullLayout._indicatorlayer = fullLayout._toppaper.append('g').classed('indicatorlayer', true);
// fill in image server scrape-svg
fullLayout._glimages = fullLayout._paper.append('g').classed('glimages', true);
// lastly upper shapes, info (legend, annotations) and hover layers go on top
// these are in a different svg element normally, but get collapsed into a single
// svg when exporting (after inserting 3D)
// upper shapes/images are only those drawn above the whole plot, including subplots
var layerAbove = fullLayout._toppaper.append('g').classed('layer-above', true);
fullLayout._imageUpperLayer = layerAbove.append('g').classed('imagelayer', true);
fullLayout._shapeUpperLayer = layerAbove.append('g').classed('shapelayer', true);
fullLayout._selectionLayer = fullLayout._toppaper.append('g').classed('selectionlayer', true);
fullLayout._infolayer = fullLayout._toppaper.append('g').classed('infolayer', true);
fullLayout._menulayer = fullLayout._toppaper.append('g').classed('menulayer', true);
fullLayout._zoomlayer = fullLayout._toppaper.append('g').classed('zoomlayer', true);
fullLayout._hoverlayer = fullLayout._hoverpaper.append('g').classed('hoverlayer', true);
// Make the modebar container
fullLayout._modebardiv.classed('modebar-container', true).style('position', 'absolute').style('top', '0px').style('right', '0px');
gd.emit('plotly_framework');
}
exports.animate = animate;
exports.addFrames = addFrames;
exports.deleteFrames = deleteFrames;
exports.addTraces = addTraces;
exports.deleteTraces = deleteTraces;
exports.extendTraces = extendTraces;
exports.moveTraces = moveTraces;
exports.prependTraces = prependTraces;
exports.newPlot = newPlot;
exports._doPlot = _doPlot;
exports.purge = purge;
exports.react = react;
exports.redraw = redraw;
exports.relayout = relayout;
exports.restyle = restyle;
exports.setPlotConfig = setPlotConfig;
exports.update = update;
exports._guiRelayout = guiEdit(relayout);
exports._guiRestyle = guiEdit(restyle);
exports._guiUpdate = guiEdit(update);
exports._storeDirectGUIEdit = _storeDirectGUIEdit;
/***/ }),
/***/ 20556:
/***/ (function(module) {
"use strict";
/**
* This will be transferred over to gd and overridden by
* config args to Plotly.newPlot.
*
* The defaults are the appropriate settings for plotly.js,
* so we get the right experience without any config argument.
*
* N.B. the config options are not coerced using Lib.coerce so keys
* like `valType` and `values` are only set for documentation purposes
* at the moment.
*/
var configAttributes = {
staticPlot: {
valType: 'boolean',
dflt: false
},
typesetMath: {
valType: 'boolean',
dflt: true
},
plotlyServerURL: {
valType: 'string',
dflt: ''
},
editable: {
valType: 'boolean',
dflt: false
},
edits: {
annotationPosition: {
valType: 'boolean',
dflt: false
},
annotationTail: {
valType: 'boolean',
dflt: false
},
annotationText: {
valType: 'boolean',
dflt: false
},
axisTitleText: {
valType: 'boolean',
dflt: false
},
colorbarPosition: {
valType: 'boolean',
dflt: false
},
colorbarTitleText: {
valType: 'boolean',
dflt: false
},
legendPosition: {
valType: 'boolean',
dflt: false
},
legendText: {
valType: 'boolean',
dflt: false
},
shapePosition: {
valType: 'boolean',
dflt: false
},
titleText: {
valType: 'boolean',
dflt: false
}
},
editSelection: {
valType: 'boolean',
dflt: true
},
autosizable: {
valType: 'boolean',
dflt: false
},
responsive: {
valType: 'boolean',
dflt: false
},
fillFrame: {
valType: 'boolean',
dflt: false
},
frameMargins: {
valType: 'number',
dflt: 0,
min: 0,
max: 0.5
},
scrollZoom: {
valType: 'flaglist',
flags: ['cartesian', 'gl3d', 'geo', 'mapbox'],
extras: [true, false],
dflt: 'gl3d+geo+mapbox'
},
doubleClick: {
valType: 'enumerated',
values: [false, 'reset', 'autosize', 'reset+autosize'],
dflt: 'reset+autosize'
},
doubleClickDelay: {
valType: 'number',
dflt: 300,
min: 0
},
showAxisDragHandles: {
valType: 'boolean',
dflt: true
},
showAxisRangeEntryBoxes: {
valType: 'boolean',
dflt: true
},
showTips: {
valType: 'boolean',
dflt: true
},
showLink: {
valType: 'boolean',
dflt: false
},
linkText: {
valType: 'string',
dflt: 'Edit chart',
noBlank: true
},
sendData: {
valType: 'boolean',
dflt: true
},
showSources: {
valType: 'any',
dflt: false
},
displayModeBar: {
valType: 'enumerated',
values: ['hover', true, false],
dflt: 'hover'
},
showSendToCloud: {
valType: 'boolean',
dflt: false
},
showEditInChartStudio: {
valType: 'boolean',
dflt: false
},
modeBarButtonsToRemove: {
valType: 'any',
dflt: []
},
modeBarButtonsToAdd: {
valType: 'any',
dflt: []
},
modeBarButtons: {
valType: 'any',
dflt: false
},
toImageButtonOptions: {
valType: 'any',
dflt: {}
},
displaylogo: {
valType: 'boolean',
dflt: true
},
watermark: {
valType: 'boolean',
dflt: false
},
plotGlPixelRatio: {
valType: 'number',
dflt: 2,
min: 1,
max: 4
},
setBackground: {
valType: 'any',
dflt: 'transparent'
},
topojsonURL: {
valType: 'string',
noBlank: true,
dflt: 'https://cdn.plot.ly/'
},
mapboxAccessToken: {
valType: 'string',
dflt: null
},
logging: {
valType: 'integer',
min: 0,
max: 2,
dflt: 1
},
notifyOnLogging: {
valType: 'integer',
min: 0,
max: 2,
dflt: 0
},
queueLength: {
valType: 'integer',
min: 0,
dflt: 0
},
globalTransforms: {
valType: 'any',
dflt: []
},
locale: {
valType: 'string',
dflt: 'en-US'
},
locales: {
valType: 'any',
dflt: {}
}
};
var dfltConfig = {};
function crawl(src, target) {
for (var k in src) {
var obj = src[k];
if (obj.valType) {
target[k] = obj.dflt;
} else {
if (!target[k]) {
target[k] = {};
}
crawl(obj, target[k]);
}
}
}
crawl(configAttributes, dfltConfig);
module.exports = {
configAttributes: configAttributes,
dfltConfig: dfltConfig
};
/***/ }),
/***/ 73060:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var baseAttributes = __webpack_require__(45464);
var baseLayoutAttributes = __webpack_require__(64859);
var frameAttributes = __webpack_require__(16672);
var animationAttributes = __webpack_require__(85656);
var configAttributes = (__webpack_require__(20556).configAttributes);
var editTypes = __webpack_require__(67824);
var extendDeepAll = Lib.extendDeepAll;
var isPlainObject = Lib.isPlainObject;
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var nestedProperty = Lib.nestedProperty;
var valObjectMeta = Lib.valObjectMeta;
var IS_SUBPLOT_OBJ = '_isSubplotObj';
var IS_LINKED_TO_ARRAY = '_isLinkedToArray';
var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps';
var DEPRECATED = '_deprecated';
var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED];
exports.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ;
exports.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY;
exports.DEPRECATED = DEPRECATED;
exports.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS;
/** Outputs the full plotly.js plot schema
*
* @return {object}
* - defs
* - traces
* - layout
* - transforms
* - frames
* - animations
* - config
*/
exports.get = function () {
var traces = {};
Registry.allTypes.forEach(function (type) {
traces[type] = getTraceAttributes(type);
});
var transforms = {};
Object.keys(Registry.transformsRegistry).forEach(function (type) {
transforms[type] = getTransformAttributes(type);
});
return {
defs: {
valObjects: valObjectMeta,
metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']),
editType: {
traces: editTypes.traces,
layout: editTypes.layout
},
impliedEdits: {}
},
traces: traces,
layout: getLayoutAttributes(),
transforms: transforms,
frames: getFramesAttributes(),
animation: formatAttributes(animationAttributes),
config: formatAttributes(configAttributes)
};
};
/**
* Crawl the attribute tree, recursively calling a callback function
*
* @param {object} attrs
* The node of the attribute tree (e.g. the root) from which recursion originates
* @param {Function} callback
* A callback function with the signature:
* @callback callback
* @param {object} attr an attribute
* @param {String} attrName name string
* @param {object[]} attrs all the attributes
* @param {Number} level the recursion level, 0 at the root
* @param {String} fullAttrString full attribute name (ie 'marker.line')
* @param {Number} [specifiedLevel]
* The level in the tree, in order to let the callback function detect descend or backtrack,
* typically unsupplied (implied 0), just used by the self-recursive call.
* The necessity arises because the tree traversal is not controlled by callback return values.
* The decision to not use callback return values for controlling tree pruning arose from
* the goal of keeping the crawler backwards compatible. Observe that one of the pruning conditions
* precedes the callback call.
* @param {string} [attrString]
* the path to the current attribute, as an attribute string (ie 'marker.line')
* typically unsupplied, but you may supply it if you want to disambiguate which attrs tree you
* are starting from
*
* @return {object} transformOut
* copy of transformIn that contains attribute defaults
*/
exports.crawl = function (attrs, callback, specifiedLevel, attrString) {
var level = specifiedLevel || 0;
attrString = attrString || '';
Object.keys(attrs).forEach(function (attrName) {
var attr = attrs[attrName];
if (UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return;
var fullAttrString = (attrString ? attrString + '.' : '') + attrName;
callback(attr, attrName, attrs, level, fullAttrString);
if (exports.isValObject(attr)) return;
if (isPlainObject(attr) && attrName !== 'impliedEdits') {
exports.crawl(attr, callback, level + 1, fullAttrString);
}
});
};
/** Is object a value object (or a container object)?
*
* @param {object} obj
* @return {boolean}
* returns true for a valid value object and
* false for tree nodes in the attribute hierarchy
*/
exports.isValObject = function (obj) {
return obj && obj.valType !== undefined;
};
/**
* Find all data array attributes in a given trace object - including
* `arrayOk` attributes.
*
* @param {object} trace
* full trace object that contains a reference to `_module.attributes`
*
* @return {array} arrayAttributes
* list of array attributes for the given trace
*/
exports.findArrayAttributes = function (trace) {
var arrayAttributes = [];
var stack = [];
var isArrayStack = [];
var baseContainer, baseAttrName;
function callback(attr, attrName, attrs, level) {
stack = stack.slice(0, level).concat([attrName]);
isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]);
var splittableAttr = attr && (attr.valType === 'data_array' || attr.arrayOk === true) && !(stack[level - 1] === 'colorbar' && (attrName === 'ticktext' || attrName === 'tickvals'));
// Manually exclude 'colorbar.tickvals' and 'colorbar.ticktext' for now
// which are declared as `valType: 'data_array'` but scale independently of
// the coordinate arrays.
//
// Down the road, we might want to add a schema field (e.g `uncorrelatedArray: true`)
// to distinguish attributes of the likes.
if (!splittableAttr) return;
crawlIntoTrace(baseContainer, 0, '');
}
function crawlIntoTrace(container, i, astrPartial) {
var item = container[stack[i]];
var newAstrPartial = astrPartial + stack[i];
if (i === stack.length - 1) {
if (isArrayOrTypedArray(item)) {
arrayAttributes.push(baseAttrName + newAstrPartial);
}
} else {
if (isArrayStack[i]) {
if (Array.isArray(item)) {
for (var j = 0; j < item.length; j++) {
if (isPlainObject(item[j])) {
crawlIntoTrace(item[j], i + 1, newAstrPartial + '[' + j + '].');
}
}
}
} else if (isPlainObject(item)) {
crawlIntoTrace(item, i + 1, newAstrPartial + '.');
}
}
}
baseContainer = trace;
baseAttrName = '';
exports.crawl(baseAttributes, callback);
if (trace._module && trace._module.attributes) {
exports.crawl(trace._module.attributes, callback);
}
var transforms = trace.transforms;
if (transforms) {
for (var i = 0; i < transforms.length; i++) {
var transform = transforms[i];
var module = transform._module;
if (module) {
baseAttrName = 'transforms[' + i + '].';
baseContainer = transform;
exports.crawl(module.attributes, callback);
}
}
}
return arrayAttributes;
};
/*
* Find the valObject for one attribute in an existing trace
*
* @param {object} trace
* full trace object that contains a reference to `_module.attributes`
* @param {object} parts
* an array of parts, like ['transforms', 1, 'value']
* typically from nestedProperty(...).parts
*
* @return {object|false}
* the valObject for this attribute, or the last found parent
* in some cases the innermost valObject will not exist, for example
* `valType: 'any'` attributes where we might set a part of the attribute.
* In that case, stop at the deepest valObject we *do* find.
*/
exports.getTraceValObject = function (trace, parts) {
var head = parts[0];
var i = 1; // index to start recursing from
var moduleAttrs, valObject;
if (head === 'transforms') {
if (parts.length === 1) {
return baseAttributes.transforms;
}
var transforms = trace.transforms;
if (!Array.isArray(transforms) || !transforms.length) return false;
var tNum = parts[1];
if (!isIndex(tNum) || tNum >= transforms.length) {
return false;
}
moduleAttrs = (Registry.transformsRegistry[transforms[tNum].type] || {}).attributes;
valObject = moduleAttrs && moduleAttrs[parts[2]];
i = 3; // start recursing only inside the transform
} else {
// first look in the module for this trace
// components have already merged their trace attributes in here
var _module = trace._module;
if (!_module) _module = (Registry.modules[trace.type || baseAttributes.type.dflt] || {})._module;
if (!_module) return false;
moduleAttrs = _module.attributes;
valObject = moduleAttrs && moduleAttrs[head];
// then look in the subplot attributes
if (!valObject) {
var subplotModule = _module.basePlotModule;
if (subplotModule && subplotModule.attributes) {
valObject = subplotModule.attributes[head];
}
}
// finally look in the global attributes
if (!valObject) valObject = baseAttributes[head];
}
return recurseIntoValObject(valObject, parts, i);
};
/*
* Find the valObject for one layout attribute
*
* @param {array} parts
* an array of parts, like ['annotations', 1, 'x']
* typically from nestedProperty(...).parts
*
* @return {object|false}
* the valObject for this attribute, or the last found parent
* in some cases the innermost valObject will not exist, for example
* `valType: 'any'` attributes where we might set a part of the attribute.
* In that case, stop at the deepest valObject we *do* find.
*/
exports.getLayoutValObject = function (fullLayout, parts) {
var valObject = layoutHeadAttr(fullLayout, parts[0]);
return recurseIntoValObject(valObject, parts, 1);
};
function layoutHeadAttr(fullLayout, head) {
var i, key, _module, attributes;
// look for attributes of the subplot types used on the plot
var basePlotModules = fullLayout._basePlotModules;
if (basePlotModules) {
var out;
for (i = 0; i < basePlotModules.length; i++) {
_module = basePlotModules[i];
if (_module.attrRegex && _module.attrRegex.test(head)) {
// if a module defines overrides, these take precedence
// initially this is to allow gl2d different editTypes from svg cartesian
if (_module.layoutAttrOverrides) return _module.layoutAttrOverrides;
// otherwise take the first attributes we find
if (!out && _module.layoutAttributes) out = _module.layoutAttributes;
}
// a module can also override the behavior of base (and component) module layout attrs
// again see gl2d for initial use case
var baseOverrides = _module.baseLayoutAttrOverrides;
if (baseOverrides && head in baseOverrides) return baseOverrides[head];
}
if (out) return out;
}
// look for layout attributes contributed by traces on the plot
var modules = fullLayout._modules;
if (modules) {
for (i = 0; i < modules.length; i++) {
attributes = modules[i].layoutAttributes;
if (attributes && head in attributes) {
return attributes[head];
}
}
}
/*
* Next look in components.
* Components that define a schema have already merged this into
* base and subplot attribute defs, so ignore these.
* Others (older style) all put all their attributes
* inside a container matching the module `name`
* eg `attributes` (array) or `legend` (object)
*/
for (key in Registry.componentsRegistry) {
_module = Registry.componentsRegistry[key];
if (_module.name === 'colorscale' && head.indexOf('coloraxis') === 0) {
return _module.layoutAttributes[head];
} else if (!_module.schema && head === _module.name) {
return _module.layoutAttributes;
}
}
if (head in baseLayoutAttributes) return baseLayoutAttributes[head];
return false;
}
function recurseIntoValObject(valObject, parts, i) {
if (!valObject) return false;
if (valObject._isLinkedToArray) {
// skip array index, abort if we try to dive into an array without an index
if (isIndex(parts[i])) i++;else if (i < parts.length) return false;
}
// now recurse as far as we can. Occasionally we have an attribute
// setting an internal part below what's in the schema; just return
// the innermost schema item we find.
for (; i < parts.length; i++) {
var newValObject = valObject[parts[i]];
if (isPlainObject(newValObject)) valObject = newValObject;else break;
if (i === parts.length - 1) break;
if (valObject._isLinkedToArray) {
i++;
if (!isIndex(parts[i])) return false;
} else if (valObject.valType === 'info_array') {
i++;
var index = parts[i];
if (!isIndex(index)) return false;
var items = valObject.items;
if (Array.isArray(items)) {
if (index >= items.length) return false;
if (valObject.dimensions === 2) {
i++;
if (parts.length === i) return valObject;
var index2 = parts[i];
if (!isIndex(index2)) return false;
valObject = items[index][index2];
} else valObject = items[index];
} else {
valObject = items;
}
}
}
return valObject;
}
// note: this is different from Lib.isIndex, this one doesn't accept numeric
// strings, only actual numbers.
function isIndex(val) {
return val === Math.round(val) && val >= 0;
}
function getTraceAttributes(type) {
var _module, basePlotModule;
_module = Registry.modules[type]._module, basePlotModule = _module.basePlotModule;
var attributes = {};
// make 'type' the first attribute in the object
attributes.type = null;
var copyBaseAttributes = extendDeepAll({}, baseAttributes);
var copyModuleAttributes = extendDeepAll({}, _module.attributes);
// prune global-level trace attributes that are already defined in a trace
exports.crawl(copyModuleAttributes, function (attr, attrName, attrs, level, fullAttrString) {
nestedProperty(copyBaseAttributes, fullAttrString).set(undefined);
// Prune undefined attributes
if (attr === undefined) nestedProperty(copyModuleAttributes, fullAttrString).set(undefined);
});
// base attributes (same for all trace types)
extendDeepAll(attributes, copyBaseAttributes);
// prune-out base attributes based on trace module categories
if (Registry.traceIs(type, 'noOpacity')) {
delete attributes.opacity;
}
if (!Registry.traceIs(type, 'showLegend')) {
delete attributes.showlegend;
delete attributes.legendgroup;
}
if (Registry.traceIs(type, 'noHover')) {
delete attributes.hoverinfo;
delete attributes.hoverlabel;
}
if (!_module.selectPoints) {
delete attributes.selectedpoints;
}
// module attributes
extendDeepAll(attributes, copyModuleAttributes);
// subplot attributes
if (basePlotModule.attributes) {
extendDeepAll(attributes, basePlotModule.attributes);
}
// 'type' gets overwritten by baseAttributes; reset it here
attributes.type = type;
var out = {
meta: _module.meta || {},
categories: _module.categories || {},
animatable: Boolean(_module.animatable),
type: type,
attributes: formatAttributes(attributes)
};
// trace-specific layout attributes
if (_module.layoutAttributes) {
var layoutAttributes = {};
extendDeepAll(layoutAttributes, _module.layoutAttributes);
out.layoutAttributes = formatAttributes(layoutAttributes);
}
// drop anim:true in non-animatable modules
if (!_module.animatable) {
exports.crawl(out, function (attr) {
if (exports.isValObject(attr) && 'anim' in attr) {
delete attr.anim;
}
});
}
return out;
}
function getLayoutAttributes() {
var layoutAttributes = {};
var key, _module;
// global layout attributes
extendDeepAll(layoutAttributes, baseLayoutAttributes);
// add base plot module layout attributes
for (key in Registry.subplotsRegistry) {
_module = Registry.subplotsRegistry[key];
if (!_module.layoutAttributes) continue;
if (Array.isArray(_module.attr)) {
for (var i = 0; i < _module.attr.length; i++) {
handleBasePlotModule(layoutAttributes, _module, _module.attr[i]);
}
} else {
var astr = _module.attr === 'subplot' ? _module.name : _module.attr;
handleBasePlotModule(layoutAttributes, _module, astr);
}
}
// add registered components layout attributes
for (key in Registry.componentsRegistry) {
_module = Registry.componentsRegistry[key];
var schema = _module.schema;
if (schema && (schema.subplots || schema.layout)) {
/*
* Components with defined schema have already been merged in at register time
* but a few components define attributes that apply only to xaxis
* not yaxis (rangeselector, rangeslider) - delete from y schema.
* Note that the input attributes for xaxis/yaxis are the same object
* so it's not possible to only add them to xaxis from the start.
* If we ever have such asymmetry the other way, or anywhere else,
* we will need to extend both this code and mergeComponentAttrsToSubplot
* (which will not find yaxis only for example)
*/
var subplots = schema.subplots;
if (subplots && subplots.xaxis && !subplots.yaxis) {
for (var xkey in subplots.xaxis) {
delete layoutAttributes.yaxis[xkey];
}
}
/*
* Also some attributes e.g. shift & autoshift only implemented on the yaxis
* at the moment. Remove them from the xaxis.
*/
delete layoutAttributes.xaxis.shift;
delete layoutAttributes.xaxis.autoshift;
} else if (_module.name === 'colorscale') {
extendDeepAll(layoutAttributes, _module.layoutAttributes);
} else if (_module.layoutAttributes) {
// older style without schema need to be explicitly merged in now
insertAttrs(layoutAttributes, _module.layoutAttributes, _module.name);
}
}
return {
layoutAttributes: formatAttributes(layoutAttributes)
};
}
function getTransformAttributes(type) {
var _module = Registry.transformsRegistry[type];
var attributes = extendDeepAll({}, _module.attributes);
// add registered components transform attributes
Object.keys(Registry.componentsRegistry).forEach(function (k) {
var _module = Registry.componentsRegistry[k];
if (_module.schema && _module.schema.transforms && _module.schema.transforms[type]) {
Object.keys(_module.schema.transforms[type]).forEach(function (v) {
insertAttrs(attributes, _module.schema.transforms[type][v], v);
});
}
});
return {
attributes: formatAttributes(attributes)
};
}
function getFramesAttributes() {
var attrs = {
frames: extendDeepAll({}, frameAttributes)
};
formatAttributes(attrs);
return attrs.frames;
}
function formatAttributes(attrs) {
mergeValTypeAndRole(attrs);
formatArrayContainers(attrs);
stringify(attrs);
return attrs;
}
function mergeValTypeAndRole(attrs) {
function makeSrcAttr(attrName) {
return {
valType: 'string',
editType: 'none'
};
}
function callback(attr, attrName, attrs) {
if (exports.isValObject(attr)) {
if (attr.arrayOk === true || attr.valType === 'data_array') {
// all 'arrayOk' and 'data_array' attrs have a corresponding 'src' attr
attrs[attrName + 'src'] = makeSrcAttr(attrName);
}
} else if (isPlainObject(attr)) {
// all attrs container objects get role 'object'
attr.role = 'object';
}
}
exports.crawl(attrs, callback);
}
function formatArrayContainers(attrs) {
function callback(attr, attrName, attrs) {
if (!attr) return;
var itemName = attr[IS_LINKED_TO_ARRAY];
if (!itemName) return;
delete attr[IS_LINKED_TO_ARRAY];
attrs[attrName] = {
items: {}
};
attrs[attrName].items[itemName] = attr;
attrs[attrName].role = 'object';
}
exports.crawl(attrs, callback);
}
// this can take around 10ms and should only be run from PlotSchema.get(),
// to ensure JSON.stringify(PlotSchema.get()) gives the intended result.
function stringify(attrs) {
function walk(attr) {
for (var k in attr) {
if (isPlainObject(attr[k])) {
walk(attr[k]);
} else if (Array.isArray(attr[k])) {
for (var i = 0; i < attr[k].length; i++) {
walk(attr[k][i]);
}
} else {
// as JSON.stringify(/test/) // => {}
if (attr[k] instanceof RegExp) {
attr[k] = attr[k].toString();
}
}
}
}
walk(attrs);
}
function handleBasePlotModule(layoutAttributes, _module, astr) {
var np = nestedProperty(layoutAttributes, astr);
var attrs = extendDeepAll({}, _module.layoutAttributes);
attrs[IS_SUBPLOT_OBJ] = true;
np.set(attrs);
}
function insertAttrs(baseAttrs, newAttrs, astr) {
var np = nestedProperty(baseAttrs, astr);
np.set(extendDeepAll(np.get() || {}, newAttrs));
}
/***/ }),
/***/ 31780:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var plotAttributes = __webpack_require__(45464);
var TEMPLATEITEMNAME = 'templateitemname';
var templateAttrs = {
name: {
valType: 'string',
editType: 'none'
}
};
templateAttrs[TEMPLATEITEMNAME] = {
valType: 'string',
editType: 'calc'
};
/**
* templatedArray: decorate an attributes object with templating (and array)
* properties.
*
* @param {string} name: the singular form of the array name. Sets
* `_isLinkedToArray` to this, so the schema knows to treat this as an array.
* @param {object} attrs: the item attributes. Since all callers are expected
* to be constructing this object on the spot, we mutate it here for
* performance, rather than extending a new object with it.
*
* @returns {object}: the decorated `attrs` object
*/
exports.templatedArray = function (name, attrs) {
attrs._isLinkedToArray = name;
attrs.name = templateAttrs.name;
attrs[TEMPLATEITEMNAME] = templateAttrs[TEMPLATEITEMNAME];
return attrs;
};
/**
* traceTemplater: logic for matching traces to trace templates
*
* @param {object} dataTemplate: collection of {traceType: [{template}, ...]}
* ie each type the template applies to contains a list of template objects,
* to be provided cyclically to data traces of that type.
*
* @returns {object}: {newTrace}, a function:
* newTrace(traceIn): that takes the input traceIn, coerces its type, then
* uses that type to find the next template to apply. returns the output
* traceOut with template attached, ready to continue supplyDefaults.
*/
exports.traceTemplater = function (dataTemplate) {
var traceCounts = {};
var traceType, typeTemplates;
for (traceType in dataTemplate) {
typeTemplates = dataTemplate[traceType];
if (Array.isArray(typeTemplates) && typeTemplates.length) {
traceCounts[traceType] = 0;
}
}
function newTrace(traceIn) {
traceType = Lib.coerce(traceIn, {}, plotAttributes, 'type');
var traceOut = {
type: traceType,
_template: null
};
if (traceType in traceCounts) {
typeTemplates = dataTemplate[traceType];
// cycle through traces in the template set for this type
var typei = traceCounts[traceType] % typeTemplates.length;
traceCounts[traceType]++;
traceOut._template = typeTemplates[typei];
} else {
// TODO: anything we should do for types missing from the template?
// try to apply some other type? Or just bail as we do here?
// Actually I think yes, we should apply other types; would be nice
// if all scatter* could inherit from each other, and if histogram
// could inherit from bar, etc... but how to specify this? And do we
// compose them, or if a type is present require it to be complete?
// Actually this could apply to layout too - 3D annotations
// inheriting from 2D, axes of different types inheriting from each
// other...
}
return traceOut;
}
return {
newTrace: newTrace
// TODO: function to figure out what's left & what didn't work
};
};
/**
* newContainer: Create a new sub-container inside `container` and propagate any
* applicable template to it. If there's no template, still propagates
* `undefined` so relinkPrivate will not retain an old template!
*
* @param {object} container: the outer container, should already have _template
* if there *is* a template for this plot
* @param {string} name: the key of the new container to make
* @param {string} baseName: if applicable, a base attribute to take the
* template from, ie for xaxis3 the base would be xaxis
*
* @returns {object}: an object for inclusion _full*, empty except for the
* appropriate template piece
*/
exports.newContainer = function (container, name, baseName) {
var template = container._template;
var part = template && (template[name] || baseName && template[baseName]);
if (!Lib.isPlainObject(part)) part = null;
var out = container[name] = {
_template: part
};
return out;
};
/**
* arrayTemplater: special logic for templating both defaults and specific items
* in a container array (annotations etc)
*
* @param {object} container: the outer container, should already have _template
* if there *is* a template for this plot
* @param {string} name: the name of the array to template (ie 'annotations')
* will be used to find default ('annotationdefaults' object) and specific
* ('annotations' array) template specs.
* @param {string} inclusionAttr: the attribute determining this item's
* inclusion in the output, usually 'visible' or 'enabled'
*
* @returns {object}: {newItem, defaultItems}, both functions:
* newItem(itemIn): create an output item, bare except for the correct
* template and name(s), as the base for supplyDefaults
* defaultItems(): to be called after all newItem calls, return any
* specific template items that have not already beeen included,
* also as bare output items ready for supplyDefaults.
*/
exports.arrayTemplater = function (container, name, inclusionAttr) {
var template = container._template;
var defaultsTemplate = template && template[arrayDefaultKey(name)];
var templateItems = template && template[name];
if (!Array.isArray(templateItems) || !templateItems.length) {
templateItems = [];
}
var usedNames = {};
function newItem(itemIn) {
// include name and templateitemname in the output object for ALL
// container array items. Note: you could potentially use different
// name and templateitemname, if you're using one template to make
// another template. templateitemname would be the name in the original
// template, and name is the new "subclassed" item name.
var out = {
name: itemIn.name,
_input: itemIn
};
var templateItemName = out[TEMPLATEITEMNAME] = itemIn[TEMPLATEITEMNAME];
// no itemname: use the default template
if (!validItemName(templateItemName)) {
out._template = defaultsTemplate;
return out;
}
// look for an item matching this itemname
// note these do not inherit from the default template, only the item.
for (var i = 0; i < templateItems.length; i++) {
var templateItem = templateItems[i];
if (templateItem.name === templateItemName) {
// Note: it's OK to use a template item more than once
// but using it at least once will stop it from generating
// a default item at the end.
usedNames[templateItemName] = 1;
out._template = templateItem;
return out;
}
}
// Didn't find a matching template item, so since this item is intended
// to only be modifications it's most likely broken. Hide it unless
// it's explicitly marked visible - in which case it gets NO template,
// not even the default.
out[inclusionAttr] = itemIn[inclusionAttr] || false;
// special falsy value we can look for in validateTemplate
out._template = false;
return out;
}
function defaultItems() {
var out = [];
for (var i = 0; i < templateItems.length; i++) {
var templateItem = templateItems[i];
var name = templateItem.name;
// only allow named items to be added as defaults,
// and only allow each name once
if (validItemName(name) && !usedNames[name]) {
var outi = {
_template: templateItem,
name: name,
_input: {
_templateitemname: name
}
};
outi[TEMPLATEITEMNAME] = templateItem[TEMPLATEITEMNAME];
out.push(outi);
usedNames[name] = 1;
}
}
return out;
}
return {
newItem: newItem,
defaultItems: defaultItems
};
};
function validItemName(name) {
return name && typeof name === 'string';
}
function arrayDefaultKey(name) {
var lastChar = name.length - 1;
if (name.charAt(lastChar) !== 's') {
Lib.warn('bad argument to arrayDefaultKey: ' + name);
}
return name.substr(0, name.length - 1) + 'defaults';
}
exports.arrayDefaultKey = arrayDefaultKey;
/**
* arrayEditor: helper for editing array items that may have come from
* template defaults (in which case they will not exist in the input yet)
*
* @param {object} parentIn: the input container (eg gd.layout)
* @param {string} containerStr: the attribute string for the container inside
* `parentIn`.
* @param {object} itemOut: the _full* item (eg gd._fullLayout.annotations[0])
* that we'll be editing. Assumed to have been created by `arrayTemplater`.
*
* @returns {object}: {modifyBase, modifyItem, getUpdateObj, applyUpdate}, all functions:
* modifyBase(attr, value): Add an update that's *not* related to the item.
* `attr` is the full attribute string.
* modifyItem(attr, value): Add an update to the item. `attr` is just the
* portion of the attribute string inside the item.
* getUpdateObj(): Get the final constructed update object, to use in
* `restyle` or `relayout`. Also resets the update object in case this
* update was canceled.
* applyUpdate(attr, value): optionally add an update `attr: value`,
* then apply it to `parent` which should be the parent of `containerIn`,
* ie the object to which `containerStr` is the attribute string.
*/
exports.arrayEditor = function (parentIn, containerStr, itemOut) {
var lengthIn = (Lib.nestedProperty(parentIn, containerStr).get() || []).length;
var index = itemOut._index;
// Check that we are indeed off the end of this container.
// Otherwise a devious user could put a key `_templateitemname` in their
// own input and break lots of things.
var templateItemName = index >= lengthIn && (itemOut._input || {})._templateitemname;
if (templateItemName) index = lengthIn;
var itemStr = containerStr + '[' + index + ']';
var update;
function resetUpdate() {
update = {};
if (templateItemName) {
update[itemStr] = {};
update[itemStr][TEMPLATEITEMNAME] = templateItemName;
}
}
resetUpdate();
function modifyBase(attr, value) {
update[attr] = value;
}
function modifyItem(attr, value) {
if (templateItemName) {
// we're making a new object: edit that object
Lib.nestedProperty(update[itemStr], attr).set(value);
} else {
// we're editing an existing object: include *just* the edit
update[itemStr + '.' + attr] = value;
}
}
function getUpdateObj() {
var updateOut = update;
resetUpdate();
return updateOut;
}
function applyUpdate(attr, value) {
if (attr) modifyItem(attr, value);
var updateToApply = getUpdateObj();
for (var key in updateToApply) {
Lib.nestedProperty(parentIn, key).set(updateToApply[key]);
}
}
return {
modifyBase: modifyBase,
modifyItem: modifyItem,
getUpdateObj: getUpdateObj,
applyUpdate: applyUpdate
};
};
/***/ }),
/***/ 39172:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Registry = __webpack_require__(24040);
var Plots = __webpack_require__(7316);
var Lib = __webpack_require__(3400);
var svgTextUtils = __webpack_require__(72736);
var clearGlCanvases = __webpack_require__(73696);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Titles = __webpack_require__(81668);
var ModeBar = __webpack_require__(45460);
var Axes = __webpack_require__(54460);
var alignmentConstants = __webpack_require__(84284);
var axisConstraints = __webpack_require__(71888);
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = (__webpack_require__(19280).doAutoRange);
var SVG_TEXT_ANCHOR_START = 'start';
var SVG_TEXT_ANCHOR_MIDDLE = 'middle';
var SVG_TEXT_ANCHOR_END = 'end';
var zindexSeparator = (__webpack_require__(33816).zindexSeparator);
exports.layoutStyles = function (gd) {
return Lib.syncOrAsync([Plots.doAutoMargin, lsInner], gd);
};
function overlappingDomain(xDomain, yDomain, domains) {
for (var i = 0; i < domains.length; i++) {
var existingX = domains[i][0];
var existingY = domains[i][1];
if (existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
continue;
}
if (existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
return true;
}
}
return false;
}
function lsInner(gd) {
var fullLayout = gd._fullLayout;
var gs = fullLayout._size;
var pad = gs.p;
var axList = Axes.list(gd, '', true);
var i, subplot, plotinfo, ax, xa, ya;
fullLayout._paperdiv.style({
width: gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroWidth && !gd.layout.width ? '100%' : fullLayout.width + 'px',
height: gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroHeight && !gd.layout.height ? '100%' : fullLayout.height + 'px'
}).selectAll('.main-svg').call(Drawing.setSize, fullLayout.width, fullLayout.height);
gd._context.setBackground(gd, fullLayout.paper_bgcolor);
exports.drawMainTitle(gd);
ModeBar.manage(gd);
// _has('cartesian') means SVG specifically, not GL2D - but GL2D
// can still get here because it makes some of the SVG structure
// for shared features like selections.
if (!fullLayout._has('cartesian')) {
return Plots.previousPromises(gd);
}
function getLinePosition(ax, counterAx, side) {
var lwHalf = ax._lw / 2;
if (ax._id.charAt(0) === 'x') {
if (!counterAx) return gs.t + gs.h * (1 - (ax.position || 0)) + lwHalf % 1;else if (side === 'top') return counterAx._offset - pad - lwHalf;
return counterAx._offset + counterAx._length + pad + lwHalf;
}
if (!counterAx) return gs.l + gs.w * (ax.position || 0) + lwHalf % 1;else if (side === 'right') return counterAx._offset + counterAx._length + pad + lwHalf;
return counterAx._offset - pad - lwHalf;
}
// some preparation of axis position info
for (i = 0; i < axList.length; i++) {
ax = axList[i];
var counterAx = ax._anchorAxis;
// clear axis line positions, to be set in the subplot loop below
ax._linepositions = {};
// stash crispRounded linewidth so we don't need to pass gd all over the place
ax._lw = Drawing.crispRound(gd, ax.linewidth, 1);
// figure out the main axis line and main mirror line position.
// it's easier to follow the logic if we handle these separately from
// ax._linepositions, which are only used by mirror=allticks
// for non-main-subplot ticks, and mirror=all(ticks)? for zero line
// hiding logic
ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side);
ax._mainMirrorPosition = ax.mirror && counterAx ? getLinePosition(ax, counterAx, alignmentConstants.OPPOSITE_SIDE[ax.side]) : null;
}
// figure out which backgrounds we need to draw,
// and in which layers to put them
var lowerBackgroundIDs = [];
var backgroundIds = [];
var lowerDomains = [];
// no need to draw background when paper and plot color are the same color,
// activate mode just for large splom (which benefit the most from this
// optimization), but this could apply to all cartesian subplots.
var noNeedForBg = Color.opacity(fullLayout.paper_bgcolor) === 1 && Color.opacity(fullLayout.plot_bgcolor) === 1 && fullLayout.paper_bgcolor === fullLayout.plot_bgcolor;
for (subplot in fullLayout._plots) {
plotinfo = fullLayout._plots[subplot];
if (plotinfo.mainplot) {
// mainplot is a reference to the main plot this one is overlaid on
// so if it exists, this is an overlaid plot and we don't need to
// give it its own background
if (plotinfo.bg) {
plotinfo.bg.remove();
}
plotinfo.bg = undefined;
} else {
var xDomain = plotinfo.xaxis.domain;
var yDomain = plotinfo.yaxis.domain;
var plotgroup = plotinfo.plotgroup;
if (overlappingDomain(xDomain, yDomain, lowerDomains) && subplot.indexOf(zindexSeparator) === -1) {
var pgNode = plotgroup.node();
var plotgroupBg = plotinfo.bg = Lib.ensureSingle(plotgroup, 'rect', 'bg');
pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]);
backgroundIds.push(subplot);
} else {
plotgroup.select('rect.bg').remove();
lowerDomains.push([xDomain, yDomain]);
if (!noNeedForBg) {
lowerBackgroundIDs.push(subplot);
backgroundIds.push(subplot);
}
}
}
}
// now create all the lower-layer backgrounds at once now that
// we have the list of subplots that need them
var lowerBackgrounds = fullLayout._bgLayer.selectAll('.bg').data(lowerBackgroundIDs);
lowerBackgrounds.enter().append('rect').classed('bg', true);
lowerBackgrounds.exit().remove();
lowerBackgrounds.each(function (subplot) {
fullLayout._plots[subplot].bg = d3.select(this);
});
// style all backgrounds
for (i = 0; i < backgroundIds.length; i++) {
plotinfo = fullLayout._plots[backgroundIds[i]];
xa = plotinfo.xaxis;
ya = plotinfo.yaxis;
if (plotinfo.bg && xa._offset !== undefined && ya._offset !== undefined) {
plotinfo.bg.call(Drawing.setRect, xa._offset - pad, ya._offset - pad, xa._length + 2 * pad, ya._length + 2 * pad).call(Color.fill, fullLayout.plot_bgcolor).style('stroke-width', 0);
}
}
if (!fullLayout._hasOnlyLargeSploms) {
for (subplot in fullLayout._plots) {
plotinfo = fullLayout._plots[subplot];
xa = plotinfo.xaxis;
ya = plotinfo.yaxis;
// Clip so that data only shows up on the plot area.
var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot';
var plotClip = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function (s) {
s.classed('plotclip', true).append('rect');
});
plotinfo.clipRect = plotClip.select('rect').attr({
width: xa._length,
height: ya._length
});
Drawing.setTranslate(plotinfo.plot, xa._offset, ya._offset);
var plotClipId;
var layerClipId;
if (plotinfo._hasClipOnAxisFalse) {
plotClipId = null;
layerClipId = clipId;
} else {
plotClipId = clipId;
layerClipId = null;
}
Drawing.setClipUrl(plotinfo.plot, plotClipId, gd);
// stash layer clipId value (null or same as clipId)
// to DRY up Drawing.setClipUrl calls on trace-module and trace layers
// downstream
plotinfo.layerClipId = layerClipId;
}
}
var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop, leftYLineWidth, rightYLineWidth;
var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight, connectYBottom, connectYTop;
var extraSubplot;
function xLinePath(y) {
return 'M' + xLinesXLeft + ',' + y + 'H' + xLinesXRight;
}
function xLinePathFree(y) {
return 'M' + xa._offset + ',' + y + 'h' + xa._length;
}
function yLinePath(x) {
return 'M' + x + ',' + yLinesYTop + 'V' + yLinesYBottom;
}
function yLinePathFree(x) {
if (ya._shift !== undefined) {
x += ya._shift;
}
return 'M' + x + ',' + ya._offset + 'v' + ya._length;
}
function mainPath(ax, pathFn, pathFnFree) {
if (!ax.showline || subplot !== ax._mainSubplot) return '';
if (!ax._anchorAxis) return pathFnFree(ax._mainLinePosition);
var out = pathFn(ax._mainLinePosition);
if (ax.mirror) out += pathFn(ax._mainMirrorPosition);
return out;
}
for (subplot in fullLayout._plots) {
plotinfo = fullLayout._plots[subplot];
xa = plotinfo.xaxis;
ya = plotinfo.yaxis;
/*
* x lines get longer where they meet y lines, to make a crisp corner.
* The x lines get the padding (margin.pad) plus the y line width to
* fill up the corner nicely. Free x lines are excluded - they always
* span exactly the data area of the plot
*
* | XXXXX
* | XXXXX
* |
* +------
* x1
* -----
* x2
*/
var xPath = 'M0,0';
if (shouldShowLinesOrTicks(xa, subplot)) {
leftYLineWidth = findCounterAxisLineWidth(xa, 'left', ya, axList);
xLinesXLeft = xa._offset - (leftYLineWidth ? pad + leftYLineWidth : 0);
rightYLineWidth = findCounterAxisLineWidth(xa, 'right', ya, axList);
xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? pad + rightYLineWidth : 0);
xLinesYBottom = getLinePosition(xa, ya, 'bottom');
xLinesYTop = getLinePosition(xa, ya, 'top');
// save axis line positions for extra ticks to reference
// each subplot that gets ticks from "allticks" gets an entry:
// [left or bottom, right or top]
extraSubplot = !xa._anchorAxis || subplot !== xa._mainSubplot;
if (extraSubplot && (xa.mirror === 'allticks' || xa.mirror === 'all')) {
xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop];
}
xPath = mainPath(xa, xLinePath, xLinePathFree);
if (extraSubplot && xa.showline && (xa.mirror === 'all' || xa.mirror === 'allticks')) {
xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop);
}
plotinfo.xlines.style('stroke-width', xa._lw + 'px').call(Color.stroke, xa.showline ? xa.linecolor : 'rgba(0,0,0,0)');
}
plotinfo.xlines.attr('d', xPath);
/*
* y lines that meet x axes get longer only by margin.pad, because
* the x axes fill in the corner space. Free y axes, like free x axes,
* always span exactly the data area of the plot
*
* | | XXXX
* y2| y1| XXXX
* | | XXXX
* |
* +-----
*/
var yPath = 'M0,0';
if (shouldShowLinesOrTicks(ya, subplot)) {
connectYBottom = findCounterAxisLineWidth(ya, 'bottom', xa, axList);
yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad : 0);
connectYTop = findCounterAxisLineWidth(ya, 'top', xa, axList);
yLinesYTop = ya._offset - (connectYTop ? pad : 0);
yLinesXLeft = getLinePosition(ya, xa, 'left');
yLinesXRight = getLinePosition(ya, xa, 'right');
extraSubplot = !ya._anchorAxis || subplot !== ya._mainSubplot;
if (extraSubplot && (ya.mirror === 'allticks' || ya.mirror === 'all')) {
ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight];
}
yPath = mainPath(ya, yLinePath, yLinePathFree);
if (extraSubplot && ya.showline && (ya.mirror === 'all' || ya.mirror === 'allticks')) {
yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight);
}
plotinfo.ylines.style('stroke-width', ya._lw + 'px').call(Color.stroke, ya.showline ? ya.linecolor : 'rgba(0,0,0,0)');
}
plotinfo.ylines.attr('d', yPath);
}
Axes.makeClipPaths(gd);
return Plots.previousPromises(gd);
}
function shouldShowLinesOrTicks(ax, subplot) {
return (ax.ticks || ax.showline) && (subplot === ax._mainSubplot || ax.mirror === 'all' || ax.mirror === 'allticks');
}
/*
* should we draw a line on counterAx at this side of ax?
* It's assumed that counterAx is known to overlay the subplot we're working on
* but it may not be its main axis.
*/
function shouldShowLineThisSide(ax, side, counterAx) {
// does counterAx get a line at all?
if (!counterAx.showline || !counterAx._lw) return false;
// are we drawing *all* lines for counterAx?
if (counterAx.mirror === 'all' || counterAx.mirror === 'allticks') return true;
var anchorAx = counterAx._anchorAxis;
// is this a free axis? free axes can only have a subplot side-line with all(ticks)? mirroring
if (!anchorAx) return false;
// in order to handle cases where the user forgot to anchor this axis correctly
// (because its default anchor has the same domain on the relevant end)
// check whether the relevant position is the same.
var sideIndex = alignmentConstants.FROM_BL[side];
if (counterAx.side === side) {
return anchorAx.domain[sideIndex] === ax.domain[sideIndex];
}
return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex];
}
/*
* Is there another axis intersecting `side` end of `ax`?
* First look at `counterAx` (the axis for this subplot),
* then at all other potential counteraxes on or overlaying this subplot.
* Take the line width from the first one that has a line.
*/
function findCounterAxisLineWidth(ax, side, counterAx, axList) {
if (shouldShowLineThisSide(ax, side, counterAx)) {
return counterAx._lw;
}
for (var i = 0; i < axList.length; i++) {
var axi = axList[i];
if (axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) {
return axi._lw;
}
}
return 0;
}
exports.drawMainTitle = function (gd) {
var title = gd._fullLayout.title;
var fullLayout = gd._fullLayout;
var textAnchor = getMainTitleTextAnchor(fullLayout);
var dy = getMainTitleDy(fullLayout);
var y = getMainTitleY(fullLayout, dy);
var x = getMainTitleX(fullLayout, textAnchor);
Titles.draw(gd, 'gtitle', {
propContainer: fullLayout,
propName: 'title.text',
subtitlePropName: 'title.subtitle.text',
placeholder: fullLayout._dfltTitle.plot,
subtitlePlaceholder: fullLayout._dfltTitle.subtitle,
attributes: {
x: x,
y: y,
'text-anchor': textAnchor,
dy: dy
}
});
if (title.text && title.automargin) {
var titleObj = d3.selectAll('.gtitle');
var titleHeight = Drawing.bBox(d3.selectAll('.g-gtitle').node()).height;
var pushMargin = needsMarginPush(gd, title, titleHeight);
if (pushMargin > 0) {
applyTitleAutoMargin(gd, y, pushMargin, titleHeight);
// Re-position the title once we know where it needs to be
titleObj.attr({
x: x,
y: y,
'text-anchor': textAnchor,
dy: getMainTitleDyAdj(title.yanchor)
}).call(svgTextUtils.positionText, x, y);
var extraLines = (title.text.match(svgTextUtils.BR_TAG_ALL) || []).length;
if (extraLines) {
var delta = alignmentConstants.LINE_SPACING * extraLines + alignmentConstants.MID_SHIFT;
if (title.y === 0) {
delta = -delta;
}
titleObj.selectAll('.line').each(function () {
var newDy = +this.getAttribute('dy').slice(0, -2) - delta + 'em';
this.setAttribute('dy', newDy);
});
}
// If there is a subtitle
var subtitleObj = d3.selectAll('.gtitle-subtitle');
if (subtitleObj.node()) {
// Get bottom edge of title bounding box
var titleBB = titleObj.node().getBBox();
var titleBottom = titleBB.y + titleBB.height;
var subtitleY = titleBottom + Titles.SUBTITLE_PADDING_EM * title.subtitle.font.size;
subtitleObj.attr({
x: x,
y: subtitleY,
'text-anchor': textAnchor,
dy: getMainTitleDyAdj(title.yanchor)
}).call(svgTextUtils.positionText, x, subtitleY);
}
}
}
};
function isOutsideContainer(gd, title, position, y, titleHeight) {
var plotHeight = title.yref === 'paper' ? gd._fullLayout._size.h : gd._fullLayout.height;
var yPosTop = Lib.isTopAnchor(title) ? y : y - titleHeight; // Standardize to the top of the title
var yPosRel = position === 'b' ? plotHeight - yPosTop : yPosTop; // Position relative to the top or bottom of plot
if (Lib.isTopAnchor(title) && position === 't' || Lib.isBottomAnchor(title) && position === 'b') {
return false;
} else {
return yPosRel < titleHeight;
}
}
function containerPushVal(position, titleY, titleYanchor, height, titleDepth) {
var push = 0;
if (titleYanchor === 'middle') {
push += titleDepth / 2;
}
if (position === 't') {
if (titleYanchor === 'top') {
push += titleDepth;
}
push += height - titleY * height;
} else {
if (titleYanchor === 'bottom') {
push += titleDepth;
}
push += titleY * height;
}
return push;
}
function needsMarginPush(gd, title, titleHeight) {
var titleY = title.y;
var titleYanchor = title.yanchor;
var position = titleY > 0.5 ? 't' : 'b';
var curMargin = gd._fullLayout.margin[position];
var pushMargin = 0;
if (title.yref === 'paper') {
pushMargin = titleHeight + title.pad.t + title.pad.b;
} else if (title.yref === 'container') {
pushMargin = containerPushVal(position, titleY, titleYanchor, gd._fullLayout.height, titleHeight) + title.pad.t + title.pad.b;
}
if (pushMargin > curMargin) {
return pushMargin;
}
return 0;
}
function applyTitleAutoMargin(gd, y, pushMargin, titleHeight) {
var titleID = 'title.automargin';
var title = gd._fullLayout.title;
var position = title.y > 0.5 ? 't' : 'b';
var push = {
x: title.x,
y: title.y,
t: 0,
b: 0
};
var reservedPush = {};
if (title.yref === 'paper' && isOutsideContainer(gd, title, position, y, titleHeight)) {
push[position] = pushMargin;
} else if (title.yref === 'container') {
reservedPush[position] = pushMargin;
gd._fullLayout._reservedMargin[titleID] = reservedPush;
}
Plots.allowAutoMargin(gd, titleID);
Plots.autoMargin(gd, titleID, push);
}
function getMainTitleX(fullLayout, textAnchor) {
var title = fullLayout.title;
var gs = fullLayout._size;
var hPadShift = 0;
if (textAnchor === SVG_TEXT_ANCHOR_START) {
hPadShift = title.pad.l;
} else if (textAnchor === SVG_TEXT_ANCHOR_END) {
hPadShift = -title.pad.r;
}
switch (title.xref) {
case 'paper':
return gs.l + gs.w * title.x + hPadShift;
case 'container':
default:
return fullLayout.width * title.x + hPadShift;
}
}
function getMainTitleY(fullLayout, dy) {
var title = fullLayout.title;
var gs = fullLayout._size;
var vPadShift = 0;
if (dy === '0em' || !dy) {
vPadShift = -title.pad.b;
} else if (dy === alignmentConstants.CAP_SHIFT + 'em') {
vPadShift = title.pad.t;
}
if (title.y === 'auto') {
return gs.t / 2;
} else {
switch (title.yref) {
case 'paper':
return gs.t + gs.h - gs.h * title.y + vPadShift;
case 'container':
default:
return fullLayout.height - fullLayout.height * title.y + vPadShift;
}
}
}
function getMainTitleDyAdj(yanchor) {
if (yanchor === 'top') {
return alignmentConstants.CAP_SHIFT + 0.3 + 'em';
} else if (yanchor === 'bottom') {
return '-0.3em';
} else {
return alignmentConstants.MID_SHIFT + 'em';
}
}
function getMainTitleTextAnchor(fullLayout) {
var title = fullLayout.title;
var textAnchor = SVG_TEXT_ANCHOR_MIDDLE;
if (Lib.isRightAnchor(title)) {
textAnchor = SVG_TEXT_ANCHOR_END;
} else if (Lib.isLeftAnchor(title)) {
textAnchor = SVG_TEXT_ANCHOR_START;
}
return textAnchor;
}
function getMainTitleDy(fullLayout) {
var title = fullLayout.title;
var dy = '0em';
if (Lib.isTopAnchor(title)) {
dy = alignmentConstants.CAP_SHIFT + 'em';
} else if (Lib.isMiddleAnchor(title)) {
dy = alignmentConstants.MID_SHIFT + 'em';
}
return dy;
}
exports.doTraceStyle = function (gd) {
var calcdata = gd.calcdata;
var editStyleCalls = [];
var i;
for (i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var cd0 = cd[0] || {};
var trace = cd0.trace || {};
var _module = trace._module || {};
// See if we need to do arraysToCalcdata
// call it regardless of what change we made, in case
// supplyDefaults brought in an array that was already
// in gd.data but not in gd._fullData previously
var arraysToCalcdata = _module.arraysToCalcdata;
if (arraysToCalcdata) arraysToCalcdata(cd, trace);
var editStyle = _module.editStyle;
if (editStyle) editStyleCalls.push({
fn: editStyle,
cd0: cd0
});
}
if (editStyleCalls.length) {
for (i = 0; i < editStyleCalls.length; i++) {
var edit = editStyleCalls[i];
edit.fn(gd, edit.cd0);
}
clearGlCanvases(gd);
exports.redrawReglTraces(gd);
}
Plots.style(gd);
Registry.getComponentMethod('legend', 'draw')(gd);
return Plots.previousPromises(gd);
};
exports.doColorBars = function (gd) {
Registry.getComponentMethod('colorbar', 'draw')(gd);
return Plots.previousPromises(gd);
};
// force plot() to redo the layout and replot with the modified layout
exports.layoutReplot = function (gd) {
var layout = gd.layout;
gd.layout = undefined;
return Registry.call('_doPlot', gd, '', layout);
};
exports.doLegend = function (gd) {
Registry.getComponentMethod('legend', 'draw')(gd);
return Plots.previousPromises(gd);
};
exports.doTicksRelayout = function (gd) {
Axes.draw(gd, 'redraw');
if (gd._fullLayout._hasOnlyLargeSploms) {
Registry.subplotsRegistry.splom.updateGrid(gd);
clearGlCanvases(gd);
exports.redrawReglTraces(gd);
}
exports.drawMainTitle(gd);
return Plots.previousPromises(gd);
};
exports.doModeBar = function (gd) {
var fullLayout = gd._fullLayout;
ModeBar.manage(gd);
for (var i = 0; i < fullLayout._basePlotModules.length; i++) {
var updateFx = fullLayout._basePlotModules[i].updateFx;
if (updateFx) updateFx(gd);
}
return Plots.previousPromises(gd);
};
exports.doCamera = function (gd) {
var fullLayout = gd._fullLayout;
var sceneIds = fullLayout._subplots.gl3d;
for (var i = 0; i < sceneIds.length; i++) {
var sceneLayout = fullLayout[sceneIds[i]];
var scene = sceneLayout._scene;
scene.setViewport(sceneLayout);
}
};
exports.drawData = function (gd) {
var fullLayout = gd._fullLayout;
clearGlCanvases(gd);
// loop over the base plot modules present on graph
var basePlotModules = fullLayout._basePlotModules;
for (var i = 0; i < basePlotModules.length; i++) {
basePlotModules[i].plot(gd);
}
exports.redrawReglTraces(gd);
// styling separate from drawing
Plots.style(gd);
// draw components that can be drawn on axes,
// and that do not push the margins
Registry.getComponentMethod('selections', 'draw')(gd);
Registry.getComponentMethod('shapes', 'draw')(gd);
Registry.getComponentMethod('annotations', 'draw')(gd);
Registry.getComponentMethod('images', 'draw')(gd);
// Mark the first render as complete
fullLayout._replotting = false;
return Plots.previousPromises(gd);
};
// Draw (or redraw) all regl-based traces in one go,
// useful during drag and selection where buffers of targeted traces are updated,
// but all traces need to be redrawn following clearGlCanvases.
//
// Note that _module.plot for regl trace does NOT draw things
// on the canvas, they only update the buffers.
// Drawing is perform here.
//
// TODO try adding per-subplot option using gl.SCISSOR_TEST for
// non-overlaying, disjoint subplots.
//
// TODO try to include parcoords in here.
// https://github.com/plotly/plotly.js/issues/3069
exports.redrawReglTraces = function (gd) {
var fullLayout = gd._fullLayout;
if (fullLayout._has('regl')) {
var fullData = gd._fullData;
var cartesianIds = [];
var polarIds = [];
var i, sp;
if (fullLayout._hasOnlyLargeSploms) {
fullLayout._splomGrid.draw();
}
// N.B.
// - Loop over fullData (not _splomScenes) to preserve splom trace-to-trace ordering
// - Fill list if subplot ids (instead of fullLayout._subplots) to handle cases where all traces
// of a given module are `visible !== true`
for (i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (trace.visible === true && trace._length !== 0) {
if (trace.type === 'splom') {
fullLayout._splomScenes[trace.uid].draw();
} else if (trace.type === 'scattergl') {
Lib.pushUnique(cartesianIds, trace.xaxis + trace.yaxis);
} else if (trace.type === 'scatterpolargl') {
Lib.pushUnique(polarIds, trace.subplot);
}
}
}
for (i = 0; i < cartesianIds.length; i++) {
sp = fullLayout._plots[cartesianIds[i]];
if (sp._scene) sp._scene.draw();
}
for (i = 0; i < polarIds.length; i++) {
sp = fullLayout[polarIds[i]]._subplot;
if (sp._scene) sp._scene.draw();
}
}
};
exports.doAutoRangeAndConstraints = function (gd) {
var axList = Axes.list(gd, '', true);
var ax;
var autoRangeDone = {};
for (var i = 0; i < axList.length; i++) {
ax = axList[i];
if (!autoRangeDone[ax._id]) {
autoRangeDone[ax._id] = 1;
cleanAxisConstraints(gd, ax);
doAutoRange(gd, ax);
// For matching axes, just propagate this autorange to the group.
// The extra arg to doAutoRange avoids recalculating the range,
// since doAutoRange by itself accounts for all matching axes. but
// there are other side-effects of doAutoRange that we still want.
var matchGroup = ax._matchGroup;
if (matchGroup) {
for (var id2 in matchGroup) {
var ax2 = Axes.getFromId(gd, id2);
doAutoRange(gd, ax2, ax.range);
autoRangeDone[id2] = 1;
}
}
}
}
enforceAxisConstraints(gd);
};
// An initial paint must be completed before these components can be
// correctly sized and the whole plot re-margined. fullLayout._replotting must
// be set to false before these will work properly.
exports.finalDraw = function (gd) {
// TODO: rangesliders really belong in marginPushers but they need to be
// drawn after data - can we at least get the margin pushing part separated
// out and done earlier?
Registry.getComponentMethod('rangeslider', 'draw')(gd);
// TODO: rangeselector only needs to be here (in addition to drawMarginPushers)
// because the margins need to be fully determined before we can call
// autorange and update axis ranges (which rangeselector needs to know which
// button is active). Can we break out its automargin step from its draw step?
Registry.getComponentMethod('rangeselector', 'draw')(gd);
};
exports.drawMarginPushers = function (gd) {
Registry.getComponentMethod('legend', 'draw')(gd);
Registry.getComponentMethod('rangeselector', 'draw')(gd);
Registry.getComponentMethod('sliders', 'draw')(gd);
Registry.getComponentMethod('updatemenus', 'draw')(gd);
Registry.getComponentMethod('colorbar', 'draw')(gd);
};
/***/ }),
/***/ 94828:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var isPlainObject = Lib.isPlainObject;
var PlotSchema = __webpack_require__(73060);
var Plots = __webpack_require__(7316);
var plotAttributes = __webpack_require__(45464);
var Template = __webpack_require__(31780);
var dfltConfig = (__webpack_require__(20556).dfltConfig);
/**
* Plotly.makeTemplate: create a template off an existing figure to reuse
* style attributes on other figures.
*
* Note: separated from the rest of templates because otherwise we get circular
* references due to PlotSchema.
*
* @param {object|DOM element|string} figure: The figure to base the template on
* should contain a trace array `figure.data`
* and a layout object `figure.layout`
* @returns {object} template: the extracted template - can then be used as
* `layout.template` in another figure.
*/
exports.makeTemplate = function (figure) {
figure = Lib.isPlainObject(figure) ? figure : Lib.getGraphDiv(figure);
figure = Lib.extendDeep({
_context: dfltConfig
}, {
data: figure.data,
layout: figure.layout
});
Plots.supplyDefaults(figure);
var data = figure.data || [];
var layout = figure.layout || {};
// copy over a few items to help follow the schema
layout._basePlotModules = figure._fullLayout._basePlotModules;
layout._modules = figure._fullLayout._modules;
var template = {
data: {},
layout: {}
};
/*
* Note: we do NOT validate template values, we just take what's in the
* user inputs data and layout, not the validated values in fullData and
* fullLayout. Even if we were to validate here, there's no guarantee that
* these values would still be valid when applied to a new figure, which
* may contain different trace modes, different axes, etc. So it's
* important that when applying a template we still validate the template
* values, rather than just using them as defaults.
*/
data.forEach(function (trace) {
// TODO: What if no style info is extracted for this trace. We may
// not want an empty object as the null value.
// TODO: allow transforms to contribute to templates?
// as it stands they are ignored, which may be for the best...
var traceTemplate = {};
walkStyleKeys(trace, traceTemplate, getTraceInfo.bind(null, trace));
var traceType = Lib.coerce(trace, {}, plotAttributes, 'type');
var typeTemplates = template.data[traceType];
if (!typeTemplates) typeTemplates = template.data[traceType] = [];
typeTemplates.push(traceTemplate);
});
walkStyleKeys(layout, template.layout, getLayoutInfo.bind(null, layout));
/*
* Compose the new template with an existing one to the same effect
*
* NOTE: there's a possibility of slightly different behavior: if the plot
* has an invalid value and the old template has a valid value for the same
* attribute, the plot will use the old template value but this routine
* will pull the invalid value (resulting in the original default).
* In the general case it's not possible to solve this with a single value,
* since valid options can be context-dependent. It could be solved with
* a *list* of values, but that would be huge complexity for little gain.
*/
delete template.layout.template;
var oldTemplate = layout.template;
if (isPlainObject(oldTemplate)) {
var oldLayoutTemplate = oldTemplate.layout;
var i, traceType, oldTypeTemplates, oldTypeLen, typeTemplates, typeLen;
if (isPlainObject(oldLayoutTemplate)) {
mergeTemplates(oldLayoutTemplate, template.layout);
}
var oldDataTemplate = oldTemplate.data;
if (isPlainObject(oldDataTemplate)) {
for (traceType in template.data) {
oldTypeTemplates = oldDataTemplate[traceType];
if (Array.isArray(oldTypeTemplates)) {
typeTemplates = template.data[traceType];
typeLen = typeTemplates.length;
oldTypeLen = oldTypeTemplates.length;
for (i = 0; i < typeLen; i++) {
mergeTemplates(oldTypeTemplates[i % oldTypeLen], typeTemplates[i]);
}
for (i = typeLen; i < oldTypeLen; i++) {
typeTemplates.push(Lib.extendDeep({}, oldTypeTemplates[i]));
}
}
}
for (traceType in oldDataTemplate) {
if (!(traceType in template.data)) {
template.data[traceType] = Lib.extendDeep([], oldDataTemplate[traceType]);
}
}
}
}
return template;
};
function mergeTemplates(oldTemplate, newTemplate) {
// we don't care about speed here, just make sure we have a totally
// distinct object from the previous template
oldTemplate = Lib.extendDeep({}, oldTemplate);
// sort keys so we always get annotationdefaults before annotations etc
// so arrayTemplater will work right
var oldKeys = Object.keys(oldTemplate).sort();
var i, j;
function mergeOne(oldVal, newVal, key) {
if (isPlainObject(newVal) && isPlainObject(oldVal)) {
mergeTemplates(oldVal, newVal);
} else if (Array.isArray(newVal) && Array.isArray(oldVal)) {
// Note: omitted `inclusionAttr` from arrayTemplater here,
// it's irrelevant as we only want the resulting `_template`.
var templater = Template.arrayTemplater({
_template: oldTemplate
}, key);
for (j = 0; j < newVal.length; j++) {
var item = newVal[j];
var oldItem = templater.newItem(item)._template;
if (oldItem) mergeTemplates(oldItem, item);
}
var defaultItems = templater.defaultItems();
for (j = 0; j < defaultItems.length; j++) newVal.push(defaultItems[j]._template);
// templateitemname only applies to receiving plots
for (j = 0; j < newVal.length; j++) delete newVal[j].templateitemname;
}
}
for (i = 0; i < oldKeys.length; i++) {
var key = oldKeys[i];
var oldVal = oldTemplate[key];
if (key in newTemplate) {
mergeOne(oldVal, newTemplate[key], key);
} else newTemplate[key] = oldVal;
// if this is a base key from the old template (eg xaxis), look for
// extended keys (eg xaxis2) in the new template to merge into
if (getBaseKey(key) === key) {
for (var key2 in newTemplate) {
var baseKey2 = getBaseKey(key2);
if (key2 !== baseKey2 && baseKey2 === key && !(key2 in oldTemplate)) {
mergeOne(oldVal, newTemplate[key2], key);
}
}
}
}
}
function getBaseKey(key) {
return key.replace(/[0-9]+$/, '');
}
function walkStyleKeys(parent, templateOut, getAttributeInfo, path, basePath) {
var pathAttr = basePath && getAttributeInfo(basePath);
for (var key in parent) {
var child = parent[key];
var nextPath = getNextPath(parent, key, path);
var nextBasePath = getNextPath(parent, key, basePath);
var attr = getAttributeInfo(nextBasePath);
if (!attr) {
var baseKey = getBaseKey(key);
if (baseKey !== key) {
nextBasePath = getNextPath(parent, baseKey, basePath);
attr = getAttributeInfo(nextBasePath);
}
}
// we'll get an attr if path starts with a valid part, then has an
// invalid ending. Make sure we got all the way to the end.
if (pathAttr && pathAttr === attr) continue;
if (!attr || attr._noTemplating || attr.valType === 'data_array' || attr.arrayOk && Array.isArray(child)) {
continue;
}
if (!attr.valType && isPlainObject(child)) {
walkStyleKeys(child, templateOut, getAttributeInfo, nextPath, nextBasePath);
} else if (attr._isLinkedToArray && Array.isArray(child)) {
var dfltDone = false;
var namedIndex = 0;
var usedNames = {};
for (var i = 0; i < child.length; i++) {
var item = child[i];
if (isPlainObject(item)) {
var name = item.name;
if (name) {
if (!usedNames[name]) {
// named array items: allow all attributes except data arrays
walkStyleKeys(item, templateOut, getAttributeInfo, getNextPath(child, namedIndex, nextPath), getNextPath(child, namedIndex, nextBasePath));
namedIndex++;
usedNames[name] = 1;
}
} else if (!dfltDone) {
var dfltKey = Template.arrayDefaultKey(key);
var dfltPath = getNextPath(parent, dfltKey, path);
// getAttributeInfo will fail if we try to use dfltKey directly.
// Instead put this item into the next array element, then
// pull it out and move it to dfltKey.
var pathInArray = getNextPath(child, namedIndex, nextPath);
walkStyleKeys(item, templateOut, getAttributeInfo, pathInArray, getNextPath(child, namedIndex, nextBasePath));
var itemPropInArray = Lib.nestedProperty(templateOut, pathInArray);
var dfltProp = Lib.nestedProperty(templateOut, dfltPath);
dfltProp.set(itemPropInArray.get());
itemPropInArray.set(null);
dfltDone = true;
}
}
}
} else {
var templateProp = Lib.nestedProperty(templateOut, nextPath);
templateProp.set(child);
}
}
}
function getLayoutInfo(layout, path) {
return PlotSchema.getLayoutValObject(layout, Lib.nestedProperty({}, path).parts);
}
function getTraceInfo(trace, path) {
return PlotSchema.getTraceValObject(trace, Lib.nestedProperty({}, path).parts);
}
function getNextPath(parent, key, path) {
var nextPath;
if (!path) nextPath = key;else if (Array.isArray(parent)) nextPath = path + '[' + key + ']';else nextPath = path + '.' + key;
return nextPath;
}
/**
* validateTemplate: Test for consistency between the given figure and
* a template, either already included in the figure or given separately.
* Note that not every issue we identify here is necessarily a problem,
* it depends on what you're using the template for.
*
* @param {object|DOM element} figure: the plot, with {data, layout} members,
* to test the template against
* @param {Optional(object)} template: the template, with its own {data, layout},
* to test. If omitted, we will look for a template already attached as the
* plot's `layout.template` attribute.
*
* @returns {array} array of error objects each containing:
* - {string} code
* error code ('missing', 'unused', 'reused', 'noLayout', 'noData')
* - {string} msg
* a full readable description of the issue.
*/
exports.validateTemplate = function (figureIn, template) {
var figure = Lib.extendDeep({}, {
_context: dfltConfig,
data: figureIn.data,
layout: figureIn.layout
});
var layout = figure.layout || {};
if (!isPlainObject(template)) template = layout.template || {};
var layoutTemplate = template.layout;
var dataTemplate = template.data;
var errorList = [];
figure.layout = layout;
figure.layout.template = template;
Plots.supplyDefaults(figure);
var fullLayout = figure._fullLayout;
var fullData = figure._fullData;
var layoutPaths = {};
function crawlLayoutForContainers(obj, paths) {
for (var key in obj) {
if (key.charAt(0) !== '_' && isPlainObject(obj[key])) {
var baseKey = getBaseKey(key);
var nextPaths = [];
var i;
for (i = 0; i < paths.length; i++) {
nextPaths.push(getNextPath(obj, key, paths[i]));
if (baseKey !== key) nextPaths.push(getNextPath(obj, baseKey, paths[i]));
}
for (i = 0; i < nextPaths.length; i++) {
layoutPaths[nextPaths[i]] = 1;
}
crawlLayoutForContainers(obj[key], nextPaths);
}
}
}
function crawlLayoutTemplateForContainers(obj, path) {
for (var key in obj) {
if (key.indexOf('defaults') === -1 && isPlainObject(obj[key])) {
var nextPath = getNextPath(obj, key, path);
if (layoutPaths[nextPath]) {
crawlLayoutTemplateForContainers(obj[key], nextPath);
} else {
errorList.push({
code: 'unused',
path: nextPath
});
}
}
}
}
if (!isPlainObject(layoutTemplate)) {
errorList.push({
code: 'layout'
});
} else {
crawlLayoutForContainers(fullLayout, ['layout']);
crawlLayoutTemplateForContainers(layoutTemplate, 'layout');
}
if (!isPlainObject(dataTemplate)) {
errorList.push({
code: 'data'
});
} else {
var typeCount = {};
var traceType;
for (var i = 0; i < fullData.length; i++) {
var fullTrace = fullData[i];
traceType = fullTrace.type;
typeCount[traceType] = (typeCount[traceType] || 0) + 1;
if (!fullTrace._fullInput._template) {
// this takes care of the case of traceType in the data but not
// the template
errorList.push({
code: 'missing',
index: fullTrace._fullInput.index,
traceType: traceType
});
}
}
for (traceType in dataTemplate) {
var templateCount = dataTemplate[traceType].length;
var dataCount = typeCount[traceType] || 0;
if (templateCount > dataCount) {
errorList.push({
code: 'unused',
traceType: traceType,
templateCount: templateCount,
dataCount: dataCount
});
} else if (dataCount > templateCount) {
errorList.push({
code: 'reused',
traceType: traceType,
templateCount: templateCount,
dataCount: dataCount
});
}
}
}
// _template: false is when someone tried to modify an array item
// but there was no template with matching name
function crawlForMissingTemplates(obj, path) {
for (var key in obj) {
if (key.charAt(0) === '_') continue;
var val = obj[key];
var nextPath = getNextPath(obj, key, path);
if (isPlainObject(val)) {
if (Array.isArray(obj) && val._template === false && val.templateitemname) {
errorList.push({
code: 'missing',
path: nextPath,
templateitemname: val.templateitemname
});
}
crawlForMissingTemplates(val, nextPath);
} else if (Array.isArray(val) && hasPlainObject(val)) {
crawlForMissingTemplates(val, nextPath);
}
}
}
crawlForMissingTemplates({
data: fullData,
layout: fullLayout
}, '');
if (errorList.length) return errorList.map(format);
};
function hasPlainObject(arr) {
for (var i = 0; i < arr.length; i++) {
if (isPlainObject(arr[i])) return true;
}
}
function format(opts) {
var msg;
switch (opts.code) {
case 'data':
msg = 'The template has no key data.';
break;
case 'layout':
msg = 'The template has no key layout.';
break;
case 'missing':
if (opts.path) {
msg = 'There are no templates for item ' + opts.path + ' with name ' + opts.templateitemname;
} else {
msg = 'There are no templates for trace ' + opts.index + ', of type ' + opts.traceType + '.';
}
break;
case 'unused':
if (opts.path) {
msg = 'The template item at ' + opts.path + ' was not used in constructing the plot.';
} else if (opts.dataCount) {
msg = 'Some of the templates of type ' + opts.traceType + ' were not used. The template has ' + opts.templateCount + ' traces, the data only has ' + opts.dataCount + ' of this type.';
} else {
msg = 'The template has ' + opts.templateCount + ' traces of type ' + opts.traceType + ' but there are none in the data.';
}
break;
case 'reused':
msg = 'Some of the templates of type ' + opts.traceType + ' were used more than once. The template has ' + opts.templateCount + ' traces, the data has ' + opts.dataCount + ' of this type.';
break;
}
opts.msg = msg;
return opts;
}
/***/ }),
/***/ 67024:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var plotApi = __webpack_require__(36424);
var plots = __webpack_require__(7316);
var Lib = __webpack_require__(3400);
var helpers = __webpack_require__(81792);
var toSVG = __webpack_require__(37164);
var svgToImg = __webpack_require__(63268);
var version = (__webpack_require__(25788).version);
var attrs = {
format: {
valType: 'enumerated',
values: ['png', 'jpeg', 'webp', 'svg', 'full-json'],
dflt: 'png'
},
width: {
valType: 'number',
min: 1
},
height: {
valType: 'number',
min: 1
},
scale: {
valType: 'number',
min: 0,
dflt: 1
},
setBackground: {
valType: 'any',
dflt: false
},
imageDataOnly: {
valType: 'boolean',
dflt: false
}
};
/** Plotly.toImage
*
* @param {object | string | HTML div} gd
* can either be a data/layout/config object
* or an existing graph
* or an id to an existing graph
* @param {object} opts (see above)
* @return {promise}
*/
function toImage(gd, opts) {
opts = opts || {};
var data;
var layout;
var config;
var fullLayout;
if (Lib.isPlainObject(gd)) {
data = gd.data || [];
layout = gd.layout || {};
config = gd.config || {};
fullLayout = {};
} else {
gd = Lib.getGraphDiv(gd);
data = Lib.extendDeep([], gd.data);
layout = Lib.extendDeep({}, gd.layout);
config = gd._context;
fullLayout = gd._fullLayout || {};
}
function isImpliedOrValid(attr) {
return !(attr in opts) || Lib.validate(opts[attr], attrs[attr]);
}
if (!isImpliedOrValid('width') && opts.width !== null || !isImpliedOrValid('height') && opts.height !== null) {
throw new Error('Height and width should be pixel values.');
}
if (!isImpliedOrValid('format')) {
throw new Error('Export format is not ' + Lib.join2(attrs.format.values, ', ', ' or ') + '.');
}
var fullOpts = {};
function coerce(attr, dflt) {
return Lib.coerce(opts, fullOpts, attrs, attr, dflt);
}
var format = coerce('format');
var width = coerce('width');
var height = coerce('height');
var scale = coerce('scale');
var setBackground = coerce('setBackground');
var imageDataOnly = coerce('imageDataOnly');
// put the cloned div somewhere off screen before attaching to DOM
var clonedGd = document.createElement('div');
clonedGd.style.position = 'absolute';
clonedGd.style.left = '-5000px';
document.body.appendChild(clonedGd);
// extend layout with image options
var layoutImage = Lib.extendFlat({}, layout);
if (width) {
layoutImage.width = width;
} else if (opts.width === null && isNumeric(fullLayout.width)) {
layoutImage.width = fullLayout.width;
}
if (height) {
layoutImage.height = height;
} else if (opts.height === null && isNumeric(fullLayout.height)) {
layoutImage.height = fullLayout.height;
}
// extend config for static plot
var configImage = Lib.extendFlat({}, config, {
_exportedPlot: true,
staticPlot: true,
setBackground: setBackground
});
var redrawFunc = helpers.getRedrawFunc(clonedGd);
function wait() {
return new Promise(function (resolve) {
setTimeout(resolve, helpers.getDelay(clonedGd._fullLayout));
});
}
function convert() {
return new Promise(function (resolve, reject) {
var svg = toSVG(clonedGd, format, scale);
var width = clonedGd._fullLayout.width;
var height = clonedGd._fullLayout.height;
function cleanup() {
plotApi.purge(clonedGd);
document.body.removeChild(clonedGd);
}
if (format === 'full-json') {
var json = plots.graphJson(clonedGd, false, 'keepdata', 'object', true, true);
json.version = version;
json = JSON.stringify(json);
cleanup();
if (imageDataOnly) {
return resolve(json);
} else {
return resolve(helpers.encodeJSON(json));
}
}
cleanup();
if (format === 'svg') {
if (imageDataOnly) {
return resolve(svg);
} else {
return resolve(helpers.encodeSVG(svg));
}
}
var canvas = document.createElement('canvas');
canvas.id = Lib.randstr();
svgToImg({
format: format,
width: width,
height: height,
scale: scale,
canvas: canvas,
svg: svg,
// ask svgToImg to return a Promise
// rather than EventEmitter
// leave EventEmitter for backward
// compatibility
promise: true
}).then(resolve).catch(reject);
});
}
function urlToImageData(url) {
if (imageDataOnly) {
return url.replace(helpers.IMAGE_URL_PREFIX, '');
} else {
return url;
}
}
return new Promise(function (resolve, reject) {
plotApi.newPlot(clonedGd, data, layoutImage, configImage).then(redrawFunc).then(wait).then(convert).then(function (url) {
resolve(urlToImageData(url));
}).catch(function (err) {
reject(err);
});
});
}
module.exports = toImage;
/***/ }),
/***/ 21480:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Plots = __webpack_require__(7316);
var PlotSchema = __webpack_require__(73060);
var dfltConfig = (__webpack_require__(20556).dfltConfig);
var isPlainObject = Lib.isPlainObject;
var isArray = Array.isArray;
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
/**
* Validate a data array and layout object.
*
* @param {array} data
* @param {object} layout
*
* @return {array} array of error objects each containing:
* - {string} code
* error code ('object', 'array', 'schema', 'unused', 'invisible' or 'value')
* - {string} container
* container where the error occurs ('data' or 'layout')
* - {number} trace
* trace index of the 'data' container where the error occurs
* - {array} path
* nested path to the key that causes the error
* - {string} astr
* attribute string variant of 'path' compatible with Plotly.restyle and
* Plotly.relayout.
* - {string} msg
* error message (shown in console in logger config argument is enable)
*/
module.exports = function validate(data, layout) {
if (data === undefined) data = [];
if (layout === undefined) layout = {};
var schema = PlotSchema.get();
var errorList = [];
var gd = {
_context: Lib.extendFlat({}, dfltConfig)
};
var dataIn, layoutIn;
if (isArray(data)) {
gd.data = Lib.extendDeep([], data);
dataIn = data;
} else {
gd.data = [];
dataIn = [];
errorList.push(format('array', 'data'));
}
if (isPlainObject(layout)) {
gd.layout = Lib.extendDeep({}, layout);
layoutIn = layout;
} else {
gd.layout = {};
layoutIn = {};
if (arguments.length > 1) {
errorList.push(format('object', 'layout'));
}
}
// N.B. dataIn and layoutIn are in general not the same as
// gd.data and gd.layout after supplyDefaults as some attributes
// in gd.data and gd.layout (still) get mutated during this step.
Plots.supplyDefaults(gd);
var dataOut = gd._fullData;
var len = dataIn.length;
for (var i = 0; i < len; i++) {
var traceIn = dataIn[i];
var base = ['data', i];
if (!isPlainObject(traceIn)) {
errorList.push(format('object', base));
continue;
}
var traceOut = dataOut[i];
var traceType = traceOut.type;
var traceSchema = schema.traces[traceType].attributes;
// PlotSchema does something fancy with trace 'type', reset it here
// to make the trace schema compatible with Lib.validate.
traceSchema.type = {
valType: 'enumerated',
values: [traceType]
};
if (traceOut.visible === false && traceIn.visible !== false) {
errorList.push(format('invisible', base));
}
crawl(traceIn, traceOut, traceSchema, errorList, base);
var transformsIn = traceIn.transforms;
var transformsOut = traceOut.transforms;
if (transformsIn) {
if (!isArray(transformsIn)) {
errorList.push(format('array', base, ['transforms']));
}
base.push('transforms');
for (var j = 0; j < transformsIn.length; j++) {
var path = ['transforms', j];
var transformType = transformsIn[j].type;
if (!isPlainObject(transformsIn[j])) {
errorList.push(format('object', base, path));
continue;
}
var transformSchema = schema.transforms[transformType] ? schema.transforms[transformType].attributes : {};
// add 'type' to transform schema to validate the transform type
transformSchema.type = {
valType: 'enumerated',
values: Object.keys(schema.transforms)
};
crawl(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path);
}
}
}
var layoutOut = gd._fullLayout;
var layoutSchema = fillLayoutSchema(schema, dataOut);
crawl(layoutIn, layoutOut, layoutSchema, errorList, 'layout');
// return undefined if no validation errors were found
return errorList.length === 0 ? void 0 : errorList;
};
function crawl(objIn, objOut, schema, list, base, path) {
path = path || [];
var keys = Object.keys(objIn);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
// transforms are handled separately
if (k === 'transforms') continue;
var p = path.slice();
p.push(k);
var valIn = objIn[k];
var valOut = objOut[k];
var nestedSchema = getNestedSchema(schema, k);
var nestedValType = (nestedSchema || {}).valType;
var isInfoArray = nestedValType === 'info_array';
var isColorscale = nestedValType === 'colorscale';
var items = (nestedSchema || {}).items;
if (!isInSchema(schema, k)) {
list.push(format('schema', base, p));
} else if (isPlainObject(valIn) && isPlainObject(valOut) && nestedValType !== 'any') {
crawl(valIn, valOut, nestedSchema, list, base, p);
} else if (isInfoArray && isArray(valIn)) {
if (valIn.length > valOut.length) {
list.push(format('unused', base, p.concat(valOut.length)));
}
var len = valOut.length;
var arrayItems = Array.isArray(items);
if (arrayItems) len = Math.min(len, items.length);
var m, n, item, valInPart, valOutPart;
if (nestedSchema.dimensions === 2) {
for (n = 0; n < len; n++) {
if (isArray(valIn[n])) {
if (valIn[n].length > valOut[n].length) {
list.push(format('unused', base, p.concat(n, valOut[n].length)));
}
var len2 = valOut[n].length;
for (m = 0; m < (arrayItems ? Math.min(len2, items[n].length) : len2); m++) {
item = arrayItems ? items[n][m] : items;
valInPart = valIn[n][m];
valOutPart = valOut[n][m];
if (!Lib.validate(valInPart, item)) {
list.push(format('value', base, p.concat(n, m), valInPart));
} else if (valOutPart !== valInPart && valOutPart !== +valInPart) {
list.push(format('dynamic', base, p.concat(n, m), valInPart, valOutPart));
}
}
} else {
list.push(format('array', base, p.concat(n), valIn[n]));
}
}
} else {
for (n = 0; n < len; n++) {
item = arrayItems ? items[n] : items;
valInPart = valIn[n];
valOutPart = valOut[n];
if (!Lib.validate(valInPart, item)) {
list.push(format('value', base, p.concat(n), valInPart));
} else if (valOutPart !== valInPart && valOutPart !== +valInPart) {
list.push(format('dynamic', base, p.concat(n), valInPart, valOutPart));
}
}
}
} else if (nestedSchema.items && !isInfoArray && isArray(valIn)) {
var _nestedSchema = items[Object.keys(items)[0]];
var indexList = [];
var j, _p;
// loop over valOut items while keeping track of their
// corresponding input container index (given by _index)
for (j = 0; j < valOut.length; j++) {
var _index = valOut[j]._index || j;
_p = p.slice();
_p.push(_index);
if (isPlainObject(valIn[_index]) && isPlainObject(valOut[j])) {
indexList.push(_index);
var valInj = valIn[_index];
var valOutj = valOut[j];
if (isPlainObject(valInj) && valInj.visible !== false && valOutj.visible === false) {
list.push(format('invisible', base, _p));
} else crawl(valInj, valOutj, _nestedSchema, list, base, _p);
}
}
// loop over valIn to determine where it went wrong for some items
for (j = 0; j < valIn.length; j++) {
_p = p.slice();
_p.push(j);
if (!isPlainObject(valIn[j])) {
list.push(format('object', base, _p, valIn[j]));
} else if (indexList.indexOf(j) === -1) {
list.push(format('unused', base, _p));
}
}
} else if (!isPlainObject(valIn) && isPlainObject(valOut)) {
list.push(format('object', base, p, valIn));
} else if (!isArrayOrTypedArray(valIn) && isArrayOrTypedArray(valOut) && !isInfoArray && !isColorscale) {
list.push(format('array', base, p, valIn));
} else if (!(k in objOut)) {
list.push(format('unused', base, p, valIn));
} else if (!Lib.validate(valIn, nestedSchema)) {
list.push(format('value', base, p, valIn));
} else if (nestedSchema.valType === 'enumerated' && (nestedSchema.coerceNumber && valIn !== +valOut || valIn !== valOut)) {
list.push(format('dynamic', base, p, valIn, valOut));
}
}
return list;
}
// the 'full' layout schema depends on the traces types presents
function fillLayoutSchema(schema, dataOut) {
var layoutSchema = schema.layout.layoutAttributes;
for (var i = 0; i < dataOut.length; i++) {
var traceOut = dataOut[i];
var traceSchema = schema.traces[traceOut.type];
var traceLayoutAttr = traceSchema.layoutAttributes;
if (traceLayoutAttr) {
if (traceOut.subplot) {
Lib.extendFlat(layoutSchema[traceSchema.attributes.subplot.dflt], traceLayoutAttr);
} else {
Lib.extendFlat(layoutSchema, traceLayoutAttr);
}
}
}
return layoutSchema;
}
// validation error codes
var code2msgFunc = {
object: function (base, astr) {
var prefix;
if (base === 'layout' && astr === '') prefix = 'The layout argument';else if (base[0] === 'data' && astr === '') {
prefix = 'Trace ' + base[1] + ' in the data argument';
} else prefix = inBase(base) + 'key ' + astr;
return prefix + ' must be linked to an object container';
},
array: function (base, astr) {
var prefix;
if (base === 'data') prefix = 'The data argument';else prefix = inBase(base) + 'key ' + astr;
return prefix + ' must be linked to an array container';
},
schema: function (base, astr) {
return inBase(base) + 'key ' + astr + ' is not part of the schema';
},
unused: function (base, astr, valIn) {
var target = isPlainObject(valIn) ? 'container' : 'key';
return inBase(base) + target + ' ' + astr + ' did not get coerced';
},
dynamic: function (base, astr, valIn, valOut) {
return [inBase(base) + 'key', astr, '(set to \'' + valIn + '\')', 'got reset to', '\'' + valOut + '\'', 'during defaults.'].join(' ');
},
invisible: function (base, astr) {
return (astr ? inBase(base) + 'item ' + astr : 'Trace ' + base[1]) + ' got defaulted to be not visible';
},
value: function (base, astr, valIn) {
return [inBase(base) + 'key ' + astr, 'is set to an invalid value (' + valIn + ')'].join(' ');
}
};
function inBase(base) {
if (isArray(base)) return 'In data trace ' + base[1] + ', ';
return 'In ' + base + ', ';
}
function format(code, base, path, valIn, valOut) {
path = path || '';
var container, trace;
// container is either 'data' or 'layout
// trace is the trace index if 'data', null otherwise
if (isArray(base)) {
container = base[0];
trace = base[1];
} else {
container = base;
trace = null;
}
var astr = convertPathToAttributeString(path);
var msg = code2msgFunc[code](base, astr, valIn, valOut);
// log to console if logger config option is enabled
Lib.log(msg);
return {
code: code,
container: container,
trace: trace,
path: path,
astr: astr,
msg: msg
};
}
function isInSchema(schema, key) {
var parts = splitKey(key);
var keyMinusId = parts.keyMinusId;
var id = parts.id;
if (keyMinusId in schema && schema[keyMinusId]._isSubplotObj && id) {
return true;
}
return key in schema;
}
function getNestedSchema(schema, key) {
if (key in schema) return schema[key];
var parts = splitKey(key);
return schema[parts.keyMinusId];
}
var idRegex = Lib.counterRegex('([a-z]+)');
function splitKey(key) {
var idMatch = key.match(idRegex);
return {
keyMinusId: idMatch && idMatch[1],
id: idMatch && idMatch[2]
};
}
function convertPathToAttributeString(path) {
if (!isArray(path)) return String(path);
var astr = '';
for (var i = 0; i < path.length; i++) {
var p = path[i];
if (typeof p === 'number') {
astr = astr.substr(0, astr.length - 1) + '[' + p + ']';
} else {
astr += p;
}
if (i < path.length - 1) astr += '.';
}
return astr;
}
/***/ }),
/***/ 85656:
/***/ (function(module) {
"use strict";
module.exports = {
mode: {
valType: 'enumerated',
dflt: 'afterall',
values: ['immediate', 'next', 'afterall']
},
direction: {
valType: 'enumerated',
values: ['forward', 'reverse'],
dflt: 'forward'
},
fromcurrent: {
valType: 'boolean',
dflt: false
},
frame: {
duration: {
valType: 'number',
min: 0,
dflt: 500
},
redraw: {
valType: 'boolean',
dflt: true
}
},
transition: {
duration: {
valType: 'number',
min: 0,
dflt: 500,
editType: 'none'
},
easing: {
valType: 'enumerated',
dflt: 'cubic-in-out',
values: ['linear', 'quad', 'cubic', 'sin', 'exp', 'circle', 'elastic', 'back', 'bounce', 'linear-in', 'quad-in', 'cubic-in', 'sin-in', 'exp-in', 'circle-in', 'elastic-in', 'back-in', 'bounce-in', 'linear-out', 'quad-out', 'cubic-out', 'sin-out', 'exp-out', 'circle-out', 'elastic-out', 'back-out', 'bounce-out', 'linear-in-out', 'quad-in-out', 'cubic-in-out', 'sin-in-out', 'exp-in-out', 'circle-in-out', 'elastic-in-out', 'back-in-out', 'bounce-in-out'],
editType: 'none'
},
ordering: {
valType: 'enumerated',
values: ['layout first', 'traces first'],
dflt: 'layout first',
editType: 'none'
}
}
};
/***/ }),
/***/ 51272:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
/** Convenience wrapper for making array container logic DRY and consistent
*
* @param {object} parentObjIn
* user input object where the container in question is linked
* (i.e. either a user trace object or the user layout object)
*
* @param {object} parentObjOut
* full object where the coerced container will be linked
* (i.e. either a full trace object or the full layout object)
*
* @param {object} opts
* options object:
* - name {string}
* name of the key linking the container in question
* - inclusionAttr {string}
* name of the item attribute for inclusion/exclusion. Default is 'visible'.
* Since inclusion is true, use eg 'enabled' instead of 'disabled'.
* - handleItemDefaults {function}
* defaults method to be called on each item in the array container in question
*
* Its arguments are:
* - itemIn {object} item in user layout
* - itemOut {object} item in full layout
* - parentObj {object} (as in closure)
* - opts {object} (as in closure)
* N.B.
*
* - opts is passed to handleItemDefaults so it can also store
* links to supplementary data (e.g. fullData for layout components)
*
*/
module.exports = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) {
var name = opts.name;
var inclusionAttr = opts.inclusionAttr || 'visible';
var previousContOut = parentObjOut[name];
var contIn = Lib.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [];
var contOut = parentObjOut[name] = [];
var templater = Template.arrayTemplater(parentObjOut, name, inclusionAttr);
var i, itemOut;
for (i = 0; i < contIn.length; i++) {
var itemIn = contIn[i];
if (!Lib.isPlainObject(itemIn)) {
itemOut = templater.newItem({});
itemOut[inclusionAttr] = false;
} else {
itemOut = templater.newItem(itemIn);
}
itemOut._index = i;
if (itemOut[inclusionAttr] !== false) {
opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts);
}
contOut.push(itemOut);
}
var defaultItems = templater.defaultItems();
for (i = 0; i < defaultItems.length; i++) {
itemOut = defaultItems[i];
itemOut._index = contOut.length;
opts.handleItemDefaults({}, itemOut, parentObjOut, opts, {});
contOut.push(itemOut);
}
// in case this array gets its defaults rebuilt independent of the whole layout,
// relink the private keys just for this array.
if (Lib.isArrayOrTypedArray(previousContOut)) {
var len = Math.min(previousContOut.length, contOut.length);
for (i = 0; i < len; i++) {
Lib.relinkPrivateKeys(contOut[i], previousContOut[i]);
}
}
return contOut;
};
/***/ }),
/***/ 45464:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var fxAttrs = __webpack_require__(55756);
module.exports = {
type: {
valType: 'enumerated',
values: [],
// listed dynamically
dflt: 'scatter',
editType: 'calc+clearAxisTypes',
_noTemplating: true // we handle this at a higher level
},
visible: {
valType: 'enumerated',
values: [true, false, 'legendonly'],
dflt: true,
editType: 'calc'
},
showlegend: {
valType: 'boolean',
dflt: true,
editType: 'style'
},
legend: {
valType: 'subplotid',
dflt: 'legend',
editType: 'style'
},
legendgroup: {
valType: 'string',
dflt: '',
editType: 'style'
},
legendgrouptitle: {
text: {
valType: 'string',
dflt: '',
editType: 'style'
},
font: fontAttrs({
editType: 'style'
}),
editType: 'style'
},
legendrank: {
valType: 'number',
dflt: 1000,
editType: 'style'
},
legendwidth: {
valType: 'number',
min: 0,
editType: 'style'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1,
editType: 'style'
},
name: {
valType: 'string',
editType: 'style'
},
uid: {
valType: 'string',
editType: 'plot',
anim: true
},
ids: {
valType: 'data_array',
editType: 'calc',
anim: true
},
customdata: {
valType: 'data_array',
editType: 'calc'
},
meta: {
valType: 'any',
arrayOk: true,
editType: 'plot'
},
// N.B. these cannot be 'data_array' as they do not have the same length as
// other data arrays and arrayOk attributes in general
//
// Maybe add another valType:
// https://github.com/plotly/plotly.js/issues/1894
selectedpoints: {
valType: 'any',
editType: 'calc'
},
hoverinfo: {
valType: 'flaglist',
flags: ['x', 'y', 'z', 'text', 'name'],
extras: ['all', 'none', 'skip'],
arrayOk: true,
dflt: 'all',
editType: 'none'
},
hoverlabel: fxAttrs.hoverlabel,
stream: {
token: {
valType: 'string',
noBlank: true,
strict: true,
editType: 'calc'
},
maxpoints: {
valType: 'number',
min: 0,
max: 10000,
dflt: 500,
editType: 'calc'
},
editType: 'calc'
},
transforms: {
_isLinkedToArray: 'transform',
editType: 'calc'
},
uirevision: {
valType: 'any',
editType: 'none'
}
};
/***/ }),
/***/ 1220:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var dateTime2ms = Lib.dateTime2ms;
var incrementMonth = Lib.incrementMonth;
var constants = __webpack_require__(39032);
var ONEAVGMONTH = constants.ONEAVGMONTH;
module.exports = function alignPeriod(trace, ax, axLetter, vals) {
if (ax.type !== 'date') return {
vals: vals
};
var alignment = trace[axLetter + 'periodalignment'];
if (!alignment) return {
vals: vals
};
var period = trace[axLetter + 'period'];
var mPeriod;
if (isNumeric(period)) {
period = +period;
if (period <= 0) return {
vals: vals
};
} else if (typeof period === 'string' && period.charAt(0) === 'M') {
var n = +period.substring(1);
if (n > 0 && Math.round(n) === n) {
mPeriod = n;
} else return {
vals: vals
};
}
var calendar = ax.calendar;
var isStart = 'start' === alignment;
// var isMiddle = 'middle' === alignment;
var isEnd = 'end' === alignment;
var period0 = trace[axLetter + 'period0'];
var base = dateTime2ms(period0, calendar) || 0;
var newVals = [];
var starts = [];
var ends = [];
var len = vals.length;
for (var i = 0; i < len; i++) {
var v = vals[i];
var nEstimated, startTime, endTime;
if (mPeriod) {
// guess at how many periods away from base we are
nEstimated = Math.round((v - base) / (mPeriod * ONEAVGMONTH));
endTime = incrementMonth(base, mPeriod * nEstimated, calendar);
// iterate to get the exact bounds before and after v
// there may be ways to make this faster, but most of the time
// we'll only execute each loop zero or one time.
while (endTime > v) {
endTime = incrementMonth(endTime, -mPeriod, calendar);
}
while (endTime <= v) {
endTime = incrementMonth(endTime, mPeriod, calendar);
}
// now we know endTime is the boundary immediately after v
// so startTime is obtained by incrementing backward one period.
startTime = incrementMonth(endTime, -mPeriod, calendar);
} else {
// case of ms
nEstimated = Math.round((v - base) / period);
endTime = base + nEstimated * period;
while (endTime > v) {
endTime -= period;
}
while (endTime <= v) {
endTime += period;
}
startTime = endTime - period;
}
newVals[i] = isStart ? startTime : isEnd ? endTime : (startTime + endTime) / 2;
starts[i] = startTime;
ends[i] = endTime;
}
return {
vals: newVals,
starts: starts,
ends: ends
};
};
/***/ }),
/***/ 26720:
/***/ (function(module) {
"use strict";
module.exports = {
xaxis: {
valType: 'subplotid',
dflt: 'x',
editType: 'calc+clearAxisTypes'
},
yaxis: {
valType: 'subplotid',
dflt: 'y',
editType: 'calc+clearAxisTypes'
}
};
/***/ }),
/***/ 19280:
/***/ (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 FP_SAFE = (__webpack_require__(39032).FP_SAFE);
var Registry = __webpack_require__(24040);
var Drawing = __webpack_require__(43616);
var axIds = __webpack_require__(79811);
var getFromId = axIds.getFromId;
var isLinked = axIds.isLinked;
module.exports = {
applyAutorangeOptions: applyAutorangeOptions,
getAutoRange: getAutoRange,
makePadFn: makePadFn,
doAutoRange: doAutoRange,
findExtremes: findExtremes,
concatExtremes: concatExtremes
};
/**
* getAutoRange
*
* Collects all _extremes values corresponding to a given axis
* and computes its auto range.
*
* Note that getAutoRange uses return values from findExtremes.
*
* @param {object} gd:
* graph div object with filled-in fullData and fullLayout, in particular
* with filled-in '_extremes' containers:
* {
* val: calcdata value,
* pad: extra pixels beyond this value,
* extrapad: bool, does this point want 5% extra padding
* }
* @param {object} ax:
* full axis object, in particular with filled-in '_traceIndices'
* and '_annIndices' / '_shapeIndices' if applicable
* @return {array}
* an array of [min, max]. These are calcdata for log and category axes
* and data for linear and date axes.
*
* TODO: we want to change log to data as well, but it's hard to do this
* maintaining backward compatibility. category will always have to use calcdata
* though, because otherwise values between categories (or outside all categories)
* would be impossible.
*/
function getAutoRange(gd, ax) {
var i, j;
var newRange = [];
var fullLayout = gd._fullLayout;
var getPadMin = makePadFn(fullLayout, ax, 0);
var getPadMax = makePadFn(fullLayout, ax, 1);
var extremes = concatExtremes(gd, ax);
var minArray = extremes.min;
var maxArray = extremes.max;
if (minArray.length === 0 || maxArray.length === 0) {
return Lib.simpleMap(ax.range, ax.r2l);
}
var minmin = minArray[0].val;
var maxmax = maxArray[0].val;
for (i = 1; i < minArray.length; i++) {
if (minmin !== maxmax) break;
minmin = Math.min(minmin, minArray[i].val);
}
for (i = 1; i < maxArray.length; i++) {
if (minmin !== maxmax) break;
maxmax = Math.max(maxmax, maxArray[i].val);
}
var autorange = ax.autorange;
var axReverse = autorange === 'reversed' || autorange === 'min reversed' || autorange === 'max reversed';
if (!axReverse && ax.range) {
var rng = Lib.simpleMap(ax.range, ax.r2l);
axReverse = rng[1] < rng[0];
}
// one-time setting to easily reverse the axis
// when plotting from code
if (ax.autorange === 'reversed') {
ax.autorange = true;
}
var rangeMode = ax.rangemode;
var toZero = rangeMode === 'tozero';
var nonNegative = rangeMode === 'nonnegative';
var axLen = ax._length;
// don't allow padding to reduce the data to < 10% of the length
var minSpan = axLen / 10;
var mbest = 0;
var minpt, maxpt, minbest, maxbest, dp, dv;
for (i = 0; i < minArray.length; i++) {
minpt = minArray[i];
for (j = 0; j < maxArray.length; j++) {
maxpt = maxArray[j];
dv = maxpt.val - minpt.val - calcBreaksLength(ax, minpt.val, maxpt.val);
if (dv > 0) {
dp = axLen - getPadMin(minpt) - getPadMax(maxpt);
if (dp > minSpan) {
if (dv / dp > mbest) {
minbest = minpt;
maxbest = maxpt;
mbest = dv / dp;
}
} else if (dv / axLen > mbest) {
// in case of padding longer than the axis
// at least include the unpadded data values.
minbest = {
val: minpt.val,
nopad: 1
};
maxbest = {
val: maxpt.val,
nopad: 1
};
mbest = dv / axLen;
}
}
}
}
function maximumPad(prev, pt) {
return Math.max(prev, getPadMax(pt));
}
if (minmin === maxmax) {
var lower = minmin - 1;
var upper = minmin + 1;
if (toZero) {
if (minmin === 0) {
// The only value we have on this axis is 0, and we want to
// autorange so zero is one end.
// In principle this could be [0, 1] or [-1, 0] but usually
// 'tozero' pins 0 to the low end, so follow that.
newRange = [0, 1];
} else {
var maxPad = (minmin > 0 ? maxArray : minArray).reduce(maximumPad, 0);
// we're pushing a single value away from the edge due to its
// padding, with the other end clamped at zero
// 0.5 means don't push it farther than the center.
var rangeEnd = minmin / (1 - Math.min(0.5, maxPad / axLen));
newRange = minmin > 0 ? [0, rangeEnd] : [rangeEnd, 0];
}
} else if (nonNegative) {
newRange = [Math.max(0, lower), Math.max(1, upper)];
} else {
newRange = [lower, upper];
}
} else {
if (toZero) {
if (minbest.val >= 0) {
minbest = {
val: 0,
nopad: 1
};
}
if (maxbest.val <= 0) {
maxbest = {
val: 0,
nopad: 1
};
}
} else if (nonNegative) {
if (minbest.val - mbest * getPadMin(minbest) < 0) {
minbest = {
val: 0,
nopad: 1
};
}
if (maxbest.val <= 0) {
maxbest = {
val: 1,
nopad: 1
};
}
}
// in case it changed again...
mbest = (maxbest.val - minbest.val - calcBreaksLength(ax, minpt.val, maxpt.val)) / (axLen - getPadMin(minbest) - getPadMax(maxbest));
newRange = [minbest.val - mbest * getPadMin(minbest), maxbest.val + mbest * getPadMax(maxbest)];
}
newRange = applyAutorangeOptions(newRange, ax);
if (ax.limitRange) ax.limitRange();
// maintain reversal
if (axReverse) newRange.reverse();
return Lib.simpleMap(newRange, ax.l2r || Number);
}
// find axis rangebreaks in [v0,v1] and compute its length in value space
function calcBreaksLength(ax, v0, v1) {
var lBreaks = 0;
if (ax.rangebreaks) {
var rangebreaksOut = ax.locateBreaks(v0, v1);
for (var i = 0; i < rangebreaksOut.length; i++) {
var brk = rangebreaksOut[i];
lBreaks += brk.max - brk.min;
}
}
return lBreaks;
}
/*
* calculate the pixel padding for ax._min and ax._max entries with
* optional extrapad as 5% of the total axis length
*/
function makePadFn(fullLayout, ax, max) {
// 5% padding for points that specify extrapad: true
var extrappad = 0.05 * ax._length;
var anchorAxis = ax._anchorAxis || {};
if ((ax.ticklabelposition || '').indexOf('inside') !== -1 || (anchorAxis.ticklabelposition || '').indexOf('inside') !== -1) {
var axReverse = ax.isReversed();
if (!axReverse) {
var rng = Lib.simpleMap(ax.range, ax.r2l);
axReverse = rng[1] < rng[0];
}
if (axReverse) max = !max;
}
var zero = 0;
if (!isLinked(fullLayout, ax._id)) {
zero = padInsideLabelsOnAnchorAxis(fullLayout, ax, max);
}
extrappad = Math.max(zero, extrappad);
// domain-constrained axes: base extrappad on the unconstrained
// domain so it's consistent as the domain changes
if (ax.constrain === 'domain' && ax._inputDomain) {
extrappad *= (ax._inputDomain[1] - ax._inputDomain[0]) / (ax.domain[1] - ax.domain[0]);
}
return function getPad(pt) {
if (pt.nopad) return 0;
return pt.pad + (pt.extrapad ? extrappad : zero);
};
}
var TEXTPAD = 3;
function padInsideLabelsOnAnchorAxis(fullLayout, ax, max) {
var pad = 0;
var isX = ax._id.charAt(0) === 'x';
for (var subplot in fullLayout._plots) {
var plotinfo = fullLayout._plots[subplot];
if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue;
var anchorAxis = (isX ? plotinfo.yaxis : plotinfo.xaxis) || {};
if ((anchorAxis.ticklabelposition || '').indexOf('inside') !== -1) {
// increase padding to make more room for inside tick labels of the counter axis
if (!max && (anchorAxis.side === 'left' || anchorAxis.side === 'bottom') || max && (anchorAxis.side === 'top' || anchorAxis.side === 'right')) {
if (anchorAxis._vals) {
var rad = Lib.deg2rad(anchorAxis._tickAngles[anchorAxis._id + 'tick'] || 0);
var cosA = Math.abs(Math.cos(rad));
var sinA = Math.abs(Math.sin(rad));
// no stashed bounding boxes - stash bounding boxes
if (!anchorAxis._vals[0].bb) {
var cls = anchorAxis._id + 'tick';
var tickLabels = anchorAxis._selections[cls];
tickLabels.each(function (d) {
var thisLabel = d3.select(this);
var mathjaxGroup = thisLabel.select('.text-math-group');
if (mathjaxGroup.empty()) {
d.bb = Drawing.bBox(thisLabel.node());
}
});
}
// use bounding boxes
for (var i = 0; i < anchorAxis._vals.length; i++) {
var t = anchorAxis._vals[i];
var bb = t.bb;
if (bb) {
var w = 2 * TEXTPAD + bb.width;
var h = 2 * TEXTPAD + bb.height;
pad = Math.max(pad, isX ? Math.max(w * cosA, h * sinA) : Math.max(h * cosA, w * sinA));
}
}
}
if (anchorAxis.ticks === 'inside' && anchorAxis.ticklabelposition === 'inside') {
pad += anchorAxis.ticklen || 0;
}
}
}
}
return pad;
}
function concatExtremes(gd, ax, noMatch) {
var axId = ax._id;
var fullData = gd._fullData;
var fullLayout = gd._fullLayout;
var minArray = [];
var maxArray = [];
var i, j, d;
function _concat(cont, indices) {
for (i = 0; i < indices.length; i++) {
var item = cont[indices[i]];
var extremes = (item._extremes || {})[axId];
if (item.visible === true && extremes) {
for (j = 0; j < extremes.min.length; j++) {
d = extremes.min[j];
collapseMinArray(minArray, d.val, d.pad, {
extrapad: d.extrapad
});
}
for (j = 0; j < extremes.max.length; j++) {
d = extremes.max[j];
collapseMaxArray(maxArray, d.val, d.pad, {
extrapad: d.extrapad
});
}
}
}
}
_concat(fullData, ax._traceIndices);
_concat(fullLayout.annotations || [], ax._annIndices || []);
_concat(fullLayout.shapes || [], ax._shapeIndices || []);
// Include the extremes from other matched axes with this one
if (ax._matchGroup && !noMatch) {
for (var axId2 in ax._matchGroup) {
if (axId2 !== ax._id) {
var ax2 = getFromId(gd, axId2);
var extremes2 = concatExtremes(gd, ax2, true);
// convert padding on the second axis to the first with lenRatio
var lenRatio = ax._length / ax2._length;
for (j = 0; j < extremes2.min.length; j++) {
d = extremes2.min[j];
collapseMinArray(minArray, d.val, d.pad * lenRatio, {
extrapad: d.extrapad
});
}
for (j = 0; j < extremes2.max.length; j++) {
d = extremes2.max[j];
collapseMaxArray(maxArray, d.val, d.pad * lenRatio, {
extrapad: d.extrapad
});
}
}
}
}
return {
min: minArray,
max: maxArray
};
}
function doAutoRange(gd, ax, presetRange) {
ax.setScale();
if (ax.autorange) {
ax.range = presetRange ? presetRange.slice() : getAutoRange(gd, ax);
ax._r = ax.range.slice();
ax._rl = Lib.simpleMap(ax._r, ax.r2l);
// doAutoRange will get called on fullLayout,
// but we want to report its results back to layout
var axIn = ax._input;
// before we edit _input, store preGUI values
var edits = {};
edits[ax._attr + '.range'] = ax.range;
edits[ax._attr + '.autorange'] = ax.autorange;
Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, edits);
axIn.range = ax.range.slice();
axIn.autorange = ax.autorange;
}
var anchorAx = ax._anchorAxis;
if (anchorAx && anchorAx.rangeslider) {
var axeRangeOpts = anchorAx.rangeslider[ax._name];
if (axeRangeOpts) {
if (axeRangeOpts.rangemode === 'auto') {
axeRangeOpts.range = getAutoRange(gd, ax);
}
}
anchorAx._input.rangeslider[ax._name] = Lib.extendFlat({}, axeRangeOpts);
}
}
/**
* findExtremes
*
* Find min/max extremes of an array of coordinates on a given axis.
*
* Note that findExtremes is called during `calc`, when we don't yet know the axis
* length; all the inputs should be based solely on the trace data, nothing
* about the axis layout.
*
* Note that `ppad` and `vpad` as well as their asymmetric variants refer to
* the before and after padding of the passed `data` array, not to the whole axis.
*
* @param {object} ax: full axis object
* relies on
* - ax.type
* - ax._m (just its sign)
* - ax.d2l
* @param {array} data:
* array of numbers (i.e. already run though ax.d2c)
* @param {object} opts:
* available keys are:
* vpad: (number or number array) pad values (data value +-vpad)
* ppad: (number or number array) pad pixels (pixel location +-ppad)
* ppadplus, ppadminus, vpadplus, vpadminus:
* separate padding for each side, overrides symmetric
* padded: (boolean) add 5% padding to both ends
* (unless one end is overridden by tozero)
* tozero: (boolean) make sure to include zero if axis is linear,
* and make it a tight bound if possible
* vpadLinearized: (boolean) whether or not vpad (or vpadplus/vpadminus)
* is linearized (for log scale axes)
*
* @return {object}
* - min {array of objects}
* - max {array of objects}
* each object item has fields:
* - val {number}
* - pad {number}
* - extrappad {number}
* - opts {object}: a ref to the passed "options" object
*/
function findExtremes(ax, data, opts) {
if (!opts) opts = {};
if (!ax._m) ax.setScale();
var minArray = [];
var maxArray = [];
var len = data.length;
var extrapad = opts.padded || false;
var tozero = opts.tozero && (ax.type === 'linear' || ax.type === '-');
var isLog = ax.type === 'log';
var hasArrayOption = false;
var vpadLinearized = opts.vpadLinearized || false;
var i, v, di, dmin, dmax, ppadiplus, ppadiminus, vmin, vmax;
function makePadAccessor(item) {
if (Array.isArray(item)) {
hasArrayOption = true;
return function (i) {
return Math.max(Number(item[i] || 0), 0);
};
} else {
var v = Math.max(Number(item || 0), 0);
return function () {
return v;
};
}
}
var ppadplus = makePadAccessor((ax._m > 0 ? opts.ppadplus : opts.ppadminus) || opts.ppad || 0);
var ppadminus = makePadAccessor((ax._m > 0 ? opts.ppadminus : opts.ppadplus) || opts.ppad || 0);
var vpadplus = makePadAccessor(opts.vpadplus || opts.vpad);
var vpadminus = makePadAccessor(opts.vpadminus || opts.vpad);
if (!hasArrayOption) {
// with no arrays other than `data` we don't need to consider
// every point, only the extreme data points
vmin = Infinity;
vmax = -Infinity;
if (isLog) {
for (i = 0; i < len; i++) {
v = data[i];
// data is not linearized yet so we still have to filter out negative logs
if (v < vmin && v > 0) vmin = v;
if (v > vmax && v < FP_SAFE) vmax = v;
}
} else {
for (i = 0; i < len; i++) {
v = data[i];
if (v < vmin && v > -FP_SAFE) vmin = v;
if (v > vmax && v < FP_SAFE) vmax = v;
}
}
data = [vmin, vmax];
len = 2;
}
var collapseOpts = {
tozero: tozero,
extrapad: extrapad
};
function addItem(i) {
di = data[i];
if (!isNumeric(di)) return;
ppadiplus = ppadplus(i);
ppadiminus = ppadminus(i);
if (vpadLinearized) {
dmin = ax.c2l(di) - vpadminus(i);
dmax = ax.c2l(di) + vpadplus(i);
} else {
vmin = di - vpadminus(i);
vmax = di + vpadplus(i);
// special case for log axes: if vpad makes this object span
// more than an order of mag, clip it to one order. This is so
// we don't have non-positive errors or absurdly large lower
// range due to rounding errors
if (isLog && vmin < vmax / 10) vmin = vmax / 10;
dmin = ax.c2l(vmin);
dmax = ax.c2l(vmax);
}
if (tozero) {
dmin = Math.min(0, dmin);
dmax = Math.max(0, dmax);
}
if (goodNumber(dmin)) {
collapseMinArray(minArray, dmin, ppadiminus, collapseOpts);
}
if (goodNumber(dmax)) {
collapseMaxArray(maxArray, dmax, ppadiplus, collapseOpts);
}
}
// For efficiency covering monotonic or near-monotonic data,
// check a few points at both ends first and then sweep
// through the middle
var iMax = Math.min(6, len);
for (i = 0; i < iMax; i++) addItem(i);
for (i = len - 1; i >= iMax; i--) addItem(i);
return {
min: minArray,
max: maxArray,
opts: opts
};
}
function collapseMinArray(array, newVal, newPad, opts) {
collapseArray(array, newVal, newPad, opts, lessOrEqual);
}
function collapseMaxArray(array, newVal, newPad, opts) {
collapseArray(array, newVal, newPad, opts, greaterOrEqual);
}
/**
* collapseArray
*
* Takes items from 'array' and compares them to 'newVal', 'newPad'.
*
* @param {array} array:
* current set of min or max extremes
* @param {number} newVal:
* new value to compare against
* @param {number} newPad:
* pad value associated with 'newVal'
* @param {object} opts:
* - tozero {boolean}
* - extrapad {number}
* @param {function} atLeastAsExtreme:
* comparison function, use
* - lessOrEqual for min 'array' and
* - greaterOrEqual for max 'array'
*
* In practice, 'array' is either
* - 'extremes[ax._id].min' or
* - 'extremes[ax._id].max
* found in traces and layout items that affect autorange.
*
* Since we don't yet know the relationship between pixels and values
* (that's what we're trying to figure out!) AND we don't yet know how
* many pixels `extrapad` represents (it's going to be 5% of the length,
* but we don't want to have to redo calc just because length changed)
* two point must satisfy three criteria simultaneously for one to supersede the other:
* - at least as extreme a `val`
* - at least as big a `pad`
* - an unpadded point cannot supersede a padded point, but any other combination can
*
* Then:
* - If the item supersedes the new point, set includeThis false
* - If the new pt supersedes the item, delete it from 'array'
*/
function collapseArray(array, newVal, newPad, opts, atLeastAsExtreme) {
var tozero = opts.tozero;
var extrapad = opts.extrapad;
var includeThis = true;
for (var j = 0; j < array.length && includeThis; j++) {
var v = array[j];
if (atLeastAsExtreme(v.val, newVal) && v.pad >= newPad && (v.extrapad || !extrapad)) {
includeThis = false;
break;
} else if (atLeastAsExtreme(newVal, v.val) && v.pad <= newPad && (extrapad || !v.extrapad)) {
array.splice(j, 1);
j--;
}
}
if (includeThis) {
var clipAtZero = tozero && newVal === 0;
array.push({
val: newVal,
pad: clipAtZero ? 0 : newPad,
extrapad: clipAtZero ? false : extrapad
});
}
}
// In order to stop overflow errors, don't consider points
// too close to the limits of js floating point
function goodNumber(v) {
return isNumeric(v) && Math.abs(v) < FP_SAFE;
}
function lessOrEqual(v0, v1) {
return v0 <= v1;
}
function greaterOrEqual(v0, v1) {
return v0 >= v1;
}
function applyAutorangeMinOptions(v, ax) {
var autorangeoptions = ax.autorangeoptions;
if (autorangeoptions && autorangeoptions.minallowed !== undefined && hasValidMinAndMax(ax, autorangeoptions.minallowed, autorangeoptions.maxallowed)) {
return autorangeoptions.minallowed;
}
if (autorangeoptions && autorangeoptions.clipmin !== undefined && hasValidMinAndMax(ax, autorangeoptions.clipmin, autorangeoptions.clipmax)) {
return Math.max(v, ax.d2l(autorangeoptions.clipmin));
}
return v;
}
function applyAutorangeMaxOptions(v, ax) {
var autorangeoptions = ax.autorangeoptions;
if (autorangeoptions && autorangeoptions.maxallowed !== undefined && hasValidMinAndMax(ax, autorangeoptions.minallowed, autorangeoptions.maxallowed)) {
return autorangeoptions.maxallowed;
}
if (autorangeoptions && autorangeoptions.clipmax !== undefined && hasValidMinAndMax(ax, autorangeoptions.clipmin, autorangeoptions.clipmax)) {
return Math.min(v, ax.d2l(autorangeoptions.clipmax));
}
return v;
}
function hasValidMinAndMax(ax, min, max) {
// in case both min and max are defined, ensure min < max
if (min !== undefined && max !== undefined) {
min = ax.d2l(min);
max = ax.d2l(max);
return min < max;
}
return true;
}
// this function should be (and is) called before reversing the range
// so range[0] is the minimum and range[1] is the maximum
function applyAutorangeOptions(range, ax) {
if (!ax || !ax.autorangeoptions) return range;
var min = range[0];
var max = range[1];
var include = ax.autorangeoptions.include;
if (include !== undefined) {
var lMin = ax.d2l(min);
var lMax = ax.d2l(max);
if (!Lib.isArrayOrTypedArray(include)) include = [include];
for (var i = 0; i < include.length; i++) {
var v = ax.d2l(include[i]);
if (lMin >= v) {
lMin = v;
min = v;
}
if (lMax <= v) {
lMax = v;
max = v;
}
}
}
min = applyAutorangeMinOptions(min, ax);
max = applyAutorangeMaxOptions(max, ax);
return [min, max];
}
/***/ }),
/***/ 76808:
/***/ (function(module) {
"use strict";
module.exports = function handleAutorangeOptionsDefaults(coerce, autorange, range) {
var minRange, maxRange;
if (range) {
var isReversed = autorange === 'reversed' || autorange === 'min reversed' || autorange === 'max reversed';
minRange = range[isReversed ? 1 : 0];
maxRange = range[isReversed ? 0 : 1];
}
var minallowed = coerce('autorangeoptions.minallowed', maxRange === null ? minRange : undefined);
var maxallowed = coerce('autorangeoptions.maxallowed', minRange === null ? maxRange : undefined);
if (minallowed === undefined) coerce('autorangeoptions.clipmin');
if (maxallowed === undefined) coerce('autorangeoptions.clipmax');
coerce('autorangeoptions.include');
};
/***/ }),
/***/ 54460:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var isNumeric = __webpack_require__(38248);
var Plots = __webpack_require__(7316);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var svgTextUtils = __webpack_require__(72736);
var Titles = __webpack_require__(81668);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var axAttrs = __webpack_require__(94724);
var cleanTicks = __webpack_require__(98728);
var constants = __webpack_require__(39032);
var ONEMAXYEAR = constants.ONEMAXYEAR;
var ONEAVGYEAR = constants.ONEAVGYEAR;
var ONEMINYEAR = constants.ONEMINYEAR;
var ONEMAXQUARTER = constants.ONEMAXQUARTER;
var ONEAVGQUARTER = constants.ONEAVGQUARTER;
var ONEMINQUARTER = constants.ONEMINQUARTER;
var ONEMAXMONTH = constants.ONEMAXMONTH;
var ONEAVGMONTH = constants.ONEAVGMONTH;
var ONEMINMONTH = constants.ONEMINMONTH;
var ONEWEEK = constants.ONEWEEK;
var ONEDAY = constants.ONEDAY;
var HALFDAY = ONEDAY / 2;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var ONEMILLI = constants.ONEMILLI;
var ONEMICROSEC = constants.ONEMICROSEC;
var MINUS_SIGN = constants.MINUS_SIGN;
var BADNUM = constants.BADNUM;
var ZERO_PATH = {
K: 'zeroline'
};
var GRID_PATH = {
K: 'gridline',
L: 'path'
};
var MINORGRID_PATH = {
K: 'minor-gridline',
L: 'path'
};
var TICK_PATH = {
K: 'tick',
L: 'path'
};
var TICK_TEXT = {
K: 'tick',
L: 'text'
};
var MARGIN_MAPPING = {
width: ['x', 'r', 'l', 'xl', 'xr'],
height: ['y', 't', 'b', 'yt', 'yb'],
right: ['r', 'xr'],
left: ['l', 'xl'],
top: ['t', 'yt'],
bottom: ['b', 'yb']
};
var alignmentConstants = __webpack_require__(84284);
var MID_SHIFT = alignmentConstants.MID_SHIFT;
var CAP_SHIFT = alignmentConstants.CAP_SHIFT;
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var OPPOSITE_SIDE = alignmentConstants.OPPOSITE_SIDE;
var TEXTPAD = 3;
var axes = module.exports = {};
axes.setConvert = __webpack_require__(78344);
var autoType = __webpack_require__(52976);
var axisIds = __webpack_require__(79811);
var idSort = axisIds.idSort;
var isLinked = axisIds.isLinked;
// tight coupling to chart studio
axes.id2name = axisIds.id2name;
axes.name2id = axisIds.name2id;
axes.cleanId = axisIds.cleanId;
axes.list = axisIds.list;
axes.listIds = axisIds.listIds;
axes.getFromId = axisIds.getFromId;
axes.getFromTrace = axisIds.getFromTrace;
var autorange = __webpack_require__(19280);
axes.getAutoRange = autorange.getAutoRange;
axes.findExtremes = autorange.findExtremes;
var epsilon = 0.0001;
function expandRange(range) {
var delta = (range[1] - range[0]) * epsilon;
return [range[0] - delta, range[1] + delta];
}
/*
* find the list of possible axes to reference with an xref or yref attribute
* and coerce it to that list
*
* attr: the attribute we're generating a reference for. Should end in 'x' or 'y'
* but can be prefixed, like 'ax' for annotation's arrow x
* dflt: the default to coerce to, or blank to use the first axis (falling back on
* extraOption if there is no axis)
* extraOption: aside from existing axes with this letter, what non-axis value is allowed?
* Only required if it's different from `dflt`
*/
axes.coerceRef = function (containerIn, containerOut, gd, attr, dflt, extraOption) {
var axLetter = attr.charAt(attr.length - 1);
var axlist = gd._fullLayout._subplots[axLetter + 'axis'];
var refAttr = attr + 'ref';
var attrDef = {};
if (!dflt) dflt = axlist[0] || (typeof extraOption === 'string' ? extraOption : extraOption[0]);
if (!extraOption) extraOption = dflt;
axlist = axlist.concat(axlist.map(function (x) {
return x + ' domain';
}));
// data-ref annotations are not supported in gl2d yet
attrDef[refAttr] = {
valType: 'enumerated',
values: axlist.concat(extraOption ? typeof extraOption === 'string' ? [extraOption] : extraOption : []),
dflt: dflt
};
// xref, yref
return Lib.coerce(containerIn, containerOut, attrDef, refAttr);
};
/*
* Get the type of an axis reference. This can be 'range', 'domain', or 'paper'.
* This assumes ar is a valid axis reference and returns 'range' if it doesn't
* match the patterns for 'paper' or 'domain'.
*
* ar: the axis reference string
*
*/
axes.getRefType = function (ar) {
if (ar === undefined) {
return ar;
}
if (ar === 'paper') {
return 'paper';
}
if (ar === 'pixel') {
return 'pixel';
}
if (/( domain)$/.test(ar)) {
return 'domain';
} else {
return 'range';
}
};
/*
* coerce position attributes (range-type) that can be either on axes or absolute
* (paper or pixel) referenced. The biggest complication here is that we don't know
* before looking at the axis whether the value must be a number or not (it may be
* a date string), so we can't use the regular valType='number' machinery
*
* axRef (string): the axis this position is referenced to, or:
* paper: fraction of the plot area
* pixel: pixels relative to some starting position
* attr (string): the attribute in containerOut we are coercing
* dflt (number): the default position, as a fraction or pixels. If the attribute
* is to be axis-referenced, this will be converted to an axis data value
*
* Also cleans the values, since the attribute definition itself has to say
* valType: 'any' to handle date axes. This allows us to accept:
* - for category axes: category names, and convert them here into serial numbers.
* Note that this will NOT work for axis range endpoints, because we don't know
* the category list yet (it's set by ax.makeCalcdata during calc)
* but it works for component (note, shape, images) positions.
* - for date axes: JS Dates or milliseconds, and convert to date strings
* - for other types: coerce them to numbers
*/
axes.coercePosition = function (containerOut, gd, coerce, axRef, attr, dflt) {
var cleanPos, pos;
var axRefType = axes.getRefType(axRef);
if (axRefType !== 'range') {
cleanPos = Lib.ensureNumber;
pos = coerce(attr, dflt);
} else {
var ax = axes.getFromId(gd, axRef);
dflt = ax.fraction2r(dflt);
pos = coerce(attr, dflt);
cleanPos = ax.cleanPos;
}
containerOut[attr] = cleanPos(pos);
};
axes.cleanPosition = function (pos, gd, axRef) {
var cleanPos = axRef === 'paper' || axRef === 'pixel' ? Lib.ensureNumber : axes.getFromId(gd, axRef).cleanPos;
return cleanPos(pos);
};
axes.redrawComponents = function (gd, axIds) {
axIds = axIds ? axIds : axes.listIds(gd);
var fullLayout = gd._fullLayout;
function _redrawOneComp(moduleName, methodName, stashName, shortCircuit) {
var method = Registry.getComponentMethod(moduleName, methodName);
var stash = {};
for (var i = 0; i < axIds.length; i++) {
var ax = fullLayout[axes.id2name(axIds[i])];
var indices = ax[stashName];
for (var j = 0; j < indices.length; j++) {
var ind = indices[j];
if (!stash[ind]) {
method(gd, ind);
stash[ind] = 1;
// once is enough for images (which doesn't use the `i` arg anyway)
if (shortCircuit) return;
}
}
}
}
// annotations and shapes 'draw' method is slow,
// use the finer-grained 'drawOne' method instead
_redrawOneComp('annotations', 'drawOne', '_annIndices');
_redrawOneComp('shapes', 'drawOne', '_shapeIndices');
_redrawOneComp('images', 'draw', '_imgIndices', true);
_redrawOneComp('selections', 'drawOne', '_selectionIndices');
};
var getDataConversions = axes.getDataConversions = function (gd, trace, target, targetArray) {
var ax;
// If target points to an axis, use the type we already have for that
// axis to find the data type. Otherwise use the values to autotype.
var d2cTarget = target === 'x' || target === 'y' || target === 'z' ? target : targetArray;
// In the case of an array target, make a mock data array
// and call supplyDefaults to the data type and
// setup the data-to-calc method.
if (Lib.isArrayOrTypedArray(d2cTarget)) {
ax = {
type: autoType(targetArray, undefined, {
autotypenumbers: gd._fullLayout.autotypenumbers
}),
_categories: []
};
axes.setConvert(ax);
// build up ax._categories (usually done during ax.makeCalcdata()
if (ax.type === 'category') {
for (var i = 0; i < targetArray.length; i++) {
ax.d2c(targetArray[i]);
}
}
// TODO what to do for transforms?
} else {
ax = axes.getFromTrace(gd, trace, d2cTarget);
}
// if 'target' has corresponding axis
// -> use setConvert method
if (ax) return {
d2c: ax.d2c,
c2d: ax.c2d
};
// special case for 'ids'
// -> cast to String
if (d2cTarget === 'ids') return {
d2c: toString,
c2d: toString
};
// otherwise (e.g. numeric-array of 'marker.color' or 'marker.size')
// -> cast to Number
return {
d2c: toNum,
c2d: toNum
};
};
function toNum(v) {
return +v;
}
function toString(v) {
return String(v);
}
axes.getDataToCoordFunc = function (gd, trace, target, targetArray) {
return getDataConversions(gd, trace, target, targetArray).d2c;
};
// get counteraxis letter for this axis (name or id)
// this can also be used as the id for default counter axis
axes.counterLetter = function (id) {
var axLetter = id.charAt(0);
if (axLetter === 'x') return 'y';
if (axLetter === 'y') return 'x';
};
// incorporate a new minimum difference and first tick into
// forced
// note that _forceTick0 is linearized, so needs to be turned into
// a range value for setting tick0
axes.minDtick = function (ax, newDiff, newFirst, allow) {
// doesn't make sense to do forced min dTick on log or category axes,
// and the plot itself may decide to cancel (ie non-grouped bars)
if (['log', 'category', 'multicategory'].indexOf(ax.type) !== -1 || !allow) {
ax._minDtick = 0;
} else if (ax._minDtick === undefined) {
// undefined means there's nothing there yet
ax._minDtick = newDiff;
ax._forceTick0 = newFirst;
} else if (ax._minDtick) {
if ((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 &&
// existing minDtick is an integer multiple of newDiff
// (within rounding err)
// and forceTick0 can be shifted to newFirst
((newFirst - ax._forceTick0) / newDiff % 1 + 1.000001) % 1 < 2e-6) {
ax._minDtick = newDiff;
ax._forceTick0 = newFirst;
} else if ((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 ||
// if the converse is true (newDiff is a multiple of minDtick and
// newFirst can be shifted to forceTick0) then do nothing - same
// forcing stands. Otherwise, cancel forced minimum
((newFirst - ax._forceTick0) / ax._minDtick % 1 + 1.000001) % 1 > 2e-6) {
ax._minDtick = 0;
}
}
};
// save a copy of the initial axis ranges in fullLayout
// use them in mode bar and dblclick events
axes.saveRangeInitial = function (gd, overwrite) {
var axList = axes.list(gd, '', true);
var hasOneAxisChanged = false;
for (var i = 0; i < axList.length; i++) {
var ax = axList[i];
var isNew = ax._rangeInitial0 === undefined && ax._rangeInitial1 === undefined;
var hasChanged = isNew || ax.range[0] !== ax._rangeInitial0 || ax.range[1] !== ax._rangeInitial1;
var autorange = ax.autorange;
if (isNew && autorange !== true || overwrite && hasChanged) {
ax._rangeInitial0 = autorange === 'min' || autorange === 'max reversed' ? undefined : ax.range[0];
ax._rangeInitial1 = autorange === 'max' || autorange === 'min reversed' ? undefined : ax.range[1];
ax._autorangeInitial = autorange;
hasOneAxisChanged = true;
}
}
return hasOneAxisChanged;
};
// save a copy of the initial spike visibility
axes.saveShowSpikeInitial = function (gd, overwrite) {
var axList = axes.list(gd, '', true);
var hasOneAxisChanged = false;
var allSpikesEnabled = 'on';
for (var i = 0; i < axList.length; i++) {
var ax = axList[i];
var isNew = ax._showSpikeInitial === undefined;
var hasChanged = isNew || !(ax.showspikes === ax._showspikes);
if (isNew || overwrite && hasChanged) {
ax._showSpikeInitial = ax.showspikes;
hasOneAxisChanged = true;
}
if (allSpikesEnabled === 'on' && !ax.showspikes) {
allSpikesEnabled = 'off';
}
}
gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
return hasOneAxisChanged;
};
axes.autoBin = function (data, ax, nbins, is2d, calendar, size) {
var dataMin = Lib.aggNums(Math.min, null, data);
var dataMax = Lib.aggNums(Math.max, null, data);
if (ax.type === 'category' || ax.type === 'multicategory') {
return {
start: dataMin - 0.5,
end: dataMax + 0.5,
size: Math.max(1, Math.round(size) || 1),
_dataSpan: dataMax - dataMin
};
}
if (!calendar) calendar = ax.calendar;
// piggyback off tick code to make "nice" bin sizes and edges
var dummyAx;
if (ax.type === 'log') {
dummyAx = {
type: 'linear',
range: [dataMin, dataMax]
};
} else {
dummyAx = {
type: ax.type,
range: Lib.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar),
calendar: calendar
};
}
axes.setConvert(dummyAx);
size = size && cleanTicks.dtick(size, dummyAx.type);
if (size) {
dummyAx.dtick = size;
dummyAx.tick0 = cleanTicks.tick0(undefined, dummyAx.type, calendar);
} else {
var size0;
if (nbins) size0 = (dataMax - dataMin) / nbins;else {
// totally auto: scale off std deviation so the highest bin is
// somewhat taller than the total number of bins, but don't let
// the size get smaller than the 'nice' rounded down minimum
// difference between values
var distinctData = Lib.distinctVals(data);
var msexp = Math.pow(10, Math.floor(Math.log(distinctData.minDiff) / Math.LN10));
var minSize = msexp * Lib.roundUp(distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true);
size0 = Math.max(minSize, 2 * Lib.stdev(data) / Math.pow(data.length, is2d ? 0.25 : 0.4));
// fallback if ax.d2c output BADNUMs
// e.g. when user try to plot categorical bins
// on a layout.xaxis.type: 'linear'
if (!isNumeric(size0)) size0 = 1;
}
axes.autoTicks(dummyAx, size0);
}
var finalSize = dummyAx.dtick;
var binStart = axes.tickIncrement(axes.tickFirst(dummyAx), finalSize, 'reverse', calendar);
var binEnd, bincount;
// check for too many data points right at the edges of bins
// (>50% within 1% of bin edges) or all data points integral
// and offset the bins accordingly
if (typeof finalSize === 'number') {
binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax);
bincount = 1 + Math.floor((dataMax - binStart) / finalSize);
binEnd = binStart + bincount * finalSize;
} else {
// month ticks - should be the only nonlinear kind we have at this point.
// dtick (as supplied by axes.autoTick) only has nonlinear values on
// date and log axes, but even if you display a histogram on a log axis
// we bin it on a linear axis (which one could argue against, but that's
// a separate issue)
if (dummyAx.dtick.charAt(0) === 'M') {
binStart = autoShiftMonthBins(binStart, data, finalSize, dataMin, calendar);
}
// calculate the endpoint for nonlinear ticks - you have to
// just increment until you're done
binEnd = binStart;
bincount = 0;
while (binEnd <= dataMax) {
binEnd = axes.tickIncrement(binEnd, finalSize, false, calendar);
bincount++;
}
}
return {
start: ax.c2r(binStart, 0, calendar),
end: ax.c2r(binEnd, 0, calendar),
size: finalSize,
_dataSpan: dataMax - dataMin
};
};
function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) {
var edgecount = 0;
var midcount = 0;
var intcount = 0;
var blankCount = 0;
function nearEdge(v) {
// is a value within 1% of a bin edge?
return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2;
}
for (var i = 0; i < data.length; i++) {
if (data[i] % 1 === 0) intcount++;else if (!isNumeric(data[i])) blankCount++;
if (nearEdge(data[i])) edgecount++;
if (nearEdge(data[i] + ax.dtick / 2)) midcount++;
}
var dataCount = data.length - blankCount;
if (intcount === dataCount && ax.type !== 'date') {
if (ax.dtick < 1) {
// all integers: if bin size is <1, it's because
// that was specifically requested (large nbins)
// so respect that... but center the bins containing
// integers on those integers
binStart = dataMin - 0.5 * ax.dtick;
} else {
// otherwise start half an integer down regardless of
// the bin size, just enough to clear up endpoint
// ambiguity about which integers are in which bins.
binStart -= 0.5;
if (binStart + ax.dtick < dataMin) binStart += ax.dtick;
}
} else if (midcount < dataCount * 0.1) {
if (edgecount > dataCount * 0.3 || nearEdge(dataMin) || nearEdge(dataMax)) {
// lots of points at the edge, not many in the middle
// shift half a bin
var binshift = ax.dtick / 2;
binStart += binStart + binshift < dataMin ? binshift : -binshift;
}
}
return binStart;
}
function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) {
var stats = Lib.findExactDates(data, calendar);
// number of data points that needs to be an exact value
// to shift that increment to (near) the bin center
var threshold = 0.8;
if (stats.exactDays > threshold) {
var numMonths = Number(dtick.substr(1));
if (stats.exactYears > threshold && numMonths % 12 === 0) {
// The exact middle of a non-leap-year is 1.5 days into July
// so if we start the bins here, all but leap years will
// get hover-labeled as exact years.
binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + ONEDAY * 1.5;
} else if (stats.exactMonths > threshold) {
// Months are not as clean, but if we shift half the *longest*
// month (31/2 days) then 31-day months will get labeled exactly
// and shorter months will get labeled with the correct month
// but shifted 12-36 hours into it.
binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + ONEDAY * 15.5;
} else {
// Shifting half a day is exact, but since these are month bins it
// will always give a somewhat odd-looking label, until we do something
// smarter like showing the bin boundaries (or the bounds of the actual
// data in each bin)
binStart -= HALFDAY;
}
var nextBinStart = axes.tickIncrement(binStart, dtick);
if (nextBinStart <= dataMin) return nextBinStart;
}
return binStart;
}
// ----------------------------------------------------
// Ticks and grids
// ----------------------------------------------------
// ensure we have minor tick0 and dtick calculated
axes.prepMinorTicks = function (mockAx, ax, opts) {
if (!ax.minor.dtick) {
delete mockAx.dtick;
var hasMajor = ax.dtick && isNumeric(ax._tmin);
var mockMinorRange;
if (hasMajor) {
var tick2 = axes.tickIncrement(ax._tmin, ax.dtick, true);
// mock range a tiny bit smaller than one major tick interval
mockMinorRange = [ax._tmin, tick2 * 0.99 + ax._tmin * 0.01];
} else {
var rl = Lib.simpleMap(ax.range, ax.r2l);
// If we don't have a major dtick, the concept of minor ticks is a little
// ambiguous - just take a stab and say minor.nticks should span 1/5 the axis
mockMinorRange = [rl[0], 0.8 * rl[0] + 0.2 * rl[1]];
}
mockAx.range = Lib.simpleMap(mockMinorRange, ax.l2r);
mockAx._isMinor = true;
axes.prepTicks(mockAx, opts);
if (hasMajor) {
var numericMajor = isNumeric(ax.dtick);
var numericMinor = isNumeric(mockAx.dtick);
var majorNum = numericMajor ? ax.dtick : +ax.dtick.substring(1);
var minorNum = numericMinor ? mockAx.dtick : +mockAx.dtick.substring(1);
if (numericMajor && numericMinor) {
if (!isMultiple(majorNum, minorNum)) {
// give up on minor ticks - outside the below exceptions,
// this can only happen if minor.nticks is smaller than two jumps
// in the auto-tick scale and the first jump is not an even multiple
// (5 -> 2 or for dates 3 ->2, 15 -> 10 etc) or if you provided
// an explicit dtick, in which case it's fine to give up,
// you can provide an explicit minor.dtick.
if (majorNum === 2 * ONEWEEK && minorNum === 3 * ONEDAY) {
mockAx.dtick = ONEWEEK;
} else if (majorNum === ONEWEEK && !(ax._input.minor || {}).nticks) {
// minor.nticks defaults to 5, but in this one case we want 7,
// so the minor ticks show on all days of the week
mockAx.dtick = ONEDAY;
} else if (isClose(majorNum / minorNum, 2.5)) {
// 5*10^n -> 2*10^n and you've set nticks < 5
// quarters are pretty common, we don't do this by default as it
// would add an extra digit to display, but minor has no labels
mockAx.dtick = majorNum / 2;
} else {
mockAx.dtick = majorNum;
}
} else if (majorNum === 2 * ONEWEEK && minorNum === 2 * ONEDAY) {
// this is a weird one: we don't want to automatically choose
// 2-day minor ticks for 2-week major, even though it IS an even multiple,
// because people would expect to see the weeks clearly
mockAx.dtick = ONEWEEK;
}
} else if (String(ax.dtick).charAt(0) === 'M') {
if (numericMinor) {
mockAx.dtick = 'M1';
} else {
if (!isMultiple(majorNum, minorNum)) {
// unless you provided an explicit ax.dtick (in which case
// it's OK for us to give up, you can provide an explicit
// minor.dtick too), this can only happen with:
// minor.nticks < 3 and dtick === M3, or
// minor.nticks < 5 and dtick === 5 * 10^n years
// so in all cases we just give up.
mockAx.dtick = ax.dtick;
} else if (majorNum >= 12 && minorNum === 2) {
// another special carve-out: for year major ticks, don't show
// 2-month minor ticks, bump to quarters
mockAx.dtick = 'M3';
}
}
} else if (String(mockAx.dtick).charAt(0) === 'L') {
if (String(ax.dtick).charAt(0) === 'L') {
if (!isMultiple(majorNum, minorNum)) {
mockAx.dtick = isClose(majorNum / minorNum, 2.5) ? ax.dtick / 2 : ax.dtick;
}
} else {
mockAx.dtick = 'D1';
}
} else if (mockAx.dtick === 'D2' && +ax.dtick > 1) {
// the D2 log axis tick spacing is confusing for unlabeled minor ticks if
// the major dtick is more than one order of magnitude.
mockAx.dtick = 1;
}
}
// put back the original range, to use to find the full set of minor ticks
mockAx.range = ax.range;
}
if (ax.minor._tick0Init === undefined) {
// ensure identical tick0
mockAx.tick0 = ax.tick0;
}
};
function isMultiple(bigger, smaller) {
return Math.abs((bigger / smaller + 0.5) % 1 - 0.5) < 0.001;
}
function isClose(a, b) {
return Math.abs(a / b - 1) < 0.001;
}
// ensure we have tick0, dtick, and tick rounding calculated
axes.prepTicks = function (ax, opts) {
var rng = Lib.simpleMap(ax.range, ax.r2l, undefined, undefined, opts);
// calculate max number of (auto) ticks to display based on plot size
if (ax.tickmode === 'auto' || !ax.dtick) {
var nt = ax.nticks;
var minPx;
if (!nt) {
if (ax.type === 'category' || ax.type === 'multicategory') {
minPx = ax.tickfont ? Lib.bigFont(ax.tickfont.size || 12) : 15;
nt = ax._length / minPx;
} else {
minPx = ax._id.charAt(0) === 'y' ? 40 : 80;
nt = Lib.constrain(ax._length / minPx, 4, 9) + 1;
}
// radial axes span half their domain,
// multiply nticks value by two to get correct number of auto ticks.
if (ax._name === 'radialaxis') nt *= 2;
}
if (!(ax.minor && ax.minor.tickmode !== 'array')) {
// add a couple of extra digits for filling in ticks when we
// have explicit tickvals without tick text
if (ax.tickmode === 'array') nt *= 100;
}
ax._roughDTick = Math.abs(rng[1] - rng[0]) / nt;
axes.autoTicks(ax, ax._roughDTick);
// check for a forced minimum dtick
if (ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) {
ax.dtick = ax._minDtick;
ax.tick0 = ax.l2r(ax._forceTick0);
}
}
if (ax.ticklabelmode === 'period') {
adjustPeriodDelta(ax);
}
// check for missing tick0
if (!ax.tick0) {
ax.tick0 = ax.type === 'date' ? '2000-01-01' : 0;
}
// ensure we don't try to make ticks below our minimum precision
// see https://github.com/plotly/plotly.js/issues/2892
if (ax.type === 'date' && ax.dtick < 0.1) ax.dtick = 0.1;
// now figure out rounding of tick values
autoTickRound(ax);
};
function nMonths(dtick) {
return +dtick.substring(1);
}
function adjustPeriodDelta(ax) {
// adjusts ax.dtick and sets ax._definedDelta
var definedDelta;
function mDate() {
return !(isNumeric(ax.dtick) || ax.dtick.charAt(0) !== 'M');
}
var isMDate = mDate();
var tickformat = axes.getTickFormat(ax);
if (tickformat) {
var noDtick = ax._dtickInit !== ax.dtick;
if (!/%[fLQsSMX]/.test(tickformat)
// %f: microseconds as a decimal number [000000, 999999]
// %L: milliseconds as a decimal number [000, 999]
// %Q: milliseconds since UNIX epoch
// %s: seconds since UNIX epoch
// %S: second as a decimal number [00,61]
// %M: minute as a decimal number [00,59]
// %X: the locale’s time, such as %-I:%M:%S %p
) {
if (/%[HI]/.test(tickformat)
// %H: hour (24-hour clock) as a decimal number [00,23]
// %I: hour (12-hour clock) as a decimal number [01,12]
) {
definedDelta = ONEHOUR;
if (noDtick && !isMDate && ax.dtick < ONEHOUR) ax.dtick = ONEHOUR;
} else if (/%p/.test(tickformat) // %p: either AM or PM
) {
definedDelta = HALFDAY;
if (noDtick && !isMDate && ax.dtick < HALFDAY) ax.dtick = HALFDAY;
} else if (/%[Aadejuwx]/.test(tickformat)
// %A: full weekday name
// %a: abbreviated weekday name
// %d: zero-padded day of the month as a decimal number [01,31]
// %e: space-padded day of the month as a decimal number [ 1,31]
// %j: day of the year as a decimal number [001,366]
// %u: Monday-based (ISO 8601) weekday as a decimal number [1,7]
// %w: Sunday-based weekday as a decimal number [0,6]
// %x: the locale’s date, such as %-m/%-d/%Y
) {
definedDelta = ONEDAY;
if (noDtick && !isMDate && ax.dtick < ONEDAY) ax.dtick = ONEDAY;
} else if (/%[UVW]/.test(tickformat)
// %U: Sunday-based week of the year as a decimal number [00,53]
// %V: ISO 8601 week of the year as a decimal number [01, 53]
// %W: Monday-based week of the year as a decimal number [00,53]
) {
definedDelta = ONEWEEK;
if (noDtick && !isMDate && ax.dtick < ONEWEEK) ax.dtick = ONEWEEK;
} else if (/%[Bbm]/.test(tickformat)
// %B: full month name
// %b: abbreviated month name
// %m: month as a decimal number [01,12]
) {
definedDelta = ONEAVGMONTH;
if (noDtick && (isMDate ? nMonths(ax.dtick) < 1 : ax.dtick < ONEMINMONTH)) ax.dtick = 'M1';
} else if (/%[q]/.test(tickformat)
// %q: quarter of the year as a decimal number [1,4]
) {
definedDelta = ONEAVGQUARTER;
if (noDtick && (isMDate ? nMonths(ax.dtick) < 3 : ax.dtick < ONEMINQUARTER)) ax.dtick = 'M3';
} else if (/%[Yy]/.test(tickformat)
// %Y: year with century as a decimal number, such as 1999
// %y: year without century as a decimal number [00,99]
) {
definedDelta = ONEAVGYEAR;
if (noDtick && (isMDate ? nMonths(ax.dtick) < 12 : ax.dtick < ONEMINYEAR)) ax.dtick = 'M12';
}
}
}
isMDate = mDate();
if (isMDate && ax.tick0 === ax._dowTick0) {
// discard Sunday/Monday tweaks
ax.tick0 = ax._rawTick0;
}
ax._definedDelta = definedDelta;
}
function positionPeriodTicks(tickVals, ax, definedDelta) {
for (var i = 0; i < tickVals.length; i++) {
var v = tickVals[i].value;
var a = i;
var b = i + 1;
if (i < tickVals.length - 1) {
a = i;
b = i + 1;
} else if (i > 0) {
a = i - 1;
b = i;
} else {
a = i;
b = i;
}
var A = tickVals[a].value;
var B = tickVals[b].value;
var actualDelta = Math.abs(B - A);
var delta = definedDelta || actualDelta;
var periodLength = 0;
if (delta >= ONEMINYEAR) {
if (actualDelta >= ONEMINYEAR && actualDelta <= ONEMAXYEAR) {
periodLength = actualDelta;
} else {
periodLength = ONEAVGYEAR;
}
} else if (definedDelta === ONEAVGQUARTER && delta >= ONEMINQUARTER) {
if (actualDelta >= ONEMINQUARTER && actualDelta <= ONEMAXQUARTER) {
periodLength = actualDelta;
} else {
periodLength = ONEAVGQUARTER;
}
} else if (delta >= ONEMINMONTH) {
if (actualDelta >= ONEMINMONTH && actualDelta <= ONEMAXMONTH) {
periodLength = actualDelta;
} else {
periodLength = ONEAVGMONTH;
}
} else if (definedDelta === ONEWEEK && delta >= ONEWEEK) {
periodLength = ONEWEEK;
} else if (delta >= ONEDAY) {
periodLength = ONEDAY;
} else if (definedDelta === HALFDAY && delta >= HALFDAY) {
periodLength = HALFDAY;
} else if (definedDelta === ONEHOUR && delta >= ONEHOUR) {
periodLength = ONEHOUR;
}
var inBetween;
if (periodLength >= actualDelta) {
// ensure new label positions remain between ticks
periodLength = actualDelta;
inBetween = true;
}
var endPeriod = v + periodLength;
if (ax.rangebreaks && periodLength > 0) {
var nAll = 84; // highly divisible 7 * 12
var n = 0;
for (var c = 0; c < nAll; c++) {
var r = (c + 0.5) / nAll;
if (ax.maskBreaks(v * (1 - r) + r * endPeriod) !== BADNUM) n++;
}
periodLength *= n / nAll;
if (!periodLength) {
tickVals[i].drop = true;
}
if (inBetween && actualDelta > ONEWEEK) periodLength = actualDelta; // center monthly & longer periods
}
if (periodLength > 0 ||
// not instant
i === 0 // taking care first tick added
) {
tickVals[i].periodX = v + periodLength / 2;
}
}
}
// calculate the ticks: text, values, positioning
// if ticks are set to automatic, determine the right values (tick0,dtick)
// in any case, set tickround to # of digits to round tick labels to,
// or codes to this effect for log and date scales
axes.calcTicks = function calcTicks(ax, opts) {
var type = ax.type;
var calendar = ax.calendar;
var ticklabelstep = ax.ticklabelstep;
var isPeriod = ax.ticklabelmode === 'period';
var isReversed = ax.range[0] > ax.range[1];
var ticklabelIndex = !ax.ticklabelindex || Lib.isArrayOrTypedArray(ax.ticklabelindex) ? ax.ticklabelindex : [ax.ticklabelindex];
var rng = Lib.simpleMap(ax.range, ax.r2l, undefined, undefined, opts);
var axrev = rng[1] < rng[0];
var minRange = Math.min(rng[0], rng[1]);
var maxRange = Math.max(rng[0], rng[1]);
var maxTicks = Math.max(1000, ax._length || 0);
var ticksOut = [];
var minorTicks = [];
var tickVals = [];
var minorTickVals = [];
// all ticks for which labels are drawn which is not necessarily the major ticks when
// `ticklabelindex` is set.
var allTicklabelVals = [];
var hasMinor = ax.minor && (ax.minor.ticks || ax.minor.showgrid);
// calc major first
for (var major = 1; major >= (hasMinor ? 0 : 1); major--) {
var isMinor = !major;
if (major) {
ax._dtickInit = ax.dtick;
ax._tick0Init = ax.tick0;
} else {
ax.minor._dtickInit = ax.minor.dtick;
ax.minor._tick0Init = ax.minor.tick0;
}
var mockAx = major ? ax : Lib.extendFlat({}, ax, ax.minor);
if (isMinor) {
axes.prepMinorTicks(mockAx, ax, opts);
} else {
axes.prepTicks(mockAx, opts);
}
// now that we've figured out the auto values for formatting
// in case we're missing some ticktext, we can break out for array ticks
if (mockAx.tickmode === 'array') {
if (major) {
tickVals = [];
ticksOut = arrayTicks(ax, !isMinor);
} else {
minorTickVals = [];
minorTicks = arrayTicks(ax, !isMinor);
}
continue;
}
// fill tickVals based on overlaying axis
if (mockAx.tickmode === 'sync') {
tickVals = [];
ticksOut = syncTicks(ax);
continue;
}
// add a tiny bit so we get ticks which may have rounded out
var exRng = expandRange(rng);
var startTick = exRng[0];
var endTick = exRng[1];
var numDtick = isNumeric(mockAx.dtick);
var isDLog = type === 'log' && !(numDtick || mockAx.dtick.charAt(0) === 'L');
// find the first tick
var x0 = axes.tickFirst(mockAx, opts);
if (major) {
ax._tmin = x0;
// No visible ticks? Quit.
// I've only seen this on category axes with all categories off the edge.
if (x0 < startTick !== axrev) break;
// return the full set of tick vals
if (type === 'category' || type === 'multicategory') {
endTick = axrev ? Math.max(-0.5, endTick) : Math.min(ax._categories.length - 0.5, endTick);
}
}
var prevX = null;
var x = x0;
var majorId;
if (major) {
// ids for ticklabelstep
var _dTick;
if (numDtick) {
_dTick = ax.dtick;
} else {
if (type === 'date') {
if (typeof ax.dtick === 'string' && ax.dtick.charAt(0) === 'M') {
_dTick = ONEAVGMONTH * ax.dtick.substring(1);
}
} else {
_dTick = ax._roughDTick;
}
}
majorId = Math.round((ax.r2l(x) - ax.r2l(ax.tick0)) / _dTick) - 1;
}
var dtick = mockAx.dtick;
if (mockAx.rangebreaks && mockAx._tick0Init !== mockAx.tick0) {
// adjust tick0
x = moveOutsideBreak(x, ax);
if (!axrev) {
x = axes.tickIncrement(x, dtick, !axrev, calendar);
}
}
if (major && isPeriod) {
// add one item to label period before tick0
x = axes.tickIncrement(x, dtick, !axrev, calendar);
majorId--;
}
for (; axrev ? x >= endTick : x <= endTick; x = axes.tickIncrement(x, dtick, axrev, calendar)) {
if (major) majorId++;
if (mockAx.rangebreaks) {
if (!axrev) {
if (x < startTick) continue;
if (mockAx.maskBreaks(x) === BADNUM && moveOutsideBreak(x, mockAx) >= maxRange) break;
}
}
// prevent infinite loops - no more than one tick per pixel,
// and make sure each value is different from the previous
if (tickVals.length > maxTicks || x === prevX) break;
prevX = x;
var obj = {
value: x
};
if (major) {
if (isDLog && x !== (x | 0)) {
obj.simpleLabel = true;
}
if (ticklabelstep > 1 && majorId % ticklabelstep) {
obj.skipLabel = true;
}
tickVals.push(obj);
} else {
obj.minor = true;
minorTickVals.push(obj);
}
}
}
// check if ticklabelIndex makes sense, otherwise ignore it
if (!minorTickVals || minorTickVals.length < 2) {
ticklabelIndex = false;
} else {
var diff = (minorTickVals[1].value - minorTickVals[0].value) * (isReversed ? -1 : 1);
if (!periodCompatibleWithTickformat(diff, ax.tickformat)) {
ticklabelIndex = false;
}
}
// Determine for which ticks to draw labels
if (!ticklabelIndex) {
allTicklabelVals = tickVals;
} else {
// Collect and sort all major and minor ticks, to find the minor ticks `ticklabelIndex`
// steps away from each major tick. For those minor ticks we want to draw the label.
var allTickVals = tickVals.concat(minorTickVals);
if (isPeriod && tickVals.length) {
// first major tick was just added for period handling
allTickVals = allTickVals.slice(1);
}
allTickVals = allTickVals.sort(function (a, b) {
return a.value - b.value;
}).filter(function (tick, index, self) {
return index === 0 || tick.value !== self[index - 1].value;
});
var majorTickIndices = allTickVals.map(function (item, index) {
return item.minor === undefined && !item.skipLabel ? index : null;
}).filter(function (index) {
return index !== null;
});
majorTickIndices.forEach(function (majorIdx) {
ticklabelIndex.map(function (nextLabelIdx) {
var minorIdx = majorIdx + nextLabelIdx;
if (minorIdx >= 0 && minorIdx < allTickVals.length) {
Lib.pushUnique(allTicklabelVals, allTickVals[minorIdx]);
}
});
});
}
if (hasMinor) {
var canOverlap = ax.minor.ticks === 'inside' && ax.ticks === 'outside' || ax.minor.ticks === 'outside' && ax.ticks === 'inside';
if (!canOverlap) {
// remove duplicate minors
var majorValues = tickVals.map(function (d) {
return d.value;
});
var list = [];
for (var k = 0; k < minorTickVals.length; k++) {
var T = minorTickVals[k];
var v = T.value;
if (majorValues.indexOf(v) !== -1) {
continue;
}
var found = false;
for (var q = 0; !found && q < tickVals.length; q++) {
if (
// add 10e6 to eliminate problematic digits
10e6 + tickVals[q].value === 10e6 + v) {
found = true;
}
}
if (!found) list.push(T);
}
minorTickVals = list;
}
}
if (isPeriod) positionPeriodTicks(allTicklabelVals, ax, ax._definedDelta);
var i;
if (ax.rangebreaks) {
var flip = ax._id.charAt(0) === 'y';
var fontSize = 1; // one pixel minimum
if (ax.tickmode === 'auto') {
fontSize = ax.tickfont ? ax.tickfont.size : 12;
}
var prevL = NaN;
for (i = tickVals.length - 1; i > -1; i--) {
if (tickVals[i].drop) {
tickVals.splice(i, 1);
continue;
}
tickVals[i].value = moveOutsideBreak(tickVals[i].value, ax);
// avoid overlaps
var l = ax.c2p(tickVals[i].value);
if (flip ? prevL > l - fontSize : prevL < l + fontSize) {
// ensure one pixel minimum
tickVals.splice(axrev ? i + 1 : i, 1);
} else {
prevL = l;
}
}
}
// If same angle over a full circle, the last tick vals is a duplicate.
// TODO must do something similar for angular date axes.
if (isAngular(ax) && Math.abs(rng[1] - rng[0]) === 360) {
tickVals.pop();
}
// save the last tick as well as first, so we can
// show the exponent only on the last one
ax._tmax = (tickVals[tickVals.length - 1] || {}).value;
// for showing the rest of a date when the main tick label is only the
// latter part: ax._prevDateHead holds what we showed most recently.
// Start with it cleared and mark that we're in calcTicks (ie calculating a
// whole string of these so we should care what the previous date head was!)
ax._prevDateHead = '';
ax._inCalcTicks = true;
var lastVisibleHead;
var hideLabel = function (tick) {
tick.text = '';
ax._prevDateHead = lastVisibleHead;
};
tickVals = tickVals.concat(minorTickVals);
function setTickLabel(ax, tickVal) {
var text = axes.tickText(ax, tickVal.value, false,
// hover
tickVal.simpleLabel // noSuffixPrefix
);
var p = tickVal.periodX;
if (p !== undefined) {
text.periodX = p;
if (p > maxRange || p < minRange) {
// hide label if outside the range
if (p > maxRange) text.periodX = maxRange;
if (p < minRange) text.periodX = minRange;
hideLabel(text);
}
}
return text;
}
var t;
for (i = 0; i < tickVals.length; i++) {
var _minor = tickVals[i].minor;
var _value = tickVals[i].value;
if (_minor) {
if (ticklabelIndex && allTicklabelVals.indexOf(tickVals[i]) !== -1) {
t = setTickLabel(ax, tickVals[i]);
} else {
t = {
x: _value
};
}
t.minor = true;
minorTicks.push(t);
} else {
lastVisibleHead = ax._prevDateHead;
t = setTickLabel(ax, tickVals[i]);
if (tickVals[i].skipLabel || ticklabelIndex && allTicklabelVals.indexOf(tickVals[i]) === -1) {
hideLabel(t);
}
ticksOut.push(t);
}
}
ticksOut = ticksOut.concat(minorTicks);
ax._inCalcTicks = false;
if (isPeriod && ticksOut.length) {
// drop very first tick that we added to handle period
ticksOut[0].noTick = true;
}
return ticksOut;
};
function filterRangeBreaks(ax, ticksOut) {
if (ax.rangebreaks) {
// remove ticks falling inside rangebreaks
ticksOut = ticksOut.filter(function (d) {
return ax.maskBreaks(d.x) !== BADNUM;
});
}
return ticksOut;
}
function syncTicks(ax) {
// get the overlaying axis
var baseAxis = ax._mainAxis;
var ticksOut = [];
if (baseAxis._vals) {
for (var i = 0; i < baseAxis._vals.length; i++) {
// filter vals with noTick flag
if (baseAxis._vals[i].noTick) {
continue;
}
// get the position of the every tick
var pos = baseAxis.l2p(baseAxis._vals[i].x);
// get the tick for the current axis based on position
var vali = ax.p2l(pos);
var obj = axes.tickText(ax, vali);
// assign minor ticks
if (baseAxis._vals[i].minor) {
obj.minor = true;
obj.text = '';
}
ticksOut.push(obj);
}
}
ticksOut = filterRangeBreaks(ax, ticksOut);
return ticksOut;
}
function arrayTicks(ax, majorOnly) {
var rng = Lib.simpleMap(ax.range, ax.r2l);
var exRng = expandRange(rng);
var tickMin = Math.min(exRng[0], exRng[1]);
var tickMax = Math.max(exRng[0], exRng[1]);
// make sure showing ticks doesn't accidentally add new categories
// TODO multicategory, if we allow ticktext / tickvals
var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l;
// array ticks on log axes always show the full number
// (if no explicit ticktext overrides it)
if (ax.type === 'log' && String(ax.dtick).charAt(0) !== 'L') {
ax.dtick = 'L' + Math.pow(10, Math.floor(Math.min(ax.range[0], ax.range[1])) - 1);
}
var ticksOut = [];
for (var isMinor = 0; isMinor <= 1; isMinor++) {
if (majorOnly !== undefined && (majorOnly && isMinor || majorOnly === false && !isMinor)) continue;
if (isMinor && !ax.minor) continue;
var vals = !isMinor ? ax.tickvals : ax.minor.tickvals;
var text = !isMinor ? ax.ticktext : [];
if (!vals) continue;
// without a text array, just format the given values as any other ticks
// except with more precision to the numbers
if (!Lib.isArrayOrTypedArray(text)) text = [];
for (var i = 0; i < vals.length; i++) {
var vali = tickVal2l(vals[i]);
if (vali > tickMin && vali < tickMax) {
var obj = axes.tickText(ax, vali, false, String(text[i]));
if (isMinor) {
obj.minor = true;
obj.text = '';
}
ticksOut.push(obj);
}
}
}
ticksOut = filterRangeBreaks(ax, ticksOut);
return ticksOut;
}
var roundBase10 = [2, 5, 10];
var roundBase24 = [1, 2, 3, 6, 12];
var roundBase60 = [1, 2, 5, 10, 15, 30];
// 2&3 day ticks are weird, but need something btwn 1&7
var roundDays = [1, 2, 3, 7, 14];
// approx. tick positions for log axes, showing all (1) and just 1, 2, 5 (2)
// these don't have to be exact, just close enough to round to the right value
var roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1];
var roundLog2 = [-0.301, 0, 0.301, 0.699, 1];
// N.B. `thetaunit; 'radians' angular axes must be converted to degrees
var roundAngles = [15, 30, 45, 90, 180];
function roundDTick(roughDTick, base, roundingSet) {
return base * Lib.roundUp(roughDTick / base, roundingSet);
}
// autoTicks: calculate best guess at pleasant ticks for this axis
// inputs:
// ax - an axis object
// roughDTick - rough tick spacing (to be turned into a nice round number)
// outputs (into ax):
// tick0: starting point for ticks (not necessarily on the graph)
// usually 0 for numeric (=10^0=1 for log) or jan 1, 2000 for dates
// dtick: the actual, nice round tick spacing, usually a little larger than roughDTick
// if the ticks are spaced linearly (linear scale, categories,
// log with only full powers, date ticks < month),
// this will just be a number
// months: M#
// years: M# where # is 12*number of years
// log with linear ticks: L# where # is the linear tick spacing
// log showing powers plus some intermediates:
// D1 shows all digits, D2 shows 2 and 5
axes.autoTicks = function (ax, roughDTick, isMinor) {
var base;
function getBase(v) {
return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10));
}
if (ax.type === 'date') {
ax.tick0 = Lib.dateTick0(ax.calendar, 0);
// the criteria below are all based on the rough spacing we calculate
// being > half of the final unit - so precalculate twice the rough val
var roughX2 = 2 * roughDTick;
if (roughX2 > ONEAVGYEAR) {
roughDTick /= ONEAVGYEAR;
base = getBase(10);
ax.dtick = 'M' + 12 * roundDTick(roughDTick, base, roundBase10);
} else if (roughX2 > ONEAVGMONTH) {
roughDTick /= ONEAVGMONTH;
ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24);
} else if (roughX2 > ONEDAY) {
ax.dtick = roundDTick(roughDTick, ONEDAY, ax._hasDayOfWeekBreaks ? [1, 2, 7, 14] : roundDays);
if (!isMinor) {
// get week ticks on sunday
// this will also move the base tick off 2000-01-01 if dtick is
// 2 or 3 days... but that's a weird enough case that we'll ignore it.
var tickformat = axes.getTickFormat(ax);
var isPeriod = ax.ticklabelmode === 'period';
if (isPeriod) ax._rawTick0 = ax.tick0;
if (/%[uVW]/.test(tickformat)) {
ax.tick0 = Lib.dateTick0(ax.calendar, 2); // Monday
} else {
ax.tick0 = Lib.dateTick0(ax.calendar, 1); // Sunday
}
if (isPeriod) ax._dowTick0 = ax.tick0;
}
} else if (roughX2 > ONEHOUR) {
ax.dtick = roundDTick(roughDTick, ONEHOUR, roundBase24);
} else if (roughX2 > ONEMIN) {
ax.dtick = roundDTick(roughDTick, ONEMIN, roundBase60);
} else if (roughX2 > ONESEC) {
ax.dtick = roundDTick(roughDTick, ONESEC, roundBase60);
} else {
// milliseconds
base = getBase(10);
ax.dtick = roundDTick(roughDTick, base, roundBase10);
}
} else if (ax.type === 'log') {
ax.tick0 = 0;
var rng = Lib.simpleMap(ax.range, ax.r2l);
if (ax._isMinor) {
// Log axes by default get MORE than nTicks based on the metrics below
// But for minor ticks we don't want this increase, we already have
// the major ticks.
roughDTick *= 1.5;
}
if (roughDTick > 0.7) {
// only show powers of 10
ax.dtick = Math.ceil(roughDTick);
} else if (Math.abs(rng[1] - rng[0]) < 1) {
// span is less than one power of 10
var nt = 1.5 * Math.abs((rng[1] - rng[0]) / roughDTick);
// ticks on a linear scale, labeled fully
roughDTick = Math.abs(Math.pow(10, rng[1]) - Math.pow(10, rng[0])) / nt;
base = getBase(10);
ax.dtick = 'L' + roundDTick(roughDTick, base, roundBase10);
} else {
// include intermediates between powers of 10,
// labeled with small digits
// ax.dtick = "D2" (show 2 and 5) or "D1" (show all digits)
ax.dtick = roughDTick > 0.3 ? 'D2' : 'D1';
}
} else if (ax.type === 'category' || ax.type === 'multicategory') {
ax.tick0 = 0;
ax.dtick = Math.ceil(Math.max(roughDTick, 1));
} else if (isAngular(ax)) {
ax.tick0 = 0;
base = 1;
ax.dtick = roundDTick(roughDTick, base, roundAngles);
} else {
// auto ticks always start at 0
ax.tick0 = 0;
base = getBase(10);
ax.dtick = roundDTick(roughDTick, base, roundBase10);
}
// prevent infinite loops
if (ax.dtick === 0) ax.dtick = 1;
// TODO: this is from log axis histograms with autorange off
if (!isNumeric(ax.dtick) && typeof ax.dtick !== 'string') {
var olddtick = ax.dtick;
ax.dtick = 1;
throw 'ax.dtick error: ' + String(olddtick);
}
};
// after dtick is already known, find tickround = precision
// to display in tick labels
// for numeric ticks, integer # digits after . to round to
// for date ticks, the last date part to show (y,m,d,H,M,S)
// or an integer # digits past seconds
function autoTickRound(ax) {
var dtick = ax.dtick;
ax._tickexponent = 0;
if (!isNumeric(dtick) && typeof dtick !== 'string') {
dtick = 1;
}
if (ax.type === 'category' || ax.type === 'multicategory') {
ax._tickround = null;
}
if (ax.type === 'date') {
// If tick0 is unusual, give tickround a bit more information
// not necessarily *all* the information in tick0 though, if it's really odd
// minimal string length for tick0: 'd' is 10, 'M' is 16, 'S' is 19
// take off a leading minus (year < 0) and i (intercalary month) so length is consistent
var tick0ms = ax.r2l(ax.tick0);
var tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, '');
var tick0len = tick0str.length;
if (String(dtick).charAt(0) === 'M') {
// any tick0 more specific than a year: alway show the full date
if (tick0len > 10 || tick0str.substr(5) !== '01-01') ax._tickround = 'd';
// show the month unless ticks are full multiples of a year
else ax._tickround = +dtick.substr(1) % 12 === 0 ? 'y' : 'm';
} else if (dtick >= ONEDAY && tick0len <= 10 || dtick >= ONEDAY * 15) ax._tickround = 'd';else if (dtick >= ONEMIN && tick0len <= 16 || dtick >= ONEHOUR) ax._tickround = 'M';else if (dtick >= ONESEC && tick0len <= 19 || dtick >= ONEMIN) ax._tickround = 'S';else {
// tickround is a number of digits of fractional seconds
// of any two adjacent ticks, at least one will have the maximum fractional digits
// of all possible ticks - so take the max. length of tick0 and the next one
var tick1len = ax.l2r(tick0ms + dtick).replace(/^-/, '').length;
ax._tickround = Math.max(tick0len, tick1len) - 20;
// We shouldn't get here... but in case there's a situation I'm
// not thinking of where tick0str and tick1str are identical or
// something, fall back on maximum precision
if (ax._tickround < 0) ax._tickround = 4;
}
} else if (isNumeric(dtick) || dtick.charAt(0) === 'L') {
// linear or log (except D1, D2)
var rng = ax.range.map(ax.r2d || Number);
if (!isNumeric(dtick)) dtick = Number(dtick.substr(1));
// 2 digits past largest digit of dtick
ax._tickround = 2 - Math.floor(Math.log(dtick) / Math.LN10 + 0.01);
var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1]));
var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01);
var minexponent = ax.minexponent === undefined ? 3 : ax.minexponent;
if (Math.abs(rangeexp) > minexponent) {
if (isSIFormat(ax.exponentformat) && !beyondSI(rangeexp)) {
ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3);
} else ax._tickexponent = rangeexp;
}
} else {
// D1 or D2 (log)
ax._tickround = null;
}
}
// months and years don't have constant millisecond values
// (but a year is always 12 months so we only need months)
// log-scale ticks are also not consistently spaced, except
// for pure powers of 10
// numeric ticks always have constant differences, other datetime ticks
// can all be calculated as constant number of milliseconds
axes.tickIncrement = function (x, dtick, axrev, calendar) {
var axSign = axrev ? -1 : 1;
// includes linear, all dates smaller than month, and pure 10^n in log
if (isNumeric(dtick)) return Lib.increment(x, axSign * dtick);
// everything else is a string, one character plus a number
var tType = dtick.charAt(0);
var dtSigned = axSign * Number(dtick.substr(1));
// Dates: months (or years - see Lib.incrementMonth)
if (tType === 'M') return Lib.incrementMonth(x, dtSigned, calendar);
// Log scales: Linear, Digits
if (tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10;
// log10 of 2,5,10, or all digits (logs just have to be
// close enough to round)
if (tType === 'D') {
var tickset = dtick === 'D2' ? roundLog2 : roundLog1;
var x2 = x + axSign * 0.01;
var frac = Lib.roundUp(Lib.mod(x2, 1), tickset, axrev);
return Math.floor(x2) + Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
}
throw 'unrecognized dtick ' + String(dtick);
};
// calculate the first tick on an axis
axes.tickFirst = function (ax, opts) {
var r2l = ax.r2l || Number;
var rng = Lib.simpleMap(ax.range, r2l, undefined, undefined, opts);
var axrev = rng[1] < rng[0];
var sRound = axrev ? Math.floor : Math.ceil;
// add a tiny extra bit to make sure we get ticks
// that may have been rounded out
var r0 = expandRange(rng)[0];
var dtick = ax.dtick;
var tick0 = r2l(ax.tick0);
if (isNumeric(dtick)) {
var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0;
// make sure no ticks outside the category list
if (ax.type === 'category' || ax.type === 'multicategory') {
tmin = Lib.constrain(tmin, 0, ax._categories.length - 1);
}
return tmin;
}
var tType = dtick.charAt(0);
var dtNum = Number(dtick.substr(1));
// Dates: months (or years)
if (tType === 'M') {
var cnt = 0;
var t0 = tick0;
var t1, mult, newDTick;
// This algorithm should work for *any* nonlinear (but close to linear!)
// tick spacing. Limit to 10 iterations, for gregorian months it's normally <=3.
while (cnt < 10) {
t1 = axes.tickIncrement(t0, dtick, axrev, ax.calendar);
if ((t1 - r0) * (t0 - r0) <= 0) {
// t1 and t0 are on opposite sides of r0! we've succeeded!
if (axrev) return Math.min(t0, t1);
return Math.max(t0, t1);
}
mult = (r0 - (t0 + t1) / 2) / (t1 - t0);
newDTick = tType + (Math.abs(Math.round(mult)) || 1) * dtNum;
t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar);
cnt++;
}
Lib.error('tickFirst did not converge', ax);
return t0;
} else if (tType === 'L') {
// Log scales: Linear, Digits
return Math.log(sRound((Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10;
} else if (tType === 'D') {
var tickset = dtick === 'D2' ? roundLog2 : roundLog1;
var frac = Lib.roundUp(Lib.mod(r0, 1), tickset, axrev);
return Math.floor(r0) + Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
} else throw 'unrecognized dtick ' + String(dtick);
};
// draw the text for one tick.
// px,py are the location on gd.paper
// prefix is there so the x axis ticks can be dropped a line
// ax is the axis layout, x is the tick value
// hover is a (truthy) flag for whether to show numbers with a bit
// more precision for hovertext
axes.tickText = function (ax, x, hover, noSuffixPrefix) {
var out = tickTextObj(ax, x);
var arrayMode = ax.tickmode === 'array';
var extraPrecision = hover || arrayMode;
var axType = ax.type;
// TODO multicategory, if we allow ticktext / tickvals
var tickVal2l = axType === 'category' ? ax.d2l_noadd : ax.d2l;
var i;
var inbounds = function (v) {
var p = ax.l2p(v);
return p >= 0 && p <= ax._length ? v : null;
};
if (arrayMode && Lib.isArrayOrTypedArray(ax.ticktext)) {
var rng = Lib.simpleMap(ax.range, ax.r2l);
var minDiff = (Math.abs(rng[1] - rng[0]) - (ax._lBreaks || 0)) / 10000;
for (i = 0; i < ax.ticktext.length; i++) {
if (Math.abs(x - tickVal2l(ax.tickvals[i])) < minDiff) break;
}
if (i < ax.ticktext.length) {
out.text = String(ax.ticktext[i]);
out.xbnd = [inbounds(out.x - 0.5), inbounds(out.x + ax.dtick - 0.5)];
return out;
}
}
function isHidden(showAttr) {
if (showAttr === undefined) return true;
if (hover) return showAttr === 'none';
var firstOrLast = {
first: ax._tmin,
last: ax._tmax
}[showAttr];
return showAttr !== 'all' && x !== firstOrLast;
}
var hideexp = hover ? 'never' : ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : '';
if (axType === 'date') formatDate(ax, out, hover, extraPrecision);else if (axType === 'log') formatLog(ax, out, hover, extraPrecision, hideexp);else if (axType === 'category') formatCategory(ax, out);else if (axType === 'multicategory') formatMultiCategory(ax, out, hover);else if (isAngular(ax)) formatAngle(ax, out, hover, extraPrecision, hideexp);else formatLinear(ax, out, hover, extraPrecision, hideexp);
// add prefix and suffix
if (!noSuffixPrefix) {
if (ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text;
if (ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix;
}
if (ax.labelalias && ax.labelalias.hasOwnProperty(out.text)) {
var t = ax.labelalias[out.text];
if (typeof t === 'string') out.text = t;
}
// Setup ticks and grid lines boundaries
// at 1/2 a 'category' to the left/bottom
if (ax.tickson === 'boundaries' || ax.showdividers) {
out.xbnd = [inbounds(out.x - 0.5), inbounds(out.x + ax.dtick - 0.5)];
}
return out;
};
/**
* create text for a hover label on this axis, with special handling of
* log axes (where negative values can't be displayed but can appear in hover text)
*
* @param {object} ax: the axis to format text for
* @param {number or array of numbers} values: calcdata value(s) to format
* @param {Optional(string)} hoverformat: trace (x|y)hoverformat to override axis.hoverformat
*
* @returns {string} `val` formatted as a string appropriate to this axis, or
* first value and second value as a range (ie '
- ') if the second value is provided and
* it's different from the first value.
*/
axes.hoverLabelText = function (ax, values, hoverformat) {
if (hoverformat) ax = Lib.extendFlat({}, ax, {
hoverformat: hoverformat
});
var val = Lib.isArrayOrTypedArray(values) ? values[0] : values;
var val2 = Lib.isArrayOrTypedArray(values) ? values[1] : undefined;
if (val2 !== undefined && val2 !== val) {
return axes.hoverLabelText(ax, val, hoverformat) + ' - ' + axes.hoverLabelText(ax, val2, hoverformat);
}
var logOffScale = ax.type === 'log' && val <= 0;
var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), 'hover').text;
if (logOffScale) {
return val === 0 ? '0' : MINUS_SIGN + tx;
}
// TODO: should we do something special if the axis calendar and
// the data calendar are different? Somehow display both dates with
// their system names? Right now it will just display in the axis calendar
// but users could add the other one as text.
return tx;
};
function tickTextObj(ax, x, text) {
var tf = ax.tickfont || {};
return {
x: x,
dx: 0,
dy: 0,
text: text || '',
fontSize: tf.size,
font: tf.family,
fontWeight: tf.weight,
fontStyle: tf.style,
fontVariant: tf.variant,
fontTextcase: tf.textcase,
fontLineposition: tf.lineposition,
fontShadow: tf.shadow,
fontColor: tf.color
};
}
function formatDate(ax, out, hover, extraPrecision) {
var tr = ax._tickround;
var fmt = hover && ax.hoverformat || axes.getTickFormat(ax);
// Only apply extra precision if no explicit format was provided.
extraPrecision = !fmt && extraPrecision;
if (extraPrecision) {
// second or sub-second precision: extra always shows max digits.
// for other fields, extra precision just adds one field.
if (isNumeric(tr)) tr = 4;else tr = {
y: 'm',
m: 'd',
d: 'M',
M: 'S',
S: 4
}[tr];
}
var dateStr = Lib.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat);
var headStr;
var splitIndex = dateStr.indexOf('\n');
if (splitIndex !== -1) {
headStr = dateStr.substr(splitIndex + 1);
dateStr = dateStr.substr(0, splitIndex);
}
if (extraPrecision) {
// if extraPrecision led to trailing zeros, strip them off
// actually, this can lead to removing even more zeros than
// in the original rounding, but that's fine because in these
// contexts uniformity is not so important (if there's even
// anything to be uniform with!)
// can we remove the whole time part?
if (headStr !== undefined && (dateStr === '00:00:00' || dateStr === '00:00')) {
dateStr = headStr;
headStr = '';
} else if (dateStr.length === 8) {
// strip off seconds if they're zero (zero fractional seconds
// are already omitted)
// but we never remove minutes and leave just hours
dateStr = dateStr.replace(/:00$/, '');
}
}
if (headStr) {
if (hover) {
// hover puts it all on one line, so headPart works best up front
// except for year headPart: turn this into "Jan 1, 2000" etc.
if (tr === 'd') dateStr += ', ' + headStr;else dateStr = headStr + (dateStr ? ', ' + dateStr : '');
} else {
if (!ax._inCalcTicks || ax._prevDateHead !== headStr) {
ax._prevDateHead = headStr;
dateStr += ' ' + headStr;
} else {
var isInside = insideTicklabelposition(ax);
var side = ax._trueSide || ax.side; // polar mocks the side of the radial axis
if (!isInside && side === 'top' || isInside && side === 'bottom') {
dateStr += ' ';
}
}
}
}
out.text = dateStr;
}
function formatLog(ax, out, hover, extraPrecision, hideexp) {
var dtick = ax.dtick;
var x = out.x;
var tickformat = ax.tickformat;
var dtChar0 = typeof dtick === 'string' && dtick.charAt(0);
if (hideexp === 'never') {
// If this is a hover label, then we must *never* hide the exponent
// for the sake of display, which could give the wrong value by
// potentially many orders of magnitude. If hideexp was 'never', then
// it's now succeeded by preventing the other condition from automating
// this choice. Thus we can unset it so that the axis formatting takes
// precedence.
hideexp = '';
}
if (extraPrecision && dtChar0 !== 'L') {
dtick = 'L3';
dtChar0 = 'L';
}
if (tickformat || dtChar0 === 'L') {
out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision);
} else if (isNumeric(dtick) || dtChar0 === 'D' && Lib.mod(x + 0.01, 1) < 0.1) {
var p = Math.round(x);
var absP = Math.abs(p);
var exponentFormat = ax.exponentformat;
if (exponentFormat === 'power' || isSIFormat(exponentFormat) && beyondSI(p)) {
if (p === 0) out.text = 1;else if (p === 1) out.text = '10';else out.text = '10' + (p > 1 ? '' : MINUS_SIGN) + absP + ' ';
out.fontSize *= 1.25;
} else if ((exponentFormat === 'e' || exponentFormat === 'E') && absP > 2) {
out.text = '1' + exponentFormat + (p > 0 ? '+' : MINUS_SIGN) + absP;
} else {
out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover');
if (dtick === 'D1' && ax._id.charAt(0) === 'y') {
out.dy -= out.fontSize / 6;
}
}
} else if (dtChar0 === 'D') {
out.text = String(Math.round(Math.pow(10, Lib.mod(x, 1))));
out.fontSize *= 0.75;
} else throw 'unrecognized dtick ' + String(dtick);
// if 9's are printed on log scale, move the 10's away a bit
if (ax.dtick === 'D1') {
var firstChar = String(out.text).charAt(0);
if (firstChar === '0' || firstChar === '1') {
if (ax._id.charAt(0) === 'y') {
out.dx -= out.fontSize / 4;
} else {
out.dy += out.fontSize / 2;
out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) * out.fontSize * (x < 0 ? 0.5 : 0.25);
}
}
}
}
function formatCategory(ax, out) {
var tt = ax._categories[Math.round(out.x)];
if (tt === undefined) tt = '';
out.text = String(tt);
}
function formatMultiCategory(ax, out, hover) {
var v = Math.round(out.x);
var cats = ax._categories[v] || [];
var tt = cats[1] === undefined ? '' : String(cats[1]);
var tt2 = cats[0] === undefined ? '' : String(cats[0]);
if (hover) {
// TODO is this what we want?
out.text = tt2 + ' - ' + tt;
} else {
// setup for secondary labels
out.text = tt;
out.text2 = tt2;
}
}
function formatLinear(ax, out, hover, extraPrecision, hideexp) {
if (hideexp === 'never') {
// If this is a hover label, then we must *never* hide the exponent
// for the sake of display, which could give the wrong value by
// potentially many orders of magnitude. If hideexp was 'never', then
// it's now succeeded by preventing the other condition from automating
// this choice. Thus we can unset it so that the axis formatting takes
// precedence.
hideexp = '';
} else if (ax.showexponent === 'all' && Math.abs(out.x / ax.dtick) < 1e-6) {
// don't add an exponent to zero if we're showing all exponents
// so the only reason you'd show an exponent on zero is if it's the
// ONLY tick to get an exponent (first or last)
hideexp = 'hide';
}
out.text = numFormat(out.x, ax, hideexp, extraPrecision);
}
function formatAngle(ax, out, hover, extraPrecision, hideexp) {
if (ax.thetaunit === 'radians' && !hover) {
var num = out.x / 180;
if (num === 0) {
out.text = '0';
} else {
var frac = num2frac(num);
if (frac[1] >= 100) {
out.text = numFormat(Lib.deg2rad(out.x), ax, hideexp, extraPrecision);
} else {
var isNeg = out.x < 0;
if (frac[1] === 1) {
if (frac[0] === 1) out.text = 'π';else out.text = frac[0] + 'π';
} else {
out.text = ['', frac[0], ' ', '⁄', '', frac[1], ' ', 'π'].join('');
}
if (isNeg) out.text = MINUS_SIGN + out.text;
}
}
} else {
out.text = numFormat(out.x, ax, hideexp, extraPrecision);
}
}
// inspired by
// https://github.com/yisibl/num2fraction/blob/master/index.js
function num2frac(num) {
function almostEq(a, b) {
return Math.abs(a - b) <= 1e-6;
}
function findGCD(a, b) {
return almostEq(b, 0) ? a : findGCD(b, a % b);
}
function findPrecision(n) {
var e = 1;
while (!almostEq(Math.round(n * e) / e, n)) {
e *= 10;
}
return e;
}
var precision = findPrecision(num);
var number = num * precision;
var gcd = Math.abs(findGCD(number, precision));
return [
// numerator
Math.round(number / gcd),
// denominator
Math.round(precision / gcd)];
}
// format a number (tick value) according to the axis settings
// new, more reliable procedure than d3.round or similar:
// add half the rounding increment, then stringify and truncate
// also automatically switch to sci. notation
var SIPREFIXES = ['f', 'p', 'n', 'μ', 'm', '', 'k', 'M', 'G', 'T'];
function isSIFormat(exponentFormat) {
return exponentFormat === 'SI' || exponentFormat === 'B';
}
// are we beyond the range of common SI prefixes?
// 10^-16 -> 1x10^-16
// 10^-15 -> 1f
// ...
// 10^14 -> 100T
// 10^15 -> 1x10^15
// 10^16 -> 1x10^16
function beyondSI(exponent) {
return exponent > 14 || exponent < -15;
}
function numFormat(v, ax, fmtoverride, hover) {
var isNeg = v < 0;
// max number of digits past decimal point to show
var tickRound = ax._tickround;
var exponentFormat = fmtoverride || ax.exponentformat || 'B';
var exponent = ax._tickexponent;
var tickformat = axes.getTickFormat(ax);
var separatethousands = ax.separatethousands;
// special case for hover: set exponent just for this value, and
// add a couple more digits of precision over tick labels
if (hover) {
// make a dummy axis obj to get the auto rounding and exponent
var ah = {
exponentformat: exponentFormat,
minexponent: ax.minexponent,
dtick: ax.showexponent === 'none' ? ax.dtick : isNumeric(v) ? Math.abs(v) || 1 : 1,
// if not showing any exponents, don't change the exponent
// from what we calculate
range: ax.showexponent === 'none' ? ax.range.map(ax.r2d) : [0, v || 1]
};
autoTickRound(ah);
tickRound = (Number(ah._tickround) || 0) + 4;
exponent = ah._tickexponent;
if (ax.hoverformat) tickformat = ax.hoverformat;
}
if (tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN);
// 'epsilon' - rounding increment
var e = Math.pow(10, -tickRound) / 2;
// exponentFormat codes:
// 'e' (1.2e+6, default)
// 'E' (1.2E+6)
// 'SI' (1.2M)
// 'B' (same as SI except 10^9=B not G)
// 'none' (1200000)
// 'power' (1.2x10^6)
// 'hide' (1.2, use 3rd argument=='hide' to eg
// only show exponent on last tick)
if (exponentFormat === 'none') exponent = 0;
// take the sign out, put it back manually at the end
// - makes cases easier
v = Math.abs(v);
if (v < e) {
// 0 is just 0, but may get exponent if it's the last tick
v = '0';
isNeg = false;
} else {
v += e;
// take out a common exponent, if any
if (exponent) {
v *= Math.pow(10, -exponent);
tickRound += exponent;
}
// round the mantissa
if (tickRound === 0) v = String(Math.floor(v));else if (tickRound < 0) {
v = String(Math.round(v));
v = v.substr(0, v.length + tickRound);
for (var i = tickRound; i < 0; i++) v += '0';
} else {
v = String(v);
var dp = v.indexOf('.') + 1;
if (dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, '');
}
// insert appropriate decimal point and thousands separator
v = Lib.numSeparate(v, ax._separators, separatethousands);
}
// add exponent
if (exponent && exponentFormat !== 'hide') {
if (isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power';
var signedExponent;
if (exponent < 0) signedExponent = MINUS_SIGN + -exponent;else if (exponentFormat !== 'power') signedExponent = '+' + exponent;else signedExponent = String(exponent);
if (exponentFormat === 'e' || exponentFormat === 'E') {
v += exponentFormat + signedExponent;
} else if (exponentFormat === 'power') {
v += '×10' + signedExponent + ' ';
} else if (exponentFormat === 'B' && exponent === 9) {
v += 'B';
} else if (isSIFormat(exponentFormat)) {
v += SIPREFIXES[exponent / 3 + 5];
}
}
// put sign back in and return
// replace standard minus character (which is technically a hyphen)
// with a true minus sign
if (isNeg) return MINUS_SIGN + v;
return v;
}
axes.getTickFormat = function (ax) {
var i;
function convertToMs(dtick) {
return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH;
}
function compareLogTicks(left, right) {
var priority = ['L', 'D'];
if (typeof left === typeof right) {
if (typeof left === 'number') {
return left - right;
} else {
var leftPriority = priority.indexOf(left.charAt(0));
var rightPriority = priority.indexOf(right.charAt(0));
if (leftPriority === rightPriority) {
return Number(left.replace(/(L|D)/g, '')) - Number(right.replace(/(L|D)/g, ''));
} else {
return leftPriority - rightPriority;
}
}
} else {
return typeof left === 'number' ? 1 : -1;
}
}
function isProperStop(dtick, range, convert) {
var convertFn = convert || function (x) {
return x;
};
var leftDtick = range[0];
var rightDtick = range[1];
return (!leftDtick && typeof leftDtick !== 'number' || convertFn(leftDtick) <= convertFn(dtick)) && (!rightDtick && typeof rightDtick !== 'number' || convertFn(rightDtick) >= convertFn(dtick));
}
function isProperLogStop(dtick, range) {
var isLeftDtickNull = range[0] === null;
var isRightDtickNull = range[1] === null;
var isDtickInRangeLeft = compareLogTicks(dtick, range[0]) >= 0;
var isDtickInRangeRight = compareLogTicks(dtick, range[1]) <= 0;
return (isLeftDtickNull || isDtickInRangeLeft) && (isRightDtickNull || isDtickInRangeRight);
}
var tickstop, stopi;
if (ax.tickformatstops && ax.tickformatstops.length > 0) {
switch (ax.type) {
case 'date':
case 'linear':
{
for (i = 0; i < ax.tickformatstops.length; i++) {
stopi = ax.tickformatstops[i];
if (stopi.enabled && isProperStop(ax.dtick, stopi.dtickrange, convertToMs)) {
tickstop = stopi;
break;
}
}
break;
}
case 'log':
{
for (i = 0; i < ax.tickformatstops.length; i++) {
stopi = ax.tickformatstops[i];
if (stopi.enabled && isProperLogStop(ax.dtick, stopi.dtickrange)) {
tickstop = stopi;
break;
}
}
break;
}
default:
}
}
return tickstop ? tickstop.value : ax.tickformat;
};
// getSubplots - extract all subplot IDs we need
// as an array of items like 'xy', 'x2y', 'x2y2'...
// sorted by x (x,x2,x3...) then y
// optionally restrict to only subplots containing axis object ax
//
// NOTE: this is currently only used OUTSIDE plotly.js (toolpanel, webapp)
// ideally we get rid of it there (or just copy this there) and remove it here
axes.getSubplots = function (gd, ax) {
var subplotObj = gd._fullLayout._subplots;
var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []);
var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots;
out.sort(function (a, b) {
var aParts = a.substr(1).split('y');
var bParts = b.substr(1).split('y');
if (aParts[0] === bParts[0]) return +aParts[1] - +bParts[1];
return +aParts[0] - +bParts[0];
});
return out;
};
// find all subplots with axis 'ax'
// NOTE: this is only used in axes.getSubplots (only used outside plotly.js) and
// gl2d/convert (where it restricts axis subplots to only those with gl2d)
axes.findSubplotsWithAxis = function (subplots, ax) {
var axMatch = new RegExp(ax._id.charAt(0) === 'x' ? '^' + ax._id + 'y' : ax._id + '$');
var subplotsWithAx = [];
for (var i = 0; i < subplots.length; i++) {
var sp = subplots[i];
if (axMatch.test(sp)) subplotsWithAx.push(sp);
}
return subplotsWithAx;
};
// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings
axes.makeClipPaths = function (gd) {
var fullLayout = gd._fullLayout;
// for more info: https://github.com/plotly/plotly.js/issues/2595
if (fullLayout._hasOnlyLargeSploms) return;
var fullWidth = {
_offset: 0,
_length: fullLayout.width,
_id: ''
};
var fullHeight = {
_offset: 0,
_length: fullLayout.height,
_id: ''
};
var xaList = axes.list(gd, 'x', true);
var yaList = axes.list(gd, 'y', true);
var clipList = [];
var i, j;
for (i = 0; i < xaList.length; i++) {
clipList.push({
x: xaList[i],
y: fullHeight
});
for (j = 0; j < yaList.length; j++) {
if (i === 0) clipList.push({
x: fullWidth,
y: yaList[j]
});
clipList.push({
x: xaList[i],
y: yaList[j]
});
}
}
// selectors don't work right with camelCase tags,
// have to use class instead
// https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I
var axClips = fullLayout._clips.selectAll('.axesclip').data(clipList, function (d) {
return d.x._id + d.y._id;
});
axClips.enter().append('clipPath').classed('axesclip', true).attr('id', function (d) {
return 'clip' + fullLayout._uid + d.x._id + d.y._id;
}).append('rect');
axClips.exit().remove();
axClips.each(function (d) {
d3.select(this).select('rect').attr({
x: d.x._offset || 0,
y: d.y._offset || 0,
width: d.x._length || 1,
height: d.y._length || 1
});
});
};
/**
* Main multi-axis drawing routine!
*
* @param {DOM element} gd : graph div
* @param {string or array of strings} arg : polymorphic argument
* @param {object} opts:
* - @param {boolean} skipTitle : optional flag to skip axis title draw/update
*
* Signature 1: Axes.draw(gd, 'redraw')
* use this to clear and redraw all axes on graph
*
* Signature 2: Axes.draw(gd, '')
* use this to draw all axes on graph w/o the selectAll().remove()
* of the 'redraw' signature
*
* Signature 3: Axes.draw(gd, [axId, axId2, ...])
* where the items are axis id string,
* use this to update multiple axes in one call
*
* N.B draw updates:
* - ax._r (stored range for use by zoom/pan)
* - ax._rl (stored linearized range for use by zoom/pan)
*/
axes.draw = function (gd, arg, opts) {
var fullLayout = gd._fullLayout;
if (arg === 'redraw') {
fullLayout._paper.selectAll('g.subplot').each(function (d) {
var id = d[0];
var plotinfo = fullLayout._plots[id];
if (plotinfo) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove();
plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').remove();
plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick2').remove();
plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick2').remove();
plotinfo.xaxislayer.selectAll('.' + xa._id + 'divider').remove();
plotinfo.yaxislayer.selectAll('.' + ya._id + 'divider').remove();
if (plotinfo.minorGridlayer) plotinfo.minorGridlayer.selectAll('path').remove();
if (plotinfo.gridlayer) plotinfo.gridlayer.selectAll('path').remove();
if (plotinfo.zerolinelayer) plotinfo.zerolinelayer.selectAll('path').remove();
fullLayout._infolayer.select('.g-' + xa._id + 'title').remove();
fullLayout._infolayer.select('.g-' + ya._id + 'title').remove();
}
});
}
var axList = !arg || arg === 'redraw' ? axes.listIds(gd) : arg;
var fullAxList = axes.list(gd);
// Get the list of the overlaying axis for all 'shift' axes
var overlayingShiftedAx = fullAxList.filter(function (ax) {
return ax.autoshift;
}).map(function (ax) {
return ax.overlaying;
});
// order axes that have dependency to other axes
axList.map(function (axId) {
var ax = axes.getFromId(gd, axId);
if (ax.tickmode === 'sync' && ax.overlaying) {
var overlayingIndex = axList.findIndex(function (axis) {
return axis === ax.overlaying;
});
if (overlayingIndex >= 0) {
axList.unshift(axList.splice(overlayingIndex, 1).shift());
}
}
});
var axShifts = {
false: {
left: 0,
right: 0
}
};
return Lib.syncOrAsync(axList.map(function (axId) {
return function () {
if (!axId) return;
var ax = axes.getFromId(gd, axId);
if (!opts) opts = {};
opts.axShifts = axShifts;
opts.overlayingShiftedAx = overlayingShiftedAx;
var axDone = axes.drawOne(gd, ax, opts);
if (ax._shiftPusher) {
incrementShift(ax, ax._fullDepth || 0, axShifts, true);
}
ax._r = ax.range.slice();
ax._rl = Lib.simpleMap(ax._r, ax.r2l);
return axDone;
};
}));
};
/**
* Draw one cartesian axis
*
* @param {DOM element} gd
* @param {object} ax (full) axis object
* @param {object} opts
* - @param {boolean} skipTitle (set to true to skip axis title draw call)
*
* Depends on:
* - ax._mainSubplot (from linkSubplots)
* - ax._mainAxis
* - ax._anchorAxis
* - ax._subplotsWith
* - ax._counterDomainMin, ax._counterDomainMax (optionally, from linkSubplots)
* - ax._tickAngles (on redraw only, old value relinked during supplyDefaults)
* - ax._mainLinePosition (from lsInner)
* - ax._mainMirrorPosition
* - ax._linepositions
*
* Fills in:
* - ax._vals:
* - ax._gridVals:
* - ax._selections:
* - ax._tickAngles:
* - ax._depth (when required only):
* - and calls ax.setScale
*/
axes.drawOne = function (gd, ax, opts) {
opts = opts || {};
var axShifts = opts.axShifts || {};
var overlayingShiftedAx = opts.overlayingShiftedAx || [];
var i, sp, plotinfo;
ax.setScale();
var fullLayout = gd._fullLayout;
var axId = ax._id;
var axLetter = axId.charAt(0);
var counterLetter = axes.counterLetter(axId);
var mainPlotinfo = fullLayout._plots[ax._mainSubplot];
// this happens when updating matched group with 'missing' axes
if (!mainPlotinfo) return;
ax._shiftPusher = ax.autoshift || overlayingShiftedAx.indexOf(ax._id) !== -1 || overlayingShiftedAx.indexOf(ax.overlaying) !== -1;
// An axis is also shifted by 1/2 of its own linewidth and inside tick length if applicable
// as well as its manually specified `shift` val if we're in the context of `autoshift`
if (ax._shiftPusher & ax.anchor === 'free') {
var selfPush = ax.linewidth / 2 || 0;
if (ax.ticks === 'inside') {
selfPush += ax.ticklen;
}
incrementShift(ax, selfPush, axShifts, true);
incrementShift(ax, ax.shift || 0, axShifts, false);
}
// Somewhat inelegant way of making sure that the shift value is only updated when the
// Axes.DrawOne() function is called from the right context. An issue when redrawing the
// axis as result of using the dragbox, for example.
if (opts.skipTitle !== true || ax._shift === undefined) ax._shift = setShiftVal(ax, axShifts);
var mainAxLayer = mainPlotinfo[axLetter + 'axislayer'];
var mainLinePosition = ax._mainLinePosition;
var mainLinePositionShift = mainLinePosition += ax._shift;
var mainMirrorPosition = ax._mainMirrorPosition;
var vals = ax._vals = axes.calcTicks(ax);
// Add a couple of axis properties that should cause us to recreate
// elements. Used in d3 data function.
var axInfo = [ax.mirror, mainLinePositionShift, mainMirrorPosition].join('_');
for (i = 0; i < vals.length; i++) {
vals[i].axInfo = axInfo;
}
// stash selections to avoid DOM queries e.g.
// - stash tickLabels selection, so that drawTitle can use it to scoot title
ax._selections = {};
// stash tick angle (including the computed 'auto' values) per tick-label class
// linkup 'previous' tick angles on redraws
if (ax._tickAngles) ax._prevTickAngles = ax._tickAngles;
ax._tickAngles = {};
// measure [in px] between axis position and outward-most part of bounding box
// (touching either the tick label or ticks)
// depth can be expansive to compute, so we only do so when required
ax._depth = null;
// calcLabelLevelBbox can be expensive,
// so make sure to not call it twice during the same Axes.drawOne call
// by stashing label-level bounding boxes per tick-label class
var llbboxes = {};
function getLabelLevelBbox(suffix) {
var cls = axId + (suffix || 'tick');
if (!llbboxes[cls]) llbboxes[cls] = calcLabelLevelBbox(ax, cls, mainLinePositionShift);
return llbboxes[cls];
}
if (!ax.visible) return;
var transTickFn = axes.makeTransTickFn(ax);
var transTickLabelFn = axes.makeTransTickLabelFn(ax);
var tickVals;
// We remove zero lines, grid lines, and inside ticks if they're within 1px of the end
// The key case here is removing zero lines when the axis bound is zero
var valsClipped;
var insideTicks = ax.ticks === 'inside';
var outsideTicks = ax.ticks === 'outside';
if (ax.tickson === 'boundaries') {
var boundaryVals = getBoundaryVals(ax, vals);
valsClipped = axes.clipEnds(ax, boundaryVals);
tickVals = insideTicks ? valsClipped : boundaryVals;
} else {
valsClipped = axes.clipEnds(ax, vals);
tickVals = insideTicks && ax.ticklabelmode !== 'period' ? valsClipped : vals;
}
var gridVals = ax._gridVals = valsClipped;
var dividerVals = getDividerVals(ax, vals);
if (!fullLayout._hasOnlyLargeSploms) {
var subplotsWithAx = ax._subplotsWith;
// keep track of which subplots (by main counter axis) we've already
// drawn grids for, so we don't overdraw overlaying subplots
var finishedGrids = {};
for (i = 0; i < subplotsWithAx.length; i++) {
sp = subplotsWithAx[i];
plotinfo = fullLayout._plots[sp];
var counterAxis = plotinfo[counterLetter + 'axis'];
var mainCounterID = counterAxis._mainAxis._id;
if (finishedGrids[mainCounterID]) continue;
finishedGrids[mainCounterID] = 1;
var gridPath = axLetter === 'x' ? 'M0,' + counterAxis._offset + 'v' + counterAxis._length : 'M' + counterAxis._offset + ',0h' + counterAxis._length;
axes.drawGrid(gd, ax, {
vals: gridVals,
counterAxis: counterAxis,
layer: plotinfo.gridlayer.select('.' + axId),
minorLayer: plotinfo.minorGridlayer.select('.' + axId),
path: gridPath,
transFn: transTickFn
});
axes.drawZeroLine(gd, ax, {
counterAxis: counterAxis,
layer: plotinfo.zerolinelayer,
path: gridPath,
transFn: transTickFn
});
}
}
var tickPath;
var majorTickSigns = axes.getTickSigns(ax);
var minorTickSigns = axes.getTickSigns(ax, 'minor');
if (ax.ticks || ax.minor && ax.minor.ticks) {
var majorTickPath = axes.makeTickPath(ax, mainLinePositionShift, majorTickSigns[2]);
var minorTickPath = axes.makeTickPath(ax, mainLinePositionShift, minorTickSigns[2], {
minor: true
});
var mirrorMajorTickPath;
var mirrorMinorTickPath;
var fullMajorTickPath;
var fullMinorTickPath;
if (ax._anchorAxis && ax.mirror && ax.mirror !== true) {
mirrorMajorTickPath = axes.makeTickPath(ax, mainMirrorPosition, majorTickSigns[3]);
mirrorMinorTickPath = axes.makeTickPath(ax, mainMirrorPosition, minorTickSigns[3], {
minor: true
});
fullMajorTickPath = majorTickPath + mirrorMajorTickPath;
fullMinorTickPath = minorTickPath + mirrorMinorTickPath;
} else {
mirrorMajorTickPath = '';
mirrorMinorTickPath = '';
fullMajorTickPath = majorTickPath;
fullMinorTickPath = minorTickPath;
}
if (ax.showdividers && outsideTicks && ax.tickson === 'boundaries') {
var dividerLookup = {};
for (i = 0; i < dividerVals.length; i++) {
dividerLookup[dividerVals[i].x] = 1;
}
tickPath = function (d) {
return dividerLookup[d.x] ? mirrorMajorTickPath : fullMajorTickPath;
};
} else {
tickPath = function (d) {
return d.minor ? fullMinorTickPath : fullMajorTickPath;
};
}
}
axes.drawTicks(gd, ax, {
vals: tickVals,
layer: mainAxLayer,
path: tickPath,
transFn: transTickFn
});
if (ax.mirror === 'allticks') {
var tickSubplots = Object.keys(ax._linepositions || {});
for (i = 0; i < tickSubplots.length; i++) {
sp = tickSubplots[i];
plotinfo = fullLayout._plots[sp];
// [bottom or left, top or right], free and main are handled above
var linepositions = ax._linepositions[sp] || [];
var p0 = linepositions[0];
var p1 = linepositions[1];
var isMinor = linepositions[2];
var spTickPath = axes.makeTickPath(ax, p0, isMinor ? majorTickSigns[0] : minorTickSigns[0], {
minor: isMinor
}) + axes.makeTickPath(ax, p1, isMinor ? majorTickSigns[1] : minorTickSigns[1], {
minor: isMinor
});
axes.drawTicks(gd, ax, {
vals: tickVals,
layer: plotinfo[axLetter + 'axislayer'],
path: spTickPath,
transFn: transTickFn
});
}
}
var seq = [];
// tick labels - for now just the main labels.
// TODO: mirror labels, esp for subplots
seq.push(function () {
return axes.drawLabels(gd, ax, {
vals: vals,
layer: mainAxLayer,
plotinfo: plotinfo,
transFn: transTickLabelFn,
labelFns: axes.makeLabelFns(ax, mainLinePositionShift)
});
});
if (ax.type === 'multicategory') {
var pad = {
x: 2,
y: 10
}[axLetter];
seq.push(function () {
var bboxKey = {
x: 'height',
y: 'width'
}[axLetter];
var standoff = getLabelLevelBbox()[bboxKey] + pad + (ax._tickAngles[axId + 'tick'] ? ax.tickfont.size * LINE_SPACING : 0);
return axes.drawLabels(gd, ax, {
vals: getSecondaryLabelVals(ax, vals),
layer: mainAxLayer,
cls: axId + 'tick2',
repositionOnUpdate: true,
secondary: true,
transFn: transTickFn,
labelFns: axes.makeLabelFns(ax, mainLinePositionShift + standoff * majorTickSigns[4])
});
});
seq.push(function () {
ax._depth = majorTickSigns[4] * (getLabelLevelBbox('tick2')[ax.side] - mainLinePositionShift);
return drawDividers(gd, ax, {
vals: dividerVals,
layer: mainAxLayer,
path: axes.makeTickPath(ax, mainLinePositionShift, majorTickSigns[4], {
len: ax._depth
}),
transFn: transTickFn
});
});
} else if (ax.title.hasOwnProperty('standoff')) {
seq.push(function () {
ax._depth = majorTickSigns[4] * (getLabelLevelBbox()[ax.side] - mainLinePositionShift);
});
}
var hasRangeSlider = Registry.getComponentMethod('rangeslider', 'isVisible')(ax);
if (!opts.skipTitle && !(hasRangeSlider && ax.side === 'bottom')) {
seq.push(function () {
return drawTitle(gd, ax);
});
}
seq.push(function () {
var s = ax.side.charAt(0);
var sMirror = OPPOSITE_SIDE[ax.side].charAt(0);
var pos = axes.getPxPosition(gd, ax);
var outsideTickLen = outsideTicks ? ax.ticklen : 0;
var llbbox;
var push;
var mirrorPush;
var rangeSliderPush;
if (ax.automargin || hasRangeSlider || ax._shiftPusher) {
if (ax.type === 'multicategory') {
llbbox = getLabelLevelBbox('tick2');
} else {
llbbox = getLabelLevelBbox();
if (axLetter === 'x' && s === 'b') {
ax._depth = Math.max(llbbox.width > 0 ? llbbox.bottom - pos : 0, outsideTickLen);
}
}
}
var axDepth = 0;
var titleDepth = 0;
if (ax._shiftPusher) {
axDepth = Math.max(outsideTickLen, llbbox.height > 0 ? s === 'l' ? pos - llbbox.left : llbbox.right - pos : 0);
if (ax.title.text !== fullLayout._dfltTitle[axLetter]) {
titleDepth = (ax._titleStandoff || 0) + (ax._titleScoot || 0);
if (s === 'l') {
titleDepth += approxTitleDepth(ax);
}
}
ax._fullDepth = Math.max(axDepth, titleDepth);
}
if (ax.automargin) {
push = {
x: 0,
y: 0,
r: 0,
l: 0,
t: 0,
b: 0
};
var domainIndices = [0, 1];
var shift = typeof ax._shift === 'number' ? ax._shift : 0;
if (axLetter === 'x') {
if (s === 'b') {
push[s] = ax._depth;
} else {
push[s] = ax._depth = Math.max(llbbox.width > 0 ? pos - llbbox.top : 0, outsideTickLen);
domainIndices.reverse();
}
if (llbbox.width > 0) {
var rExtra = llbbox.right - (ax._offset + ax._length);
if (rExtra > 0) {
push.xr = 1;
push.r = rExtra;
}
var lExtra = ax._offset - llbbox.left;
if (lExtra > 0) {
push.xl = 0;
push.l = lExtra;
}
}
} else {
if (s === 'l') {
ax._depth = Math.max(llbbox.height > 0 ? pos - llbbox.left : 0, outsideTickLen);
push[s] = ax._depth - shift;
} else {
ax._depth = Math.max(llbbox.height > 0 ? llbbox.right - pos : 0, outsideTickLen);
push[s] = ax._depth + shift;
domainIndices.reverse();
}
if (llbbox.height > 0) {
var bExtra = llbbox.bottom - (ax._offset + ax._length);
if (bExtra > 0) {
push.yb = 0;
push.b = bExtra;
}
var tExtra = ax._offset - llbbox.top;
if (tExtra > 0) {
push.yt = 1;
push.t = tExtra;
}
}
}
push[counterLetter] = ax.anchor === 'free' ? ax.position : ax._anchorAxis.domain[domainIndices[0]];
if (ax.title.text !== fullLayout._dfltTitle[axLetter]) {
push[s] += approxTitleDepth(ax) + (ax.title.standoff || 0);
}
if (ax.mirror && ax.anchor !== 'free') {
mirrorPush = {
x: 0,
y: 0,
r: 0,
l: 0,
t: 0,
b: 0
};
mirrorPush[sMirror] = ax.linewidth;
if (ax.mirror && ax.mirror !== true) mirrorPush[sMirror] += outsideTickLen;
if (ax.mirror === true || ax.mirror === 'ticks') {
mirrorPush[counterLetter] = ax._anchorAxis.domain[domainIndices[1]];
} else if (ax.mirror === 'all' || ax.mirror === 'allticks') {
mirrorPush[counterLetter] = [ax._counterDomainMin, ax._counterDomainMax][domainIndices[1]];
}
}
}
if (hasRangeSlider) {
rangeSliderPush = Registry.getComponentMethod('rangeslider', 'autoMarginOpts')(gd, ax);
}
if (typeof ax.automargin === 'string') {
filterPush(push, ax.automargin);
filterPush(mirrorPush, ax.automargin);
}
Plots.autoMargin(gd, axAutoMarginID(ax), push);
Plots.autoMargin(gd, axMirrorAutoMarginID(ax), mirrorPush);
Plots.autoMargin(gd, rangeSliderAutoMarginID(ax), rangeSliderPush);
});
return Lib.syncOrAsync(seq);
};
function filterPush(push, automargin) {
if (!push) return;
var keepMargin = Object.keys(MARGIN_MAPPING).reduce(function (data, nextKey) {
if (automargin.indexOf(nextKey) !== -1) {
MARGIN_MAPPING[nextKey].forEach(function (key) {
data[key] = 1;
});
}
return data;
}, {});
Object.keys(push).forEach(function (key) {
if (!keepMargin[key]) {
if (key.length === 1) push[key] = 0;else delete push[key];
}
});
}
function getBoundaryVals(ax, vals) {
var out = [];
var i;
// boundaryVals are never used for labels;
// no need to worry about the other tickTextObj keys
var _push = function (d, bndIndex) {
var xb = d.xbnd[bndIndex];
if (xb !== null) {
out.push(Lib.extendFlat({}, d, {
x: xb
}));
}
};
if (vals.length) {
for (i = 0; i < vals.length; i++) {
_push(vals[i], 0);
}
_push(vals[i - 1], 1);
}
return out;
}
function getSecondaryLabelVals(ax, vals) {
var out = [];
var lookup = {};
for (var i = 0; i < vals.length; i++) {
var d = vals[i];
if (lookup[d.text2]) {
lookup[d.text2].push(d.x);
} else {
lookup[d.text2] = [d.x];
}
}
for (var k in lookup) {
out.push(tickTextObj(ax, Lib.interp(lookup[k], 0.5), k));
}
return out;
}
function getDividerVals(ax, vals) {
var out = [];
var i, current;
var reversed = vals.length && vals[vals.length - 1].x < vals[0].x;
// never used for labels;
// no need to worry about the other tickTextObj keys
var _push = function (d, bndIndex) {
var xb = d.xbnd[bndIndex];
if (xb !== null) {
out.push(Lib.extendFlat({}, d, {
x: xb
}));
}
};
if (ax.showdividers && vals.length) {
for (i = 0; i < vals.length; i++) {
var d = vals[i];
if (d.text2 !== current) {
_push(d, reversed ? 1 : 0);
}
current = d.text2;
}
_push(vals[i - 1], reversed ? 0 : 1);
}
return out;
}
function calcLabelLevelBbox(ax, cls, mainLinePositionShift) {
var top, bottom;
var left, right;
if (ax._selections[cls].size()) {
top = Infinity;
bottom = -Infinity;
left = Infinity;
right = -Infinity;
ax._selections[cls].each(function () {
var thisLabel = selectTickLabel(this);
// Use parent node , to make Drawing.bBox
// retrieve a bbox computed with transform info
//
// To improve perf, it would be nice to use `thisLabel.node()`
// (like in fixLabelOverlaps) instead and use Axes.getPxPosition
// together with the makeLabelFns outputs and `tickangle`
// to compute one bbox per (tick value x tick style)
var bb = Drawing.bBox(thisLabel.node().parentNode);
top = Math.min(top, bb.top);
bottom = Math.max(bottom, bb.bottom);
left = Math.min(left, bb.left);
right = Math.max(right, bb.right);
});
} else {
var dummyCalc = axes.makeLabelFns(ax, mainLinePositionShift);
top = bottom = dummyCalc.yFn({
dx: 0,
dy: 0,
fontSize: 0
});
left = right = dummyCalc.xFn({
dx: 0,
dy: 0,
fontSize: 0
});
}
return {
top: top,
bottom: bottom,
left: left,
right: right,
height: bottom - top,
width: right - left
};
}
/**
* Which direction do the 'ax.side' values, and free ticks go?
*
* @param {object} ax (full) axis object
* - {string} _id (starting with 'x' or 'y')
* - {string} side
* - {string} ticks
* @return {array} all entries are either -1 or 1
* - [0]: sign for top/right ticks (i.e. negative SVG direction)
* - [1]: sign for bottom/left ticks (i.e. positive SVG direction)
* - [2]: sign for ticks corresponding to 'ax.side'
* - [3]: sign for ticks mirroring 'ax.side'
* - [4]: sign of arrow starting at axis pointing towards margin
*/
axes.getTickSigns = function (ax, minor) {
var axLetter = ax._id.charAt(0);
var sideOpposite = {
x: 'top',
y: 'right'
}[axLetter];
var main = ax.side === sideOpposite ? 1 : -1;
var out = [-1, 1, main, -main];
// then we flip if outside XOR y axis
var ticks = minor ? (ax.minor || {}).ticks : ax.ticks;
if (ticks !== 'inside' === (axLetter === 'x')) {
out = out.map(function (v) {
return -v;
});
}
// independent of `ticks`; do not flip this one
if (ax.side) {
out.push({
l: -1,
t: -1,
r: 1,
b: 1
}[ax.side.charAt(0)]);
}
return out;
};
/**
* Make axis translate transform function
*
* @param {object} ax (full) axis object
* - {string} _id
* - {number} _offset
* - {fn} l2p
* @return {fn} function of calcTicks items
*/
axes.makeTransTickFn = function (ax) {
return ax._id.charAt(0) === 'x' ? function (d) {
return strTranslate(ax._offset + ax.l2p(d.x), 0);
} : function (d) {
return strTranslate(0, ax._offset + ax.l2p(d.x));
};
};
axes.makeTransTickLabelFn = function (ax) {
var uv = getTickLabelUV(ax);
var shift = ax.ticklabelshift || 0;
var standoff = ax.ticklabelstandoff || 0;
var u = uv[0];
var v = uv[1];
var isReversed = ax.range[0] > ax.range[1];
var labelsInside = ax.ticklabelposition && ax.ticklabelposition.indexOf('inside') !== -1;
var labelsOutside = !labelsInside;
if (shift) {
var shiftSign = isReversed ? -1 : 1;
shift = shift * shiftSign;
}
if (standoff) {
var side = ax.side;
var standoffSign = labelsInside && (side === 'top' || side === 'left') || labelsOutside && (side === 'bottom' || side === 'right') ? 1 : -1;
standoff = standoff * standoffSign;
}
return ax._id.charAt(0) === 'x' ? function (d) {
return strTranslate(u + ax._offset + ax.l2p(getPosX(d)) + shift, v + standoff);
} : function (d) {
return strTranslate(v + standoff, u + ax._offset + ax.l2p(getPosX(d)) + shift);
};
};
function getPosX(d) {
return d.periodX !== undefined ? d.periodX : d.x;
}
// u is a shift along the axis,
// v is a shift perpendicular to the axis
function getTickLabelUV(ax) {
var ticklabelposition = ax.ticklabelposition || '';
var has = function (str) {
return ticklabelposition.indexOf(str) !== -1;
};
var isTop = has('top');
var isLeft = has('left');
var isRight = has('right');
var isBottom = has('bottom');
var isInside = has('inside');
var isAligned = isBottom || isLeft || isTop || isRight;
// early return
if (!isAligned && !isInside) return [0, 0];
var side = ax.side;
var u = isAligned ? (ax.tickwidth || 0) / 2 : 0;
var v = TEXTPAD;
var fontSize = ax.tickfont ? ax.tickfont.size : 12;
if (isBottom || isTop) {
u += fontSize * CAP_SHIFT;
v += (ax.linewidth || 0) / 2;
}
if (isLeft || isRight) {
u += (ax.linewidth || 0) / 2;
v += TEXTPAD;
}
if (isInside && side === 'top') {
v -= fontSize * (1 - CAP_SHIFT);
}
if (isLeft || isTop) u = -u;
if (side === 'bottom' || side === 'right') v = -v;
return [isAligned ? u : 0, isInside ? v : 0];
}
/**
* Make axis tick path string
*
* @param {object} ax (full) axis object
* - {string} _id
* - {number} ticklen
* - {number} linewidth
* @param {number} shift along direction of ticklen
* @param {1 or -1} sgn tick sign
* @param {object} opts
* - {number (optional)} len tick length
* @return {string}
*/
axes.makeTickPath = function (ax, shift, sgn, opts) {
if (!opts) opts = {};
var minor = opts.minor;
if (minor && !ax.minor) return '';
var len = opts.len !== undefined ? opts.len : minor ? ax.minor.ticklen : ax.ticklen;
var axLetter = ax._id.charAt(0);
var pad = (ax.linewidth || 1) / 2;
return axLetter === 'x' ? 'M0,' + (shift + pad * sgn) + 'v' + len * sgn : 'M' + (shift + pad * sgn) + ',0h' + len * sgn;
};
/**
* Make axis tick label x, y and anchor functions
*
* @param {object} ax (full) axis object
* - {string} _id
* - {string} ticks
* - {number} ticklen
* - {string} side
* - {number} linewidth
* - {number} tickfont.size
* - {boolean} showline
* @param {number} shift
* @param {number} angle [in degrees] ...
* @return {object}
* - {fn} xFn
* - {fn} yFn
* - {fn} anchorFn
* - {fn} heightFn
* - {number} labelStandoff (gap parallel to ticks)
* - {number} labelShift (gap perpendicular to ticks)
*/
axes.makeLabelFns = function (ax, shift, angle) {
var ticklabelposition = ax.ticklabelposition || '';
var has = function (str) {
return ticklabelposition.indexOf(str) !== -1;
};
var isTop = has('top');
var isLeft = has('left');
var isRight = has('right');
var isBottom = has('bottom');
var isAligned = isBottom || isLeft || isTop || isRight;
var insideTickLabels = has('inside');
var labelsOverTicks = ticklabelposition === 'inside' && ax.ticks === 'inside' || !insideTickLabels && ax.ticks === 'outside' && ax.tickson !== 'boundaries';
var labelStandoff = 0;
var labelShift = 0;
var tickLen = labelsOverTicks ? ax.ticklen : 0;
if (insideTickLabels) {
tickLen *= -1;
} else if (isAligned) {
tickLen = 0;
}
if (labelsOverTicks) {
labelStandoff += tickLen;
if (angle) {
var rad = Lib.deg2rad(angle);
labelStandoff = tickLen * Math.cos(rad) + 1;
labelShift = tickLen * Math.sin(rad);
}
}
if (ax.showticklabels && (labelsOverTicks || ax.showline)) {
labelStandoff += 0.2 * ax.tickfont.size;
}
labelStandoff += (ax.linewidth || 1) / 2 * (insideTickLabels ? -1 : 1);
var out = {
labelStandoff: labelStandoff,
labelShift: labelShift
};
var x0, y0, ff, flipIt;
var xQ = 0;
var side = ax.side;
var axLetter = ax._id.charAt(0);
var tickangle = ax.tickangle;
var endSide;
if (axLetter === 'x') {
endSide = !insideTickLabels && side === 'bottom' || insideTickLabels && side === 'top';
flipIt = endSide ? 1 : -1;
if (insideTickLabels) flipIt *= -1;
x0 = labelShift * flipIt;
y0 = shift + labelStandoff * flipIt;
ff = endSide ? 1 : -0.2;
if (Math.abs(tickangle) === 90) {
if (insideTickLabels) {
ff += MID_SHIFT;
} else {
if (tickangle === -90 && side === 'bottom') {
ff = CAP_SHIFT;
} else if (tickangle === 90 && side === 'top') {
ff = MID_SHIFT;
} else {
ff = 0.5;
}
}
xQ = MID_SHIFT / 2 * (tickangle / 90);
}
out.xFn = function (d) {
return d.dx + x0 + xQ * d.fontSize;
};
out.yFn = function (d) {
return d.dy + y0 + d.fontSize * ff;
};
out.anchorFn = function (d, a) {
if (isAligned) {
if (isLeft) return 'end';
if (isRight) return 'start';
}
if (!isNumeric(a) || a === 0 || a === 180) {
return 'middle';
}
return a * flipIt < 0 !== insideTickLabels ? 'end' : 'start';
};
out.heightFn = function (d, a, h) {
return a < -60 || a > 60 ? -0.5 * h : ax.side === 'top' !== insideTickLabels ? -h : 0;
};
} else if (axLetter === 'y') {
endSide = !insideTickLabels && side === 'left' || insideTickLabels && side === 'right';
flipIt = endSide ? 1 : -1;
if (insideTickLabels) flipIt *= -1;
x0 = labelStandoff;
y0 = labelShift * flipIt;
ff = 0;
if (!insideTickLabels && Math.abs(tickangle) === 90) {
if (tickangle === -90 && side === 'left' || tickangle === 90 && side === 'right') {
ff = CAP_SHIFT;
} else {
ff = 0.5;
}
}
if (insideTickLabels) {
var ang = isNumeric(tickangle) ? +tickangle : 0;
if (ang !== 0) {
var rA = Lib.deg2rad(ang);
xQ = Math.abs(Math.sin(rA)) * CAP_SHIFT * flipIt;
ff = 0;
}
}
out.xFn = function (d) {
return d.dx + shift - (x0 + d.fontSize * ff) * flipIt + xQ * d.fontSize;
};
out.yFn = function (d) {
return d.dy + y0 + d.fontSize * MID_SHIFT;
};
out.anchorFn = function (d, a) {
if (isNumeric(a) && Math.abs(a) === 90) {
return 'middle';
}
return endSide ? 'end' : 'start';
};
out.heightFn = function (d, a, h) {
if (ax.side === 'right') a *= -1;
return a < -30 ? -h : a < 30 ? -0.5 * h : 0;
};
}
return out;
};
function tickDataFn(d) {
return [d.text, d.x, d.axInfo, d.font, d.fontSize, d.fontColor].join('_');
}
/**
* Draw axis ticks
*
* @param {DOM element} gd
* @param {object} ax (full) axis object
* - {string} _id
* - {string} ticks
* - {number} linewidth
* - {string} tickcolor
* @param {object} opts
* - {array of object} vals (calcTicks output-like)
* - {d3 selection} layer
* - {string or fn} path
* - {fn} transFn
* - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
*/
axes.drawTicks = function (gd, ax, opts) {
opts = opts || {};
var cls = ax._id + 'tick';
var vals = [].concat(ax.minor && ax.minor.ticks ?
// minor vals
opts.vals.filter(function (d) {
return d.minor && !d.noTick;
}) : []).concat(ax.ticks ?
// major vals
opts.vals.filter(function (d) {
return !d.minor && !d.noTick;
}) : []);
var ticks = opts.layer.selectAll('path.' + cls).data(vals, tickDataFn);
ticks.exit().remove();
ticks.enter().append('path').classed(cls, 1).classed('ticks', 1).classed('crisp', opts.crisp !== false).each(function (d) {
return Color.stroke(d3.select(this), d.minor ? ax.minor.tickcolor : ax.tickcolor);
}).style('stroke-width', function (d) {
return Drawing.crispRound(gd, d.minor ? ax.minor.tickwidth : ax.tickwidth, 1) + 'px';
}).attr('d', opts.path).style('display', null); // visible
hideCounterAxisInsideTickLabels(ax, [TICK_PATH]);
ticks.attr('transform', opts.transFn);
};
/**
* Draw axis grid
*
* @param {DOM element} gd
* @param {object} ax (full) axis object
* - {string} _id
* - {boolean} showgrid
* - {string} gridcolor
* - {string} gridwidth
* - {string} griddash
* - {boolean} zeroline
* - {string} type
* - {string} dtick
* @param {object} opts
* - {array of object} vals (calcTicks output-like)
* - {d3 selection} layer
* - {object} counterAxis (full axis object corresponding to counter axis)
* optional - only required if this axis supports zero lines
* - {string or fn} path
* - {fn} transFn
* - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
*/
axes.drawGrid = function (gd, ax, opts) {
opts = opts || {};
if (ax.tickmode === 'sync') {
// for tickmode sync we use the overlaying axis grid
return;
}
var cls = ax._id + 'grid';
var hasMinor = ax.minor && ax.minor.showgrid;
var minorVals = hasMinor ? opts.vals.filter(function (d) {
return d.minor;
}) : [];
var majorVals = ax.showgrid ? opts.vals.filter(function (d) {
return !d.minor;
}) : [];
var counterAx = opts.counterAxis;
if (counterAx && axes.shouldShowZeroLine(gd, ax, counterAx)) {
var isArrayMode = ax.tickmode === 'array';
for (var i = 0; i < majorVals.length; i++) {
var xi = majorVals[i].x;
if (isArrayMode ? !xi : Math.abs(xi) < ax.dtick / 100) {
majorVals = majorVals.slice(0, i).concat(majorVals.slice(i + 1));
// In array mode you can in principle have multiple
// ticks at 0, so test them all. Otherwise once we found
// one we can stop.
if (isArrayMode) i--;else break;
}
}
}
ax._gw = Drawing.crispRound(gd, ax.gridwidth, 1);
var wMinor = !hasMinor ? 0 : Drawing.crispRound(gd, ax.minor.gridwidth, 1);
var majorLayer = opts.layer;
var minorLayer = opts.minorLayer;
for (var major = 1; major >= 0; major--) {
var layer = major ? majorLayer : minorLayer;
if (!layer) continue;
var grid = layer.selectAll('path.' + cls).data(major ? majorVals : minorVals, tickDataFn);
grid.exit().remove();
grid.enter().append('path').classed(cls, 1).classed('crisp', opts.crisp !== false);
grid.attr('transform', opts.transFn).attr('d', opts.path).each(function (d) {
return Color.stroke(d3.select(this), d.minor ? ax.minor.gridcolor : ax.gridcolor || '#ddd');
}).style('stroke-dasharray', function (d) {
return Drawing.dashStyle(d.minor ? ax.minor.griddash : ax.griddash, d.minor ? ax.minor.gridwidth : ax.gridwidth);
}).style('stroke-width', function (d) {
return (d.minor ? wMinor : ax._gw) + 'px';
}).style('display', null); // visible
if (typeof opts.path === 'function') grid.attr('d', opts.path);
}
hideCounterAxisInsideTickLabels(ax, [GRID_PATH, MINORGRID_PATH]);
};
/**
* Draw axis zero-line
*
* @param {DOM element} gd
* @param {object} ax (full) axis object
* - {string} _id
* - {boolean} zeroline
* - {number} zerolinewidth
* - {string} zerolinecolor
* - {number (optional)} _gridWidthCrispRound
* @param {object} opts
* - {d3 selection} layer
* - {object} counterAxis (full axis object corresponding to counter axis)
* - {string or fn} path
* - {fn} transFn
* - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
*/
axes.drawZeroLine = function (gd, ax, opts) {
opts = opts || opts;
var cls = ax._id + 'zl';
var show = axes.shouldShowZeroLine(gd, ax, opts.counterAxis);
var zl = opts.layer.selectAll('path.' + cls).data(show ? [{
x: 0,
id: ax._id
}] : []);
zl.exit().remove();
zl.enter().append('path').classed(cls, 1).classed('zl', 1).classed('crisp', opts.crisp !== false).each(function () {
// use the fact that only one element can enter to trigger a sort.
// If several zerolines enter at the same time we will sort once per,
// but generally this should be a minimal overhead.
opts.layer.selectAll('path').sort(function (da, db) {
return idSort(da.id, db.id);
});
});
zl.attr('transform', opts.transFn).attr('d', opts.path).call(Color.stroke, ax.zerolinecolor || Color.defaultLine).style('stroke-width', Drawing.crispRound(gd, ax.zerolinewidth, ax._gw || 1) + 'px').style('display', null); // visible
hideCounterAxisInsideTickLabels(ax, [ZERO_PATH]);
};
/**
* Draw axis tick labels
*
* @param {DOM element} gd
* @param {object} ax (full) axis object
* - {string} _id
* - {boolean} showticklabels
* - {number} tickangle
* - {object (optional)} _selections
* - {object} (optional)} _tickAngles
* - {object} (optional)} _prevTickAngles
* @param {object} opts
* - {array of object} vals (calcTicks output-like)
* - {d3 selection} layer
* - {string (optional)} cls (node className)
* - {boolean} repositionOnUpdate (set to true to reposition update selection)
* - {boolean} secondary
* - {fn} transFn
* - {object} labelFns
* + {fn} xFn
* + {fn} yFn
* + {fn} anchorFn
* + {fn} heightFn
*/
axes.drawLabels = function (gd, ax, opts) {
opts = opts || {};
var fullLayout = gd._fullLayout;
var axId = ax._id;
var cls = opts.cls || axId + 'tick';
var vals = opts.vals.filter(function (d) {
return d.text;
});
var labelFns = opts.labelFns;
var tickAngle = opts.secondary ? 0 : ax.tickangle;
var prevAngle = (ax._prevTickAngles || {})[cls];
var tickLabels = opts.layer.selectAll('g.' + cls).data(ax.showticklabels ? vals : [], tickDataFn);
var labelsReady = [];
tickLabels.enter().append('g').classed(cls, 1).append('text')
// only so tex has predictable alignment that we can
// alter later
.attr('text-anchor', 'middle').each(function (d) {
var thisLabel = d3.select(this);
var newPromise = gd._promises.length;
thisLabel.call(svgTextUtils.positionText, labelFns.xFn(d), labelFns.yFn(d)).call(Drawing.font, {
family: d.font,
size: d.fontSize,
color: d.fontColor,
weight: d.fontWeight,
style: d.fontStyle,
variant: d.fontVariant,
textcase: d.fontTextcase,
lineposition: d.fontLineposition,
shadow: d.fontShadow
}).text(d.text).call(svgTextUtils.convertToTspans, gd);
if (gd._promises[newPromise]) {
// if we have an async label, we'll deal with that
// all here so take it out of gd._promises and
// instead position the label and promise this in
// labelsReady
labelsReady.push(gd._promises.pop().then(function () {
positionLabels(thisLabel, tickAngle);
}));
} else {
// sync label: just position it now.
positionLabels(thisLabel, tickAngle);
}
});
hideCounterAxisInsideTickLabels(ax, [TICK_TEXT]);
tickLabels.exit().remove();
if (opts.repositionOnUpdate) {
tickLabels.each(function (d) {
d3.select(this).select('text').call(svgTextUtils.positionText, labelFns.xFn(d), labelFns.yFn(d));
});
}
function positionLabels(s, angle) {
s.each(function (d) {
var thisLabel = d3.select(this);
var mathjaxGroup = thisLabel.select('.text-math-group');
var anchor = labelFns.anchorFn(d, angle);
var transform = opts.transFn.call(thisLabel.node(), d) + (isNumeric(angle) && +angle !== 0 ? ' rotate(' + angle + ',' + labelFns.xFn(d) + ',' + (labelFns.yFn(d) - d.fontSize / 2) + ')' : '');
// how much to shift a multi-line label to center it vertically.
var nLines = svgTextUtils.lineCount(thisLabel);
var lineHeight = LINE_SPACING * d.fontSize;
var anchorHeight = labelFns.heightFn(d, isNumeric(angle) ? +angle : 0, (nLines - 1) * lineHeight);
if (anchorHeight) {
transform += strTranslate(0, anchorHeight);
}
if (mathjaxGroup.empty()) {
var thisText = thisLabel.select('text');
thisText.attr({
transform: transform,
'text-anchor': anchor
});
thisText.style('opacity', 1); // visible
if (ax._adjustTickLabelsOverflow) {
ax._adjustTickLabelsOverflow();
}
} else {
var mjWidth = Drawing.bBox(mathjaxGroup.node()).width;
var mjShift = mjWidth * {
end: -0.5,
start: 0.5
}[anchor];
mathjaxGroup.attr('transform', transform + strTranslate(mjShift, 0));
}
});
}
ax._adjustTickLabelsOverflow = function () {
var ticklabeloverflow = ax.ticklabeloverflow;
if (!ticklabeloverflow || ticklabeloverflow === 'allow') return;
var hideOverflow = ticklabeloverflow.indexOf('hide') !== -1;
var isX = ax._id.charAt(0) === 'x';
// div positions
var p0 = 0;
var p1 = isX ? gd._fullLayout.width : gd._fullLayout.height;
if (ticklabeloverflow.indexOf('domain') !== -1) {
// domain positions
var rl = Lib.simpleMap(ax.range, ax.r2l);
p0 = ax.l2p(rl[0]) + ax._offset;
p1 = ax.l2p(rl[1]) + ax._offset;
}
var min = Math.min(p0, p1);
var max = Math.max(p0, p1);
var side = ax.side;
var visibleLabelMin = Infinity;
var visibleLabelMax = -Infinity;
tickLabels.each(function (d) {
var thisLabel = d3.select(this);
var mathjaxGroup = thisLabel.select('.text-math-group');
if (mathjaxGroup.empty()) {
var bb = Drawing.bBox(thisLabel.node());
var adjust = 0;
if (isX) {
if (bb.right > max) adjust = 1;else if (bb.left < min) adjust = 1;
} else {
if (bb.bottom > max) adjust = 1;else if (bb.top + (ax.tickangle ? 0 : d.fontSize / 4) < min) adjust = 1;
}
var t = thisLabel.select('text');
if (adjust) {
if (hideOverflow) t.style('opacity', 0); // hidden
} else {
t.style('opacity', 1); // visible
if (side === 'bottom' || side === 'right') {
visibleLabelMin = Math.min(visibleLabelMin, isX ? bb.top : bb.left);
} else {
visibleLabelMin = -Infinity;
}
if (side === 'top' || side === 'left') {
visibleLabelMax = Math.max(visibleLabelMax, isX ? bb.bottom : bb.right);
} else {
visibleLabelMax = Infinity;
}
}
} // TODO: hide mathjax?
});
for (var subplot in fullLayout._plots) {
var plotinfo = fullLayout._plots[subplot];
if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue;
var anchorAx = isX ? plotinfo.yaxis : plotinfo.xaxis;
if (anchorAx) {
anchorAx['_visibleLabelMin_' + ax._id] = visibleLabelMin;
anchorAx['_visibleLabelMax_' + ax._id] = visibleLabelMax;
}
}
};
ax._hideCounterAxisInsideTickLabels = function (partialOpts) {
var isX = ax._id.charAt(0) === 'x';
var anchoredAxes = [];
for (var subplot in fullLayout._plots) {
var plotinfo = fullLayout._plots[subplot];
if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue;
anchoredAxes.push(isX ? plotinfo.yaxis : plotinfo.xaxis);
}
anchoredAxes.forEach(function (anchorAx, idx) {
if (anchorAx && insideTicklabelposition(anchorAx)) {
(partialOpts || [ZERO_PATH, MINORGRID_PATH, GRID_PATH, TICK_PATH, TICK_TEXT]).forEach(function (e) {
var isPeriodLabel = e.K === 'tick' && e.L === 'text' && ax.ticklabelmode === 'period';
var mainPlotinfo = fullLayout._plots[ax._mainSubplot];
var sel;
if (e.K === ZERO_PATH.K) sel = mainPlotinfo.zerolinelayer.selectAll('.' + ax._id + 'zl');else if (e.K === MINORGRID_PATH.K) sel = mainPlotinfo.minorGridlayer.selectAll('.' + ax._id);else if (e.K === GRID_PATH.K) sel = mainPlotinfo.gridlayer.selectAll('.' + ax._id);else sel = mainPlotinfo[ax._id.charAt(0) + 'axislayer'];
sel.each(function () {
var w = d3.select(this);
if (e.L) w = w.selectAll(e.L);
w.each(function (d) {
var q = ax.l2p(isPeriodLabel ? getPosX(d) : d.x) + ax._offset;
var t = d3.select(this);
if (q < ax['_visibleLabelMax_' + anchorAx._id] && q > ax['_visibleLabelMin_' + anchorAx._id]) {
t.style('display', 'none'); // hidden
} else if (e.K === 'tick' && !idx) {
t.style('display', null); // visible
}
});
});
});
}
});
};
// make sure all labels are correctly positioned at their base angle
// the positionLabels call above is only for newly drawn labels.
// do this without waiting, using the last calculated angle to
// minimize flicker, then do it again when we know all labels are
// there, putting back the prescribed angle to check for overlaps.
positionLabels(tickLabels, prevAngle + 1 ? prevAngle : tickAngle);
function allLabelsReady() {
return labelsReady.length && Promise.all(labelsReady);
}
var autoangle = null;
function fixLabelOverlaps() {
positionLabels(tickLabels, tickAngle);
// check for auto-angling if x labels overlap
// don't auto-angle at all for log axes with
// base and digit format
if (vals.length && ax.autotickangles && (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) {
autoangle = ax.autotickangles[0];
var maxFontSize = 0;
var lbbArray = [];
var i;
var maxLines = 1;
tickLabels.each(function (d) {
maxFontSize = Math.max(maxFontSize, d.fontSize);
var x = ax.l2p(d.x);
var thisLabel = selectTickLabel(this);
var bb = Drawing.bBox(thisLabel.node());
maxLines = Math.max(maxLines, svgTextUtils.lineCount(thisLabel));
lbbArray.push({
// ignore about y, just deal with x overlaps
top: 0,
bottom: 10,
height: 10,
left: x - bb.width / 2,
// impose a 2px gap
right: x + bb.width / 2 + 2,
width: bb.width + 2
});
});
// autotickangles
// if there are dividers or ticks on boundaries, the labels will be in between and
// we need to prevent overlap with the next divider/tick. Else the labels will be on
// the ticks and we need to prevent overlap with the next label.
// TODO should secondary labels also fall into this fix-overlap regime?
var preventOverlapWithTick = (ax.tickson === 'boundaries' || ax.showdividers) && !opts.secondary;
var vLen = vals.length;
var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1);
var adjacent = preventOverlapWithTick ? tickSpacing / 2 : tickSpacing;
var opposite = preventOverlapWithTick ? ax.ticklen : maxFontSize * 1.25 * maxLines;
var hypotenuse = Math.sqrt(Math.pow(adjacent, 2) + Math.pow(opposite, 2));
var maxCos = adjacent / hypotenuse;
var autoTickAnglesRadians = ax.autotickangles.map(function (degrees) {
return degrees * Math.PI / 180;
});
var angleRadians = autoTickAnglesRadians.find(function (angle) {
return Math.abs(Math.cos(angle)) <= maxCos;
});
if (angleRadians === undefined) {
// no angle with smaller cosine than maxCos, just pick the angle with smallest cosine
angleRadians = autoTickAnglesRadians.reduce(function (currentMax, nextAngle) {
return Math.abs(Math.cos(currentMax)) < Math.abs(Math.cos(nextAngle)) ? currentMax : nextAngle;
}, autoTickAnglesRadians[0]);
}
var newAngle = angleRadians * (180 / Math.PI /* to degrees */);
if (preventOverlapWithTick) {
var gap = 2;
if (ax.ticks) gap += ax.tickwidth / 2;
for (i = 0; i < lbbArray.length; i++) {
var xbnd = vals[i].xbnd;
var lbb = lbbArray[i];
if (xbnd[0] !== null && lbb.left - ax.l2p(xbnd[0]) < gap || xbnd[1] !== null && ax.l2p(xbnd[1]) - lbb.right < gap) {
autoangle = newAngle;
break;
}
}
} else {
var ticklabelposition = ax.ticklabelposition || '';
var has = function (str) {
return ticklabelposition.indexOf(str) !== -1;
};
var isTop = has('top');
var isLeft = has('left');
var isRight = has('right');
var isBottom = has('bottom');
var isAligned = isBottom || isLeft || isTop || isRight;
var pad = !isAligned ? 0 : (ax.tickwidth || 0) + 2 * TEXTPAD;
for (i = 0; i < lbbArray.length - 1; i++) {
if (Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1], pad)) {
autoangle = newAngle;
break;
}
}
}
if (autoangle) {
positionLabels(tickLabels, autoangle);
}
}
}
if (ax._selections) {
ax._selections[cls] = tickLabels;
}
var seq = [allLabelsReady];
// N.B. during auto-margin redraws, if the axis fixed its label overlaps
// by rotating 90 degrees, do not attempt to re-fix its label overlaps
// as this can lead to infinite redraw loops!
if (ax.automargin && fullLayout._redrawFromAutoMarginCount && prevAngle === 90) {
autoangle = prevAngle;
seq.push(function () {
positionLabels(tickLabels, prevAngle);
});
} else {
seq.push(fixLabelOverlaps);
}
// save current tick angle for future redraws
if (ax._tickAngles) {
seq.push(function () {
ax._tickAngles[cls] = autoangle === null ? isNumeric(tickAngle) ? tickAngle : 0 : autoangle;
});
}
var computeTickLabelBoundingBoxes = function () {
var labelsMaxW = 0;
var labelsMaxH = 0;
tickLabels.each(function (d, i) {
var thisLabel = selectTickLabel(this);
var mathjaxGroup = thisLabel.select('.text-math-group');
if (mathjaxGroup.empty()) {
var bb;
if (ax._vals[i]) {
bb = ax._vals[i].bb || Drawing.bBox(thisLabel.node());
ax._vals[i].bb = bb;
}
labelsMaxW = Math.max(labelsMaxW, bb.width);
labelsMaxH = Math.max(labelsMaxH, bb.height);
}
});
return {
labelsMaxW: labelsMaxW,
labelsMaxH: labelsMaxH
};
};
var anchorAx = ax._anchorAxis;
if (anchorAx && (anchorAx.autorange || anchorAx.insiderange) && insideTicklabelposition(ax) && !isLinked(fullLayout, ax._id)) {
if (!fullLayout._insideTickLabelsUpdaterange) {
fullLayout._insideTickLabelsUpdaterange = {};
}
if (anchorAx.autorange) {
fullLayout._insideTickLabelsUpdaterange[anchorAx._name + '.autorange'] = anchorAx.autorange;
seq.push(computeTickLabelBoundingBoxes);
}
if (anchorAx.insiderange) {
var BBs = computeTickLabelBoundingBoxes();
var move = ax._id.charAt(0) === 'y' ? BBs.labelsMaxW : BBs.labelsMaxH;
move += 2 * TEXTPAD;
if (ax.ticklabelposition === 'inside') {
move += ax.ticklen || 0;
}
var sgn = ax.side === 'right' || ax.side === 'top' ? 1 : -1;
var index = sgn === 1 ? 1 : 0;
var otherIndex = sgn === 1 ? 0 : 1;
var newRange = [];
newRange[otherIndex] = anchorAx.range[otherIndex];
var anchorAxRange = anchorAx.range;
var p0 = anchorAx.r2p(anchorAxRange[index]);
var p1 = anchorAx.r2p(anchorAxRange[otherIndex]);
var _tempNewRange = fullLayout._insideTickLabelsUpdaterange[anchorAx._name + '.range'];
if (_tempNewRange) {
// case of having multiple anchored axes having insideticklabel
var q0 = anchorAx.r2p(_tempNewRange[index]);
var q1 = anchorAx.r2p(_tempNewRange[otherIndex]);
var dir = sgn * (ax._id.charAt(0) === 'y' ? 1 : -1);
if (dir * p0 < dir * q0) {
p0 = q0;
newRange[index] = anchorAxRange[index] = _tempNewRange[index];
}
if (dir * p1 > dir * q1) {
p1 = q1;
newRange[otherIndex] = anchorAxRange[otherIndex] = _tempNewRange[otherIndex];
}
}
var dist = Math.abs(p1 - p0);
if (dist - move > 0) {
dist -= move;
move *= 1 + move / dist;
} else {
move = 0;
}
if (ax._id.charAt(0) !== 'y') move = -move;
newRange[index] = anchorAx.p2r(anchorAx.r2p(anchorAxRange[index]) + sgn * move);
// handle partial ranges in insiderange
if (anchorAx.autorange === 'min' || anchorAx.autorange === 'max reversed') {
newRange[0] = null;
anchorAx._rangeInitial0 = undefined;
anchorAx._rangeInitial1 = undefined;
} else if (anchorAx.autorange === 'max' || anchorAx.autorange === 'min reversed') {
newRange[1] = null;
anchorAx._rangeInitial0 = undefined;
anchorAx._rangeInitial1 = undefined;
}
fullLayout._insideTickLabelsUpdaterange[anchorAx._name + '.range'] = newRange;
}
}
var done = Lib.syncOrAsync(seq);
if (done && done.then) gd._promises.push(done);
return done;
};
/**
* Draw axis dividers
*
* @param {DOM element} gd
* @param {object} ax (full) axis object
* - {string} _id
* - {string} showdividers
* - {number} dividerwidth
* - {string} dividercolor
* @param {object} opts
* - {array of object} vals (calcTicks output-like)
* - {d3 selection} layer
* - {fn} path
* - {fn} transFn
*/
function drawDividers(gd, ax, opts) {
var cls = ax._id + 'divider';
var vals = opts.vals;
var dividers = opts.layer.selectAll('path.' + cls).data(vals, tickDataFn);
dividers.exit().remove();
dividers.enter().insert('path', ':first-child').classed(cls, 1).classed('crisp', 1).call(Color.stroke, ax.dividercolor).style('stroke-width', Drawing.crispRound(gd, ax.dividerwidth, 1) + 'px');
dividers.attr('transform', opts.transFn).attr('d', opts.path);
}
/**
* Get axis position in px, that is the distance for the graph's
* top (left) edge for x (y) axes.
*
* @param {DOM element} gd
* @param {object} ax (full) axis object
* - {string} _id
* - {string} side
* if anchored:
* - {object} _anchorAxis
* Otherwise:
* - {number} position
* @return {number}
*/
axes.getPxPosition = function (gd, ax) {
var gs = gd._fullLayout._size;
var axLetter = ax._id.charAt(0);
var side = ax.side;
var anchorAxis;
if (ax.anchor !== 'free') {
anchorAxis = ax._anchorAxis;
} else if (axLetter === 'x') {
anchorAxis = {
_offset: gs.t + (1 - (ax.position || 0)) * gs.h,
_length: 0
};
} else if (axLetter === 'y') {
anchorAxis = {
_offset: gs.l + (ax.position || 0) * gs.w + ax._shift,
_length: 0
};
}
if (side === 'top' || side === 'left') {
return anchorAxis._offset;
} else if (side === 'bottom' || side === 'right') {
return anchorAxis._offset + anchorAxis._length;
}
};
/**
* Approximate axis title depth (w/o computing its bounding box)
*
* @param {object} ax (full) axis object
* - {string} title.text
* - {number} title.font.size
* - {number} title.standoff
* @return {number} (in px)
*/
function approxTitleDepth(ax) {
var fontSize = ax.title.font.size;
var extraLines = (ax.title.text.match(svgTextUtils.BR_TAG_ALL) || []).length;
if (ax.title.hasOwnProperty('standoff')) {
return fontSize * (CAP_SHIFT + extraLines * LINE_SPACING);
} else {
return extraLines ? fontSize * (extraLines + 1) * LINE_SPACING : fontSize;
}
}
/**
* Draw axis title, compute default standoff if necessary
*
* @param {DOM element} gd
* @param {object} ax (full) axis object
* - {string} _id
* - {string} _name
* - {string} side
* - {number} title.font.size
* - {object} _selections
*
* - {number} _depth
* - {number} title.standoff
* OR
* - {number} linewidth
* - {boolean} showticklabels
*/
function drawTitle(gd, ax) {
var fullLayout = gd._fullLayout;
var axId = ax._id;
var axLetter = axId.charAt(0);
var fontSize = ax.title.font.size;
var titleStandoff;
var extraLines = (ax.title.text.match(svgTextUtils.BR_TAG_ALL) || []).length;
if (ax.title.hasOwnProperty('standoff')) {
// With ax._depth the initial drawing baseline is at the outer axis border (where the
// ticklabels are drawn). Since the title text will be drawn above the baseline,
// bottom/right axes must be shifted by 1 text line to draw below ticklabels instead of on
// top of them, whereas for top/left axes, the first line would be drawn
// before the ticklabels, but we need an offset for the descender portion of the first line
// and all subsequent lines.
if (ax.side === 'bottom' || ax.side === 'right') {
titleStandoff = ax._depth + ax.title.standoff + fontSize * CAP_SHIFT;
} else if (ax.side === 'top' || ax.side === 'left') {
titleStandoff = ax._depth + ax.title.standoff + fontSize * (MID_SHIFT + extraLines * LINE_SPACING);
}
} else {
var isInside = insideTicklabelposition(ax);
if (ax.type === 'multicategory') {
titleStandoff = ax._depth;
} else {
var offsetBase = 1.5 * fontSize;
if (isInside) {
offsetBase = 0.5 * fontSize;
if (ax.ticks === 'outside') {
offsetBase += ax.ticklen;
}
}
titleStandoff = 10 + offsetBase + (ax.linewidth ? ax.linewidth - 1 : 0);
}
if (!isInside) {
if (axLetter === 'x') {
titleStandoff += ax.side === 'top' ? fontSize * (ax.showticklabels ? 1 : 0) : fontSize * (ax.showticklabels ? 1.5 : 0.5);
} else {
titleStandoff += ax.side === 'right' ? fontSize * (ax.showticklabels ? 1 : 0.5) : fontSize * (ax.showticklabels ? 0.5 : 0);
}
}
}
var pos = axes.getPxPosition(gd, ax);
var transform, x, y;
if (axLetter === 'x') {
x = ax._offset + ax._length / 2;
y = ax.side === 'top' ? pos - titleStandoff : pos + titleStandoff;
} else {
y = ax._offset + ax._length / 2;
x = ax.side === 'right' ? pos + titleStandoff : pos - titleStandoff;
transform = {
rotate: '-90',
offset: 0
};
}
var avoid;
if (ax.type !== 'multicategory') {
var tickLabels = ax._selections[ax._id + 'tick'];
avoid = {
selection: tickLabels,
side: ax.side
};
if (tickLabels && tickLabels.node() && tickLabels.node().parentNode) {
var translation = Drawing.getTranslate(tickLabels.node().parentNode);
avoid.offsetLeft = translation.x;
avoid.offsetTop = translation.y;
}
if (ax.title.hasOwnProperty('standoff')) {
avoid.pad = 0;
}
}
ax._titleStandoff = titleStandoff;
return Titles.draw(gd, axId + 'title', {
propContainer: ax,
propName: ax._name + '.title.text',
placeholder: fullLayout._dfltTitle[axLetter],
avoid: avoid,
transform: transform,
attributes: {
x: x,
y: y,
'text-anchor': 'middle'
}
});
}
axes.shouldShowZeroLine = function (gd, ax, counterAxis) {
var rng = Lib.simpleMap(ax.range, ax.r2l);
return rng[0] * rng[1] <= 0 && ax.zeroline && (ax.type === 'linear' || ax.type === '-') && !(ax.rangebreaks && ax.maskBreaks(0) === BADNUM) && (clipEnds(ax, 0) || !anyCounterAxLineAtZero(gd, ax, counterAxis, rng) || hasBarsOrFill(gd, ax));
};
axes.clipEnds = function (ax, vals) {
return vals.filter(function (d) {
return clipEnds(ax, d.x);
});
};
function clipEnds(ax, l) {
var p = ax.l2p(l);
return p > 1 && p < ax._length - 1;
}
function anyCounterAxLineAtZero(gd, ax, counterAxis, rng) {
var mainCounterAxis = counterAxis._mainAxis;
if (!mainCounterAxis) return;
var fullLayout = gd._fullLayout;
var axLetter = ax._id.charAt(0);
var counterLetter = axes.counterLetter(ax._id);
var zeroPosition = ax._offset + (Math.abs(rng[0]) < Math.abs(rng[1]) === (axLetter === 'x') ? 0 : ax._length);
function lineNearZero(ax2) {
if (!ax2.showline || !ax2.linewidth) return false;
var tolerance = Math.max((ax2.linewidth + ax.zerolinewidth) / 2, 1);
function closeEnough(pos2) {
return typeof pos2 === 'number' && Math.abs(pos2 - zeroPosition) < tolerance;
}
if (closeEnough(ax2._mainLinePosition) || closeEnough(ax2._mainMirrorPosition)) {
return true;
}
var linePositions = ax2._linepositions || {};
for (var k in linePositions) {
if (closeEnough(linePositions[k][0]) || closeEnough(linePositions[k][1])) {
return true;
}
}
}
var plotinfo = fullLayout._plots[counterAxis._mainSubplot];
if (!(plotinfo.mainplotinfo || plotinfo).overlays.length) {
return lineNearZero(counterAxis, zeroPosition);
}
var counterLetterAxes = axes.list(gd, counterLetter);
for (var i = 0; i < counterLetterAxes.length; i++) {
var counterAxis2 = counterLetterAxes[i];
if (counterAxis2._mainAxis === mainCounterAxis && lineNearZero(counterAxis2, zeroPosition)) {
return true;
}
}
}
function hasBarsOrFill(gd, ax) {
var fullData = gd._fullData;
var subplot = ax._mainSubplot;
var axLetter = ax._id.charAt(0);
for (var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (trace.visible === true && trace.xaxis + trace.yaxis === subplot) {
if (Registry.traceIs(trace, 'bar-like') && trace.orientation === {
x: 'h',
y: 'v'
}[axLetter]) return true;
if (trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter) return true;
}
}
return false;
}
function selectTickLabel(gTick) {
var s = d3.select(gTick);
var mj = s.select('.text-math-group');
return mj.empty() ? s.select('text') : mj;
}
/**
* Find all margin pushers for 2D axes and reserve them for later use
* Both label and rangeslider automargin calculations happen later so
* we need to explicitly allow their ids in order to not delete them.
*
* TODO: can we pull the actual automargin calls forward to avoid this hack?
* We're probably also doing multiple redraws in this case, would be faster
* if we can just do the whole calculation ahead of time and draw once.
*/
axes.allowAutoMargin = function (gd) {
var axList = axes.list(gd, '', true);
for (var i = 0; i < axList.length; i++) {
var ax = axList[i];
if (ax.automargin) {
Plots.allowAutoMargin(gd, axAutoMarginID(ax));
if (ax.mirror) {
Plots.allowAutoMargin(gd, axMirrorAutoMarginID(ax));
}
}
if (Registry.getComponentMethod('rangeslider', 'isVisible')(ax)) {
Plots.allowAutoMargin(gd, rangeSliderAutoMarginID(ax));
}
}
};
function axAutoMarginID(ax) {
return ax._id + '.automargin';
}
function axMirrorAutoMarginID(ax) {
return axAutoMarginID(ax) + '.mirror';
}
function rangeSliderAutoMarginID(ax) {
return ax._id + '.rangeslider';
}
// swap all the presentation attributes of the axes showing these traces
axes.swap = function (gd, traces) {
var axGroups = makeAxisGroups(gd, traces);
for (var i = 0; i < axGroups.length; i++) {
swapAxisGroup(gd, axGroups[i].x, axGroups[i].y);
}
};
function makeAxisGroups(gd, traces) {
var groups = [];
var i, j;
for (i = 0; i < traces.length; i++) {
var groupsi = [];
var xi = gd._fullData[traces[i]].xaxis;
var yi = gd._fullData[traces[i]].yaxis;
if (!xi || !yi) continue; // not a 2D cartesian trace?
for (j = 0; j < groups.length; j++) {
if (groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) {
groupsi.push(j);
}
}
if (!groupsi.length) {
groups.push({
x: [xi],
y: [yi]
});
continue;
}
var group0 = groups[groupsi[0]];
var groupj;
if (groupsi.length > 1) {
for (j = 1; j < groupsi.length; j++) {
groupj = groups[groupsi[j]];
mergeAxisGroups(group0.x, groupj.x);
mergeAxisGroups(group0.y, groupj.y);
}
}
mergeAxisGroups(group0.x, [xi]);
mergeAxisGroups(group0.y, [yi]);
}
return groups;
}
function mergeAxisGroups(intoSet, fromSet) {
for (var i = 0; i < fromSet.length; i++) {
if (intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]);
}
}
function swapAxisGroup(gd, xIds, yIds) {
var xFullAxes = [];
var yFullAxes = [];
var layout = gd.layout;
var i, j;
for (i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i]));
for (i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i]));
var allAxKeys = Object.keys(axAttrs);
var noSwapAttrs = ['anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle', 'editType'];
var numericTypes = ['linear', 'log'];
for (i = 0; i < allAxKeys.length; i++) {
var keyi = allAxKeys[i];
var xVal = xFullAxes[0][keyi];
var yVal = yFullAxes[0][keyi];
var allEqual = true;
var coerceLinearX = false;
var coerceLinearY = false;
if (keyi.charAt(0) === '_' || typeof xVal === 'function' || noSwapAttrs.indexOf(keyi) !== -1) {
continue;
}
for (j = 1; j < xFullAxes.length && allEqual; j++) {
var xVali = xFullAxes[j][keyi];
if (keyi === 'type' && numericTypes.indexOf(xVal) !== -1 && numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) {
// type is special - if we find a mixture of linear and log,
// coerce them all to linear on flipping
coerceLinearX = true;
} else if (xVali !== xVal) allEqual = false;
}
for (j = 1; j < yFullAxes.length && allEqual; j++) {
var yVali = yFullAxes[j][keyi];
if (keyi === 'type' && numericTypes.indexOf(yVal) !== -1 && numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) {
// type is special - if we find a mixture of linear and log,
// coerce them all to linear on flipping
coerceLinearY = true;
} else if (yFullAxes[j][keyi] !== yVal) allEqual = false;
}
if (allEqual) {
if (coerceLinearX) layout[xFullAxes[0]._name].type = 'linear';
if (coerceLinearY) layout[yFullAxes[0]._name].type = 'linear';
swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes, gd._fullLayout._dfltTitle);
}
}
// now swap x&y for any annotations anchored to these x & y
for (i = 0; i < gd._fullLayout.annotations.length; i++) {
var ann = gd._fullLayout.annotations[i];
if (xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) {
Lib.swapAttrs(layout.annotations[i], ['?']);
}
}
}
function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) {
// in case the value is the default for either axis,
// look at the first axis in each list and see if
// this key's value is undefined
var np = Lib.nestedProperty;
var xVal = np(layout[xFullAxes[0]._name], key).get();
var yVal = np(layout[yFullAxes[0]._name], key).get();
var i;
if (key === 'title') {
// special handling of placeholder titles
if (xVal && xVal.text === dfltTitle.x) {
xVal.text = dfltTitle.y;
}
if (yVal && yVal.text === dfltTitle.y) {
yVal.text = dfltTitle.x;
}
}
for (i = 0; i < xFullAxes.length; i++) {
np(layout, xFullAxes[i]._name + '.' + key).set(yVal);
}
for (i = 0; i < yFullAxes.length; i++) {
np(layout, yFullAxes[i]._name + '.' + key).set(xVal);
}
}
function isAngular(ax) {
return ax._id === 'angularaxis';
}
function moveOutsideBreak(v, ax) {
var len = ax._rangebreaks.length;
for (var k = 0; k < len; k++) {
var brk = ax._rangebreaks[k];
if (v >= brk.min && v < brk.max) {
return brk.max;
}
}
return v;
}
function insideTicklabelposition(ax) {
return (ax.ticklabelposition || '').indexOf('inside') !== -1;
}
function hideCounterAxisInsideTickLabels(ax, opts) {
if (insideTicklabelposition(ax._anchorAxis || {})) {
if (ax._hideCounterAxisInsideTickLabels) {
ax._hideCounterAxisInsideTickLabels(opts);
}
}
}
function incrementShift(ax, shiftVal, axShifts, normalize) {
// Need to set 'overlay' for anchored axis
var overlay = ax.anchor !== 'free' && (ax.overlaying === undefined || ax.overlaying === false) ? ax._id : ax.overlaying;
var shiftValAdj;
if (normalize) {
shiftValAdj = ax.side === 'right' ? shiftVal : -shiftVal;
} else {
shiftValAdj = shiftVal;
}
if (!(overlay in axShifts)) {
axShifts[overlay] = {};
}
if (!(ax.side in axShifts[overlay])) {
axShifts[overlay][ax.side] = 0;
}
axShifts[overlay][ax.side] += shiftValAdj;
}
function setShiftVal(ax, axShifts) {
return ax.autoshift ? axShifts[ax.overlaying][ax.side] : ax.shift || 0;
}
/**
* Checks if the given period is at least the period described by the tickformat or larger. If that
* is the case, they are compatible, because then the tickformat can be used to describe the period.
* E.g. it doesn't make sense to put a year label on a period spanning only a month.
* @param {number} period in ms
* @param {string} tickformat
* @returns {boolean}
*/
function periodCompatibleWithTickformat(period, tickformat) {
return /%f/.test(tickformat) ? period >= ONEMICROSEC : /%L/.test(tickformat) ? period >= ONEMILLI : /%[SX]/.test(tickformat) ? period >= ONESEC : /%M/.test(tickformat) ? period >= ONEMIN : /%[HI]/.test(tickformat) ? period >= ONEHOUR : /%p/.test(tickformat) ? period >= HALFDAY : /%[Aadejuwx]/.test(tickformat) ? period >= ONEDAY : /%[UVW]/.test(tickformat) ? period >= ONEWEEK : /%[Bbm]/.test(tickformat) ? period >= ONEMINMONTH : /%[q]/.test(tickformat) ? period >= ONEMINQUARTER : /%[Yy]/.test(tickformat) ? period >= ONEMINYEAR : true;
}
/***/ }),
/***/ 52976:
/***/ (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);
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var isDateTime = Lib.isDateTime;
var cleanNumber = Lib.cleanNumber;
var round = Math.round;
module.exports = function autoType(array, calendar, opts) {
var a = array;
var noMultiCategory = opts.noMultiCategory;
if (isArrayOrTypedArray(a) && !a.length) return '-';
if (!noMultiCategory && multiCategory(a)) return 'multicategory';
if (noMultiCategory && Array.isArray(a[0])) {
// no need to flat typed arrays here
var b = [];
for (var i = 0; i < a.length; i++) {
if (isArrayOrTypedArray(a[i])) {
for (var j = 0; j < a[i].length; j++) {
b.push(a[i][j]);
}
}
}
a = b;
}
if (moreDates(a, calendar)) return 'date';
var convertNumeric = opts.autotypenumbers !== 'strict'; // compare against strict, just in case autotypenumbers was not provided in opts
if (category(a, convertNumeric)) return 'category';
if (linearOK(a, convertNumeric)) return 'linear';
return '-';
};
function hasTypeNumber(v, convertNumeric) {
return convertNumeric ? isNumeric(v) : typeof v === 'number';
}
// is there at least one number in array? If not, we should leave
// ax.type empty so it can be autoset later
function linearOK(a, convertNumeric) {
var len = a.length;
for (var i = 0; i < len; i++) {
if (hasTypeNumber(a[i], convertNumeric)) return true;
}
return false;
}
// does the array a have mostly dates rather than numbers?
// note: some values can be neither (such as blanks, text)
// 2- or 4-digit integers can be both, so require twice as many
// dates as non-dates, to exclude cases with mostly 2 & 4 digit
// numbers and a few dates
// as with categories, consider DISTINCT values only.
function moreDates(a, calendar) {
var len = a.length;
var inc = getIncrement(len);
var dats = 0;
var nums = 0;
var seen = {};
for (var f = 0; f < len; f += inc) {
var i = round(f);
var ai = a[i];
var stri = String(ai);
if (seen[stri]) continue;
seen[stri] = 1;
if (isDateTime(ai, calendar)) dats++;
if (isNumeric(ai)) nums++;
}
return dats > nums * 2;
}
// return increment to test at most 1000 points, evenly spaced
function getIncrement(len) {
return Math.max(1, (len - 1) / 1000);
}
// are the (x,y)-values in gd.data mostly text?
// require twice as many DISTINCT categories as distinct numbers
function category(a, convertNumeric) {
var len = a.length;
var inc = getIncrement(len);
var nums = 0;
var cats = 0;
var seen = {};
for (var f = 0; f < len; f += inc) {
var i = round(f);
var ai = a[i];
var stri = String(ai);
if (seen[stri]) continue;
seen[stri] = 1;
var t = typeof ai;
if (t === 'boolean') cats++;else if (convertNumeric ? cleanNumber(ai) !== BADNUM : t === 'number') nums++;else if (t === 'string') cats++;
}
return cats > nums * 2;
}
// very-loose requirements for multicategory,
// trace modules that should never auto-type to multicategory
// should be declared with 'noMultiCategory'
function multiCategory(a) {
return isArrayOrTypedArray(a[0]) && isArrayOrTypedArray(a[1]);
}
/***/ }),
/***/ 28336:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
var handleArrayContainerDefaults = __webpack_require__(51272);
var layoutAttributes = __webpack_require__(94724);
var handleTickValueDefaults = __webpack_require__(26332);
var handleTickMarkDefaults = __webpack_require__(25404);
var handleTickLabelDefaults = __webpack_require__(95936);
var handlePrefixSuffixDefaults = __webpack_require__(42568);
var handleCategoryOrderDefaults = __webpack_require__(22416);
var handleLineGridDefaults = __webpack_require__(42136);
var handleRangeDefaults = __webpack_require__(96312);
var setConvert = __webpack_require__(78344);
var DAY_OF_WEEK = (__webpack_require__(33816).WEEKDAY_PATTERN);
var HOUR = (__webpack_require__(33816).HOUR_PATTERN);
/**
* options: object containing:
*
* letter: 'x' or 'y'
* title: name of the axis (ie 'Colorbar') to go in default title
* font: the default font to inherit
* outerTicks: boolean, should ticks default to outside?
* showGrid: boolean, should gridlines be shown by default?
* noHover: boolean, this axis doesn't support hover effects?
* noTickson: boolean, this axis doesn't support 'tickson'
* data: the plot data, used to manage categories
* bgColor: the plot background color, to calculate default gridline colors
* calendar:
* splomStash:
* visibleDflt: boolean
* reverseDflt: boolean
* automargin: boolean
*/
module.exports = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) {
var letter = options.letter;
var font = options.font || {};
var splomStash = options.splomStash || {};
var visible = coerce('visible', !options.visibleDflt);
var axTemplate = containerOut._template || {};
var axType = containerOut.type || axTemplate.type || '-';
var ticklabelmode;
if (axType === 'date') {
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
if (!options.noTicklabelmode) {
ticklabelmode = coerce('ticklabelmode');
}
}
if (!options.noTicklabelindex && (axType === 'date' || axType === 'linear')) {
coerce('ticklabelindex');
}
var ticklabelposition = '';
if (!options.noTicklabelposition || axType === 'multicategory') {
ticklabelposition = Lib.coerce(containerIn, containerOut, {
ticklabelposition: {
valType: 'enumerated',
dflt: 'outside',
values: ticklabelmode === 'period' ? ['outside', 'inside'] : letter === 'x' ? ['outside', 'inside', 'outside left', 'inside left', 'outside right', 'inside right'] : ['outside', 'inside', 'outside top', 'inside top', 'outside bottom', 'inside bottom']
}
}, 'ticklabelposition');
}
if (!options.noTicklabeloverflow) {
coerce('ticklabeloverflow', ticklabelposition.indexOf('inside') !== -1 ? 'hide past domain' : axType === 'category' || axType === 'multicategory' ? 'allow' : 'hide past div');
}
setConvert(containerOut, layoutOut);
handleRangeDefaults(containerIn, containerOut, coerce, options);
handleCategoryOrderDefaults(containerIn, containerOut, coerce, options);
if (axType !== 'category' && !options.noHover) coerce('hoverformat');
var dfltColor = coerce('color');
// if axis.color was provided, use it for fonts too; otherwise,
// inherit from global font color in case that was provided.
// Compare to dflt rather than to containerIn, so we can provide color via
// template too.
var dfltFontColor = dfltColor !== layoutAttributes.color.dflt ? dfltColor : font.color;
// try to get default title from splom trace, fallback to graph-wide value
var dfltTitle = splomStash.label || layoutOut._dfltTitle[letter];
handlePrefixSuffixDefaults(containerIn, containerOut, coerce, axType, options);
if (!visible) return containerOut;
coerce('title.text', dfltTitle);
Lib.coerceFont(coerce, 'title.font', font, {
overrideDflt: {
size: Lib.bigFont(font.size),
color: dfltFontColor
}
});
// major ticks
handleTickValueDefaults(containerIn, containerOut, coerce, axType);
var hasMinor = options.hasMinor;
if (hasMinor) {
// minor ticks
Template.newContainer(containerOut, 'minor');
handleTickValueDefaults(containerIn, containerOut, coerce, axType, {
isMinor: true
});
}
handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
// major and minor ticks
handleTickMarkDefaults(containerIn, containerOut, coerce, options);
if (hasMinor) {
var keepIsMinor = options.isMinor;
options.isMinor = true;
handleTickMarkDefaults(containerIn, containerOut, coerce, options);
options.isMinor = keepIsMinor;
}
handleLineGridDefaults(containerIn, containerOut, coerce, {
dfltColor: dfltColor,
bgColor: options.bgColor,
showGrid: options.showGrid,
hasMinor: hasMinor,
attributes: layoutAttributes
});
// delete minor when no minor ticks or gridlines
if (hasMinor && !containerOut.minor.ticks && !containerOut.minor.showgrid) {
delete containerOut.minor;
}
// mirror
if (containerOut.showline || containerOut.ticks) coerce('mirror');
var isMultiCategory = axType === 'multicategory';
if (!options.noTickson && (axType === 'category' || isMultiCategory) && (containerOut.ticks || containerOut.showgrid)) {
var ticksonDflt;
if (isMultiCategory) ticksonDflt = 'boundaries';
var tickson = coerce('tickson', ticksonDflt);
if (tickson === 'boundaries') {
delete containerOut.ticklabelposition;
}
}
if (isMultiCategory) {
var showDividers = coerce('showdividers');
if (showDividers) {
coerce('dividercolor');
coerce('dividerwidth');
}
}
if (axType === 'date') {
handleArrayContainerDefaults(containerIn, containerOut, {
name: 'rangebreaks',
inclusionAttr: 'enabled',
handleItemDefaults: rangebreaksDefaults
});
if (!containerOut.rangebreaks.length) {
delete containerOut.rangebreaks;
} else {
for (var k = 0; k < containerOut.rangebreaks.length; k++) {
if (containerOut.rangebreaks[k].pattern === DAY_OF_WEEK) {
containerOut._hasDayOfWeekBreaks = true;
break;
}
}
setConvert(containerOut, layoutOut);
if (layoutOut._has('scattergl') || layoutOut._has('splom')) {
for (var i = 0; i < options.data.length; i++) {
var trace = options.data[i];
if (trace.type === 'scattergl' || trace.type === 'splom') {
trace.visible = false;
Lib.warn(trace.type + ' traces do not work on axes with rangebreaks.' + ' Setting trace ' + trace.index + ' to `visible: false`.');
}
}
}
}
}
return containerOut;
};
function rangebreaksDefaults(itemIn, itemOut, containerOut) {
function coerce(attr, dflt) {
return Lib.coerce(itemIn, itemOut, layoutAttributes.rangebreaks, attr, dflt);
}
var enabled = coerce('enabled');
if (enabled) {
var bnds = coerce('bounds');
if (bnds && bnds.length >= 2) {
var dfltPattern = '';
var i, q;
if (bnds.length === 2) {
for (i = 0; i < 2; i++) {
q = indexOfDay(bnds[i]);
if (q) {
dfltPattern = DAY_OF_WEEK;
break;
}
}
}
var pattern = coerce('pattern', dfltPattern);
if (pattern === DAY_OF_WEEK) {
for (i = 0; i < 2; i++) {
q = indexOfDay(bnds[i]);
if (q) {
// convert to integers i.e 'Sunday' --> 0
itemOut.bounds[i] = bnds[i] = q - 1;
}
}
}
if (pattern) {
// ensure types and ranges
for (i = 0; i < 2; i++) {
q = bnds[i];
switch (pattern) {
case DAY_OF_WEEK:
if (!isNumeric(q)) {
itemOut.enabled = false;
return;
}
q = +q;
if (q !== Math.floor(q) ||
// don't accept fractional days for mow
q < 0 || q >= 7) {
itemOut.enabled = false;
return;
}
// use number
itemOut.bounds[i] = bnds[i] = q;
break;
case HOUR:
if (!isNumeric(q)) {
itemOut.enabled = false;
return;
}
q = +q;
if (q < 0 || q > 24) {
// accept 24
itemOut.enabled = false;
return;
}
// use number
itemOut.bounds[i] = bnds[i] = q;
break;
}
}
}
if (containerOut.autorange === false) {
var rng = containerOut.range;
// if bounds are bigger than the (set) range, disable break
if (rng[0] < rng[1]) {
if (bnds[0] < rng[0] && bnds[1] > rng[1]) {
itemOut.enabled = false;
return;
}
} else if (bnds[0] > rng[0] && bnds[1] < rng[1]) {
itemOut.enabled = false;
return;
}
}
} else {
var values = coerce('values');
if (values && values.length) {
coerce('dvalue');
} else {
itemOut.enabled = false;
return;
}
}
}
}
// these numbers are one more than what bounds would be mapped to
var dayStrToNum = {
sun: 1,
mon: 2,
tue: 3,
wed: 4,
thu: 5,
fri: 6,
sat: 7
};
function indexOfDay(v) {
if (typeof v !== 'string') return;
return dayStrToNum[v.substr(0, 3).toLowerCase()];
}
/***/ }),
/***/ 29736:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var docs = __webpack_require__(26880);
var FORMAT_LINK = docs.FORMAT_LINK;
var DATE_FORMAT_LINK = docs.DATE_FORMAT_LINK;
function axisHoverFormat(x, noDates) {
return {
valType: 'string',
dflt: '',
editType: 'none',
description: (noDates ? descriptionOnlyNumbers : descriptionWithDates)('hover text', x) + ['By default the values are formatted using ' + (noDates ? 'generic number format' : '`' + x + 'axis.hoverformat`') + '.'].join(' ')
};
}
function descriptionOnlyNumbers(label, x) {
return ['Sets the ' + label + ' formatting rule' + (x ? 'for `' + x + '` ' : ''), 'using d3 formatting mini-languages', 'which are very similar to those in Python. For numbers, see: ' + FORMAT_LINK + '.'].join(' ');
}
function descriptionWithDates(label, x) {
return descriptionOnlyNumbers(label, x) + [' And for dates see: ' + DATE_FORMAT_LINK + '.', 'We add two items to d3\'s date formatter:', '*%h* for half of the year as a decimal number as well as', '*%{n}f* for fractional seconds', 'with n digits. For example, *2016-10-13 09:15:23.456* with tickformat', '*%H~%M~%S.%2f* would display *09~15~23.46*'].join(' ');
}
module.exports = {
axisHoverFormat: axisHoverFormat,
descriptionOnlyNumbers: descriptionOnlyNumbers,
descriptionWithDates: descriptionWithDates
};
/***/ }),
/***/ 79811:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var constants = __webpack_require__(33816);
// convert between axis names (xaxis, xaxis2, etc, elements of gd.layout)
// and axis id's (x, x2, etc). Would probably have ditched 'xaxis'
// completely in favor of just 'x' if it weren't ingrained in the API etc.
exports.id2name = function id2name(id) {
if (typeof id !== 'string' || !id.match(constants.AX_ID_PATTERN)) return;
var axNum = id.split(' ')[0].substr(1);
if (axNum === '1') axNum = '';
return id.charAt(0) + 'axis' + axNum;
};
exports.name2id = function name2id(name) {
if (!name.match(constants.AX_NAME_PATTERN)) return;
var axNum = name.substr(5);
if (axNum === '1') axNum = '';
return name.charAt(0) + axNum;
};
/*
* Cleans up the number of an axis, e.g., 'x002'->'x2', 'x0'->'x', 'x1' -> 'x',
* etc.
* If domainId is true, then id could be a domain reference and if it is, the
* ' domain' part is kept at the end of the axis ID string.
*/
exports.cleanId = function cleanId(id, axLetter, domainId) {
var domainTest = /( domain)$/.test(id);
if (typeof id !== 'string' || !id.match(constants.AX_ID_PATTERN)) return;
if (axLetter && id.charAt(0) !== axLetter) return;
if (domainTest && !domainId) return;
var axNum = id.split(' ')[0].substr(1).replace(/^0+/, '');
if (axNum === '1') axNum = '';
return id.charAt(0) + axNum + (domainTest && domainId ? ' domain' : '');
};
// get all axis objects, as restricted in listNames
exports.list = function (gd, axLetter, only2d) {
var fullLayout = gd._fullLayout;
if (!fullLayout) return [];
var idList = exports.listIds(gd, axLetter);
var out = new Array(idList.length);
var i;
for (i = 0; i < idList.length; i++) {
var idi = idList[i];
out[i] = fullLayout[idi.charAt(0) + 'axis' + idi.substr(1)];
}
if (!only2d) {
var sceneIds3D = fullLayout._subplots.gl3d || [];
for (i = 0; i < sceneIds3D.length; i++) {
var scene = fullLayout[sceneIds3D[i]];
if (axLetter) out.push(scene[axLetter + 'axis']);else out.push(scene.xaxis, scene.yaxis, scene.zaxis);
}
}
return out;
};
// get all axis ids, optionally restricted by letter
// this only makes sense for 2d axes
exports.listIds = function (gd, axLetter) {
var fullLayout = gd._fullLayout;
if (!fullLayout) return [];
var subplotLists = fullLayout._subplots;
if (axLetter) return subplotLists[axLetter + 'axis'];
return subplotLists.xaxis.concat(subplotLists.yaxis);
};
// get an axis object from its id 'x','x2' etc
// optionally, id can be a subplot (ie 'x2y3') and type gets x or y from it
exports.getFromId = function (gd, id, type) {
var fullLayout = gd._fullLayout;
// remove "domain" suffix
id = id === undefined || typeof id !== 'string' ? id : id.replace(' domain', '');
if (type === 'x') id = id.replace(/y[0-9]*/, '');else if (type === 'y') id = id.replace(/x[0-9]*/, '');
return fullLayout[exports.id2name(id)];
};
// get an axis object of specified type from the containing trace
exports.getFromTrace = function (gd, fullTrace, type) {
var fullLayout = gd._fullLayout;
var ax = null;
if (Registry.traceIs(fullTrace, 'gl3d')) {
var scene = fullTrace.scene;
if (scene.substr(0, 5) === 'scene') {
ax = fullLayout[scene][type + 'axis'];
}
} else {
ax = exports.getFromId(gd, fullTrace[type + 'axis'] || type);
}
return ax;
};
// sort x, x2, x10, y, y2, y10...
exports.idSort = function (id1, id2) {
var letter1 = id1.charAt(0);
var letter2 = id2.charAt(0);
if (letter1 !== letter2) return letter1 > letter2 ? 1 : -1;
return +(id1.substr(1) || 1) - +(id2.substr(1) || 1);
};
/*
* An axis reference (e.g., the contents at the 'xref' key of an object) might
* have extra information appended. Extract the axis ID only.
*
* ar: the axis reference string
*
*/
exports.ref2id = function (ar) {
// This assumes ar has been coerced via coerceRef, and uses the shortcut of
// checking if the first letter matches [xyz] to determine if it should
// return the axis ID. Otherwise it returns false.
return /^[xyz]/.test(ar) ? ar.split(' ')[0] : false;
};
function isFound(axId, list) {
if (list && list.length) {
for (var i = 0; i < list.length; i++) {
if (list[i][axId]) return true;
}
}
return false;
}
exports.isLinked = function (fullLayout, axId) {
return isFound(axId, fullLayout._axisMatchGroups) || isFound(axId, fullLayout._axisConstraintGroups);
};
/***/ }),
/***/ 22416:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isTypedArraySpec = (__webpack_require__(38116).isTypedArraySpec);
function findCategories(ax, opts) {
var dataAttr = opts.dataAttr || ax._id.charAt(0);
var lookup = {};
var axData;
var i, j;
if (opts.axData) {
// non-x/y case
axData = opts.axData;
} else {
// x/y case
axData = [];
for (i = 0; i < opts.data.length; i++) {
var trace = opts.data[i];
if (trace[dataAttr + 'axis'] === ax._id) {
axData.push(trace);
}
}
}
for (i = 0; i < axData.length; i++) {
var vals = axData[i][dataAttr];
for (j = 0; j < vals.length; j++) {
var v = vals[j];
if (v !== null && v !== undefined) {
lookup[v] = 1;
}
}
}
return Object.keys(lookup);
}
/**
* Fills in category* default and initial categories.
*
* @param {object} containerIn : input axis object
* @param {object} containerOut : full axis object
* @param {function} coerce : Lib.coerce fn wrapper
* @param {object} opts :
* - data {array} : (full) data trace
* OR
* - axData {array} : (full) data associated with axis being coerced here
* - dataAttr {string} : attribute name corresponding to coordinate array
*/
module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) {
if (containerOut.type !== 'category') return;
var arrayIn = containerIn.categoryarray;
var isValidArray = Array.isArray(arrayIn) && arrayIn.length > 0 || isTypedArraySpec(arrayIn);
// override default 'categoryorder' value when non-empty array is supplied
var orderDefault;
if (isValidArray) orderDefault = 'array';
var order = coerce('categoryorder', orderDefault);
var array;
// coerce 'categoryarray' only in array order case
if (order === 'array') {
array = coerce('categoryarray');
}
// cannot set 'categoryorder' to 'array' with an invalid 'categoryarray'
if (!isValidArray && order === 'array') {
order = containerOut.categoryorder = 'trace';
}
// set up things for makeCalcdata
if (order === 'trace') {
containerOut._initialCategories = [];
} else if (order === 'array') {
containerOut._initialCategories = array.slice();
} else {
array = findCategories(containerOut, opts).sort();
if (order === 'category ascending') {
containerOut._initialCategories = array;
} else if (order === 'category descending') {
containerOut._initialCategories = array.reverse();
}
}
};
/***/ }),
/***/ 98728:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var constants = __webpack_require__(39032);
var ONEDAY = constants.ONEDAY;
var ONEWEEK = constants.ONEWEEK;
/**
* Return a validated dtick value for this axis
*
* @param {any} dtick: the candidate dtick. valid values are numbers and strings,
* and further constrained depending on the axis type.
* @param {string} axType: the axis type
*/
exports.dtick = function (dtick, axType) {
var isLog = axType === 'log';
var isDate = axType === 'date';
var isCat = axType === 'category';
var dtickDflt = isDate ? ONEDAY : 1;
if (!dtick) return dtickDflt;
if (isNumeric(dtick)) {
dtick = Number(dtick);
if (dtick <= 0) return dtickDflt;
if (isCat) {
// category dtick must be positive integers
return Math.max(1, Math.round(dtick));
}
if (isDate) {
// date dtick must be at least 0.1ms (our current precision)
return Math.max(0.1, dtick);
}
return dtick;
}
if (typeof dtick !== 'string' || !(isDate || isLog)) {
return dtickDflt;
}
var prefix = dtick.charAt(0);
var dtickNum = dtick.substr(1);
dtickNum = isNumeric(dtickNum) ? Number(dtickNum) : 0;
if (dtickNum <= 0 || !(
// "M" gives ticks every (integer) n months
isDate && prefix === 'M' && dtickNum === Math.round(dtickNum) ||
// "L" gives ticks linearly spaced in data (not in position) every (float) f
isLog && prefix === 'L' ||
// "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5
isLog && prefix === 'D' && (dtickNum === 1 || dtickNum === 2))) {
return dtickDflt;
}
return dtick;
};
/**
* Return a validated tick0 for this axis
*
* @param {any} tick0: the candidate tick0. Valid values are numbers and strings,
* further constrained depending on the axis type
* @param {string} axType: the axis type
* @param {string} calendar: for date axes, the calendar to validate/convert with
* @param {any} dtick: an already valid dtick. Only used for D1 and D2 log dticks,
* which do not support tick0 at all.
*/
exports.tick0 = function (tick0, axType, calendar, dtick) {
if (axType === 'date') {
return Lib.cleanDate(tick0, Lib.dateTick0(calendar, dtick % ONEWEEK === 0 ? 1 : 0));
}
if (dtick === 'D1' || dtick === 'D2') {
// D1 and D2 modes ignore tick0 entirely
return undefined;
}
// Aside from date axes, tick0 must be numeric
return isNumeric(tick0) ? Number(tick0) : 0;
};
/***/ }),
/***/ 33816:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var counterRegex = (__webpack_require__(53756).counter);
module.exports = {
idRegex: {
x: counterRegex('x', '( domain)?'),
y: counterRegex('y', '( domain)?')
},
attrRegex: counterRegex('[xy]axis'),
// axis match regular expression
xAxisMatch: counterRegex('xaxis'),
yAxisMatch: counterRegex('yaxis'),
// pattern matching axis ids and names
// note that this is more permissive than counterRegex, as
// id2name, name2id, and cleanId accept "x1" etc
AX_ID_PATTERN: /^[xyz][0-9]*( domain)?$/,
AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/,
// and for 2D subplots
SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/,
HOUR_PATTERN: 'hour',
WEEKDAY_PATTERN: 'day of week',
// pixels to move mouse before you stop clamping to starting point
MINDRAG: 8,
// smallest dimension allowed for a zoombox
MINZOOM: 20,
// width of axis drag regions
DRAGGERSIZE: 20,
// delay before a redraw (relayout) after smooth panning and zooming
REDRAWDELAY: 50,
// last resort axis ranges for x and y axes if we have no data
DFLTRANGEX: [-1, 6],
DFLTRANGEY: [-1, 4],
// Layers to keep trace types in the right order
// N.B. each 'unique' plot method must have its own layer
traceLayerClasses: ['imagelayer', 'heatmaplayer', 'contourcarpetlayer', 'contourlayer', 'funnellayer', 'waterfalllayer', 'barlayer', 'carpetlayer', 'violinlayer', 'boxlayer', 'ohlclayer', 'scattercarpetlayer', 'scatterlayer'],
clipOnAxisFalseQuery: ['.scatterlayer', '.barlayer', '.funnellayer', '.waterfalllayer'],
layerValue2layerClass: {
'above traces': 'above',
'below traces': 'below'
},
zindexSeparator: 'z' // used for zindex of cartesian subplots e.g. xy, xyz2, xyz3, etc.
};
/***/ }),
/***/ 71888:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var autorange = __webpack_require__(19280);
var id2name = (__webpack_require__(79811).id2name);
var layoutAttributes = __webpack_require__(94724);
var scaleZoom = __webpack_require__(21160);
var setConvert = __webpack_require__(78344);
var ALMOST_EQUAL = (__webpack_require__(39032).ALMOST_EQUAL);
var FROM_BL = (__webpack_require__(84284).FROM_BL);
exports.handleDefaults = function (layoutIn, layoutOut, opts) {
var axIds = opts.axIds;
var axHasImage = opts.axHasImage;
// sets of axes linked by `scaleanchor` OR `matches` along with the
// scaleratios compounded together, populated in handleConstraintDefaults
var constraintGroups = layoutOut._axisConstraintGroups = [];
// similar to _axisConstraintGroups, but only matching axes
var matchGroups = layoutOut._axisMatchGroups = [];
var i, group, axId, axName, axIn, axOut, attr, val;
for (i = 0; i < axIds.length; i++) {
axName = id2name(axIds[i]);
axIn = layoutIn[axName];
axOut = layoutOut[axName];
handleOneAxDefaults(axIn, axOut, {
axIds: axIds,
layoutOut: layoutOut,
hasImage: axHasImage[axName]
});
}
// save matchGroup on each matching axis
function stash(groups, stashAttr) {
for (i = 0; i < groups.length; i++) {
group = groups[i];
for (axId in group) {
layoutOut[id2name(axId)][stashAttr] = group;
}
}
}
stash(matchGroups, '_matchGroup');
// If any axis in a constraint group is fixedrange, they all get fixed
// This covers matches axes, as they're now in the constraintgroup too
// and have not yet been removed (if the group is *only* matching)
for (i = 0; i < constraintGroups.length; i++) {
group = constraintGroups[i];
for (axId in group) {
axOut = layoutOut[id2name(axId)];
if (axOut.fixedrange) {
for (var axId2 in group) {
var axName2 = id2name(axId2);
if ((layoutIn[axName2] || {}).fixedrange === false) {
Lib.warn('fixedrange was specified as false for axis ' + axName2 + ' but was overridden because another ' + 'axis in its constraint group has fixedrange true');
}
layoutOut[axName2].fixedrange = true;
}
break;
}
}
}
// remove constraint groups that simply duplicate match groups
i = 0;
while (i < constraintGroups.length) {
group = constraintGroups[i];
for (axId in group) {
axOut = layoutOut[id2name(axId)];
if (axOut._matchGroup && Object.keys(axOut._matchGroup).length === Object.keys(group).length) {
constraintGroups.splice(i, 1);
i--;
}
break;
}
i++;
}
// save constraintGroup on each constrained axis
stash(constraintGroups, '_constraintGroup');
// make sure `matching` axes share values of necessary attributes
// Precedence (base axis is the one that doesn't list a `matches`, ie others
// all point to it):
// (1) explicitly defined value in the base axis
// (2) explicitly defined in another axis (arbitrary order)
// (3) default in the base axis
var matchAttrs = ['constrain', 'range', 'autorange', 'rangemode', 'rangebreaks', 'categoryorder', 'categoryarray'];
var hasRange = false;
var hasDayOfWeekBreaks = false;
function setAttrVal() {
val = axOut[attr];
if (attr === 'rangebreaks') {
hasDayOfWeekBreaks = axOut._hasDayOfWeekBreaks;
}
}
for (i = 0; i < matchGroups.length; i++) {
group = matchGroups[i];
// find 'matching' range attrs
for (var j = 0; j < matchAttrs.length; j++) {
attr = matchAttrs[j];
val = null;
var baseAx;
for (axId in group) {
axName = id2name(axId);
axIn = layoutIn[axName];
axOut = layoutOut[axName];
if (!(attr in axOut)) {
continue;
}
if (!axOut.matches) {
baseAx = axOut;
// top priority: explicit value in base axis
if (attr in axIn) {
setAttrVal();
break;
}
}
if (val === null && attr in axIn) {
// second priority: first explicit value in another axis
setAttrVal();
}
}
// special logic for coupling of range and autorange
// if nobody explicitly specifies autorange, but someone does
// explicitly specify range, autorange must be disabled.
if (attr === 'range' && val && axIn.range && axIn.range.length === 2 && axIn.range[0] !== null && axIn.range[1] !== null) {
hasRange = true;
}
if (attr === 'autorange' && val === null && hasRange) {
val = false;
}
if (val === null && attr in baseAx) {
// fallback: default value in base axis
val = baseAx[attr];
}
// but we still might not have a value, which is fine.
if (val !== null) {
for (axId in group) {
axOut = layoutOut[id2name(axId)];
axOut[attr] = attr === 'range' ? val.slice() : val;
if (attr === 'rangebreaks') {
axOut._hasDayOfWeekBreaks = hasDayOfWeekBreaks;
setConvert(axOut, layoutOut);
}
}
}
}
}
};
function handleOneAxDefaults(axIn, axOut, opts) {
var axIds = opts.axIds;
var layoutOut = opts.layoutOut;
var hasImage = opts.hasImage;
var constraintGroups = layoutOut._axisConstraintGroups;
var matchGroups = layoutOut._axisMatchGroups;
var axId = axOut._id;
var axLetter = axId.charAt(0);
var splomStash = ((layoutOut._splomAxes || {})[axLetter] || {})[axId] || {};
var thisID = axOut._id;
var isX = thisID.charAt(0) === 'x';
// Clear _matchGroup & _constraintGroup so relinkPrivateKeys doesn't keep
// an old one around. If this axis is in a group we'll set this again later
axOut._matchGroup = null;
axOut._constraintGroup = null;
function coerce(attr, dflt) {
return Lib.coerce(axIn, axOut, layoutAttributes, attr, dflt);
}
// coerce the constraint mechanics even if this axis has no scaleanchor
// because it may be the anchor of another axis.
coerce('constrain', hasImage ? 'domain' : 'range');
Lib.coerce(axIn, axOut, {
constraintoward: {
valType: 'enumerated',
values: isX ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'],
dflt: isX ? 'center' : 'middle'
}
}, 'constraintoward');
// If this axis is already part of a constraint group, we can't
// scaleanchor any other axis in that group, or we'd make a loop.
// Filter axIds to enforce this, also matching axis types.
var thisType = axOut.type;
var i, idi;
var linkableAxes = [];
for (i = 0; i < axIds.length; i++) {
idi = axIds[i];
if (idi === thisID) continue;
var axi = layoutOut[id2name(idi)];
if (axi.type === thisType) {
linkableAxes.push(idi);
}
}
var thisGroup = getConstraintGroup(constraintGroups, thisID);
if (thisGroup) {
var linkableAxesNoLoops = [];
for (i = 0; i < linkableAxes.length; i++) {
idi = linkableAxes[i];
if (!thisGroup[idi]) linkableAxesNoLoops.push(idi);
}
linkableAxes = linkableAxesNoLoops;
}
var canLink = linkableAxes.length;
var matches, scaleanchor;
if (canLink && (axIn.matches || splomStash.matches)) {
matches = Lib.coerce(axIn, axOut, {
matches: {
valType: 'enumerated',
values: linkableAxes,
dflt: linkableAxes.indexOf(splomStash.matches) !== -1 ? splomStash.matches : undefined
}
}, 'matches');
}
// 'matches' wins over 'scaleanchor' - each axis can only specify one
// constraint, but you can chain matches and scaleanchor constraints by
// specifying them in separate axes.
var scaleanchorDflt = hasImage && !isX ? axOut.anchor : undefined;
if (canLink && !matches && (axIn.scaleanchor || scaleanchorDflt)) {
scaleanchor = Lib.coerce(axIn, axOut, {
scaleanchor: {
valType: 'enumerated',
values: linkableAxes.concat([false])
}
}, 'scaleanchor', scaleanchorDflt);
}
if (matches) {
axOut._matchGroup = updateConstraintGroups(matchGroups, thisID, matches, 1);
// Also include match constraints in the scale groups
var matchedAx = layoutOut[id2name(matches)];
var matchRatio = extent(layoutOut, axOut) / extent(layoutOut, matchedAx);
if (isX !== (matches.charAt(0) === 'x')) {
// We don't yet know the actual scale ratio of x/y matches constraints,
// due to possible automargins, so just leave a placeholder for this:
// 'x' means "x size over y size", 'y' means the inverse.
// in principle in the constraint group you could get multiple of these.
matchRatio = (isX ? 'x' : 'y') + matchRatio;
}
updateConstraintGroups(constraintGroups, thisID, matches, matchRatio);
} else if (axIn.matches && axIds.indexOf(axIn.matches) !== -1) {
Lib.warn('ignored ' + axOut._name + '.matches: "' + axIn.matches + '" to avoid an infinite loop');
}
if (scaleanchor) {
var scaleratio = coerce('scaleratio');
// TODO: I suppose I could do attribute.min: Number.MIN_VALUE to avoid zero,
// but that seems hacky. Better way to say "must be a positive number"?
// Of course if you use several super-tiny values you could eventually
// force a product of these to zero and all hell would break loose...
// Likewise with super-huge values.
if (!scaleratio) scaleratio = axOut.scaleratio = 1;
updateConstraintGroups(constraintGroups, thisID, scaleanchor, scaleratio);
} else if (axIn.scaleanchor && axIds.indexOf(axIn.scaleanchor) !== -1) {
Lib.warn('ignored ' + axOut._name + '.scaleanchor: "' + axIn.scaleanchor + '" to avoid either an infinite loop ' + 'and possibly inconsistent scaleratios, or because this axis ' + 'declares a *matches* constraint.');
}
}
function extent(layoutOut, ax) {
var domain = ax.domain;
if (!domain) {
// at this point overlaying axes haven't yet inherited their main domains
// TODO: constrain: domain with overlaying axes is likely a bug.
domain = layoutOut[id2name(ax.overlaying)].domain;
}
return domain[1] - domain[0];
}
function getConstraintGroup(groups, thisID) {
for (var i = 0; i < groups.length; i++) {
if (groups[i][thisID]) {
return groups[i];
}
}
return null;
}
/*
* Add this axis to the axis constraint groups, which is the collection
* of axes that are all constrained together on scale (or matching).
*
* constraintGroups: a list of objects. each object is
* {axis_id: scale_within_group}, where scale_within_group is
* only important relative to the rest of the group, and defines
* the relative scales between all axes in the group
*
* thisGroup: the group the current axis is already in
* thisID: the id if the current axis
* thatID: the id of the axis to scale it with
* scaleratio: the ratio of this axis to the thatID axis
*/
function updateConstraintGroups(constraintGroups, thisID, thatID, scaleratio) {
var i, j, groupi, keyj, thisGroupIndex;
var thisGroup = getConstraintGroup(constraintGroups, thisID);
if (thisGroup === null) {
thisGroup = {};
thisGroup[thisID] = 1;
thisGroupIndex = constraintGroups.length;
constraintGroups.push(thisGroup);
} else {
thisGroupIndex = constraintGroups.indexOf(thisGroup);
}
var thisGroupKeys = Object.keys(thisGroup);
// we know that this axis isn't in any other groups, but we don't know
// about the thatID axis. If it is, we need to merge the groups.
for (i = 0; i < constraintGroups.length; i++) {
groupi = constraintGroups[i];
if (i !== thisGroupIndex && groupi[thatID]) {
var baseScale = groupi[thatID];
for (j = 0; j < thisGroupKeys.length; j++) {
keyj = thisGroupKeys[j];
groupi[keyj] = multiplyScales(baseScale, multiplyScales(scaleratio, thisGroup[keyj]));
}
constraintGroups.splice(thisGroupIndex, 1);
return;
}
}
// otherwise, we insert the new thatID axis as the base scale (1)
// in its group, and scale the rest of the group to it
if (scaleratio !== 1) {
for (j = 0; j < thisGroupKeys.length; j++) {
var key = thisGroupKeys[j];
thisGroup[key] = multiplyScales(scaleratio, thisGroup[key]);
}
}
thisGroup[thatID] = 1;
}
// scales may be numbers or 'x1.3', 'yy4.5' etc to multiply by as-yet-unknown
// ratios between x and y plot sizes n times
function multiplyScales(a, b) {
var aPrefix = '';
var bPrefix = '';
var aLen, bLen;
if (typeof a === 'string') {
aPrefix = a.match(/^[xy]*/)[0];
aLen = aPrefix.length;
a = +a.substr(aLen);
}
if (typeof b === 'string') {
bPrefix = b.match(/^[xy]*/)[0];
bLen = bPrefix.length;
b = +b.substr(bLen);
}
var c = a * b;
// just two numbers
if (!aLen && !bLen) {
return c;
}
// one or more prefixes of the same type
if (!aLen || !bLen || aPrefix.charAt(0) === bPrefix.charAt(0)) {
return aPrefix + bPrefix + a * b;
}
// x and y cancel each other out exactly - back to a number
if (aLen === bLen) {
return c;
}
// partial cancelation of prefixes
return (aLen > bLen ? aPrefix.substr(bLen) : bPrefix.substr(aLen)) + c;
}
function finalRatios(group, fullLayout) {
var size = fullLayout._size;
var yRatio = size.h / size.w;
var out = {};
var keys = Object.keys(group);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var val = group[key];
if (typeof val === 'string') {
var prefix = val.match(/^[xy]*/)[0];
var pLen = prefix.length;
val = +val.substr(pLen);
var mult = prefix.charAt(0) === 'y' ? yRatio : 1 / yRatio;
for (var j = 0; j < pLen; j++) {
val *= mult;
}
}
out[key] = val;
}
return out;
}
exports.enforce = function enforce(gd) {
var fullLayout = gd._fullLayout;
var constraintGroups = fullLayout._axisConstraintGroups || [];
var i, j, group, axisID, ax, normScale, mode, factor;
// matching constraints are handled in the autorange code when autoranged,
// or in the supplyDefaults code when explicitly ranged.
// now we just need to handle scaleanchor constraints
// matches constraints that chain with scaleanchor constraints are included
// here too, but because matches has already been satisfied,
// any changes here should preserve that.
for (i = 0; i < constraintGroups.length; i++) {
group = finalRatios(constraintGroups[i], fullLayout);
var axisIDs = Object.keys(group);
var minScale = Infinity;
var maxScale = 0;
// mostly matchScale will be the same as minScale
// ie we expand axis ranges to encompass *everything*
// that's currently in any of their ranges, but during
// autorange of a subset of axes we will ignore other
// axes for this purpose.
var matchScale = Infinity;
var normScales = {};
var axes = {};
var hasAnyDomainConstraint = false;
// find the (normalized) scale of each axis in the group
for (j = 0; j < axisIDs.length; j++) {
axisID = axisIDs[j];
axes[axisID] = ax = fullLayout[id2name(axisID)];
if (ax._inputDomain) ax.domain = ax._inputDomain.slice();else ax._inputDomain = ax.domain.slice();
if (!ax._inputRange) ax._inputRange = ax.range.slice();
// set axis scale here so we can use _m rather than
// having to calculate it from length and range
ax.setScale();
// abs: inverted scales still satisfy the constraint
normScales[axisID] = normScale = Math.abs(ax._m) / group[axisID];
minScale = Math.min(minScale, normScale);
if (ax.constrain === 'domain' || !ax._constraintShrinkable) {
matchScale = Math.min(matchScale, normScale);
}
// this has served its purpose, so remove it
delete ax._constraintShrinkable;
maxScale = Math.max(maxScale, normScale);
if (ax.constrain === 'domain') hasAnyDomainConstraint = true;
}
// Do we have a constraint mismatch? Give a small buffer for rounding errors
if (minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue;
// now increase any ranges we need to until all normalized scales are equal
for (j = 0; j < axisIDs.length; j++) {
axisID = axisIDs[j];
normScale = normScales[axisID];
ax = axes[axisID];
mode = ax.constrain;
// even if the scale didn't change, if we're shrinking domain
// we need to recalculate in case `constraintoward` changed
if (normScale !== matchScale || mode === 'domain') {
factor = normScale / matchScale;
if (mode === 'range') {
scaleZoom(ax, factor);
} else {
// mode === 'domain'
var inputDomain = ax._inputDomain;
var domainShrunk = (ax.domain[1] - ax.domain[0]) / (inputDomain[1] - inputDomain[0]);
var rangeShrunk = (ax.r2l(ax.range[1]) - ax.r2l(ax.range[0])) / (ax.r2l(ax._inputRange[1]) - ax.r2l(ax._inputRange[0]));
factor /= domainShrunk;
if (factor * rangeShrunk < 1) {
// we've asked to magnify the axis more than we can just by
// enlarging the domain - so we need to constrict range
ax.domain = ax._input.domain = inputDomain.slice();
scaleZoom(ax, factor);
continue;
}
if (rangeShrunk < 1) {
// the range has previously been constricted by ^^, but we've
// switched to the domain-constricted regime, so reset range
ax.range = ax._input.range = ax._inputRange.slice();
factor *= rangeShrunk;
}
if (ax.autorange) {
/*
* range & factor may need to change because range was
* calculated for the larger scaling, so some pixel
* paddings may get cut off when we reduce the domain.
*
* This is easier than the regular autorange calculation
* because we already know the scaling `m`, but we still
* need to cut out impossible constraints (like
* annotations with super-long arrows). That's what
* outerMin/Max are for - if the expansion was going to
* go beyond the original domain, it must be impossible
*/
var rl0 = ax.r2l(ax.range[0]);
var rl1 = ax.r2l(ax.range[1]);
var rangeCenter = (rl0 + rl1) / 2;
var rangeMin = rangeCenter;
var rangeMax = rangeCenter;
var halfRange = Math.abs(rl1 - rangeCenter);
// extra tiny bit for rounding errors, in case we actually
// *are* expanding to the full domain
var outerMin = rangeCenter - halfRange * factor * 1.0001;
var outerMax = rangeCenter + halfRange * factor * 1.0001;
var getPadMin = autorange.makePadFn(fullLayout, ax, 0);
var getPadMax = autorange.makePadFn(fullLayout, ax, 1);
updateDomain(ax, factor);
var m = Math.abs(ax._m);
var extremes = autorange.concatExtremes(gd, ax);
var minArray = extremes.min;
var maxArray = extremes.max;
var newVal;
var k;
for (k = 0; k < minArray.length; k++) {
newVal = minArray[k].val - getPadMin(minArray[k]) / m;
if (newVal > outerMin && newVal < rangeMin) {
rangeMin = newVal;
}
}
for (k = 0; k < maxArray.length; k++) {
newVal = maxArray[k].val + getPadMax(maxArray[k]) / m;
if (newVal < outerMax && newVal > rangeMax) {
rangeMax = newVal;
}
}
var domainExpand = (rangeMax - rangeMin) / (2 * halfRange);
factor /= domainExpand;
rangeMin = ax.l2r(rangeMin);
rangeMax = ax.l2r(rangeMax);
ax.range = ax._input.range = rl0 < rl1 ? [rangeMin, rangeMax] : [rangeMax, rangeMin];
}
updateDomain(ax, factor);
}
}
}
}
};
exports.getAxisGroup = function getAxisGroup(fullLayout, axId) {
var matchGroups = fullLayout._axisMatchGroups;
for (var i = 0; i < matchGroups.length; i++) {
var group = matchGroups[i];
if (group[axId]) return 'g' + i;
}
return axId;
};
// For use before autoranging, check if this axis was previously constrained
// by domain but no longer is
exports.clean = function clean(gd, ax) {
if (ax._inputDomain) {
var isConstrained = false;
var axId = ax._id;
var constraintGroups = gd._fullLayout._axisConstraintGroups;
for (var j = 0; j < constraintGroups.length; j++) {
if (constraintGroups[j][axId]) {
isConstrained = true;
break;
}
}
if (!isConstrained || ax.constrain !== 'domain') {
ax._input.domain = ax.domain = ax._inputDomain;
delete ax._inputDomain;
}
}
};
function updateDomain(ax, factor) {
var inputDomain = ax._inputDomain;
var centerFraction = FROM_BL[ax.constraintoward];
var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction;
ax.domain = ax._input.domain = [center + (inputDomain[0] - center) / factor, center + (inputDomain[1] - center) / factor];
ax.setScale();
}
/***/ }),
/***/ 51184:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var numberFormat = Lib.numberFormat;
var tinycolor = __webpack_require__(49760);
var supportsPassive = __webpack_require__(89184);
var Registry = __webpack_require__(24040);
var strTranslate = Lib.strTranslate;
var svgTextUtils = __webpack_require__(72736);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Fx = __webpack_require__(93024);
var Axes = __webpack_require__(54460);
var setCursor = __webpack_require__(93972);
var dragElement = __webpack_require__(86476);
var helpers = __webpack_require__(72760);
var selectingOrDrawing = helpers.selectingOrDrawing;
var freeMode = helpers.freeMode;
var FROM_TL = (__webpack_require__(84284).FROM_TL);
var clearGlCanvases = __webpack_require__(73696);
var redrawReglTraces = (__webpack_require__(39172).redrawReglTraces);
var Plots = __webpack_require__(7316);
var getFromId = (__webpack_require__(79811).getFromId);
var prepSelect = (__webpack_require__(22676).prepSelect);
var clearOutline = (__webpack_require__(22676).clearOutline);
var selectOnClick = (__webpack_require__(22676).selectOnClick);
var scaleZoom = __webpack_require__(21160);
var constants = __webpack_require__(33816);
var MINDRAG = constants.MINDRAG;
var MINZOOM = constants.MINZOOM;
// flag for showing "doubleclick to zoom out" only at the beginning
var SHOWZOOMOUTTIP = true;
// dragBox: create an element to drag one or more axis ends
// inputs:
// plotinfo - which subplot are we making dragboxes on?
// x,y,w,h - left, top, width, height of the box
// ns - how does this drag the vertical axis?
// 'n' - top only
// 's' - bottom only
// 'ns' - top and bottom together, difference unchanged
// ew - same for horizontal axis
function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) {
// mouseDown stores ms of first mousedown event in the last
// `gd._context.doubleClickDelay` ms on the drag bars
// numClicks stores how many mousedowns have been seen
// within `gd._context.doubleClickDelay` so we can check for click or doubleclick events
// dragged stores whether a drag has occurred, so we don't have to
// redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px
var zoomlayer = gd._fullLayout._zoomlayer;
var isMainDrag = ns + ew === 'nsew';
var singleEnd = (ns + ew).length === 1;
// main subplot x and y (i.e. found in plotinfo - the main ones)
var xa0, ya0;
// {ax._id: ax} hash objects
var xaHash, yaHash;
// xaHash/yaHash values (arrays)
var xaxes, yaxes;
// main axis offsets
var xs, ys;
// main axis lengths
var pw, ph;
// contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes'
// which are the x/y {ax._id: ax} hash objects and their values
// for linked axis relative to this subplot
var links;
// similar to `links` but for matching axes
var matches;
// set to ew/ns val when active, set to '' when inactive
var xActive, yActive;
// are all axes in this subplot are fixed?
var allFixedRanges;
// do we need to edit x/y ranges?
var editX, editY;
// graph-wide optimization flags
var hasScatterGl, hasSplom, hasSVG;
// collected changes to be made to the plot by relayout at the end
var updates;
// scaling factors from css transform
var scaleX;
var scaleY;
// offset the x location of the box if needed
x += plotinfo.yaxis._shift;
function recomputeAxisLists() {
xa0 = plotinfo.xaxis;
ya0 = plotinfo.yaxis;
pw = xa0._length;
ph = ya0._length;
xs = xa0._offset;
ys = ya0._offset;
xaHash = {};
xaHash[xa0._id] = xa0;
yaHash = {};
yaHash[ya0._id] = ya0;
// if we're dragging two axes at once, also drag overlays
if (ns && ew) {
var overlays = plotinfo.overlays;
for (var i = 0; i < overlays.length; i++) {
var xa = overlays[i].xaxis;
xaHash[xa._id] = xa;
var ya = overlays[i].yaxis;
yaHash[ya._id] = ya;
}
}
xaxes = hashValues(xaHash);
yaxes = hashValues(yaHash);
xActive = isDirectionActive(xaxes, ew);
yActive = isDirectionActive(yaxes, ns);
allFixedRanges = !yActive && !xActive;
matches = calcLinks(gd, gd._fullLayout._axisMatchGroups, xaHash, yaHash);
links = calcLinks(gd, gd._fullLayout._axisConstraintGroups, xaHash, yaHash, matches);
var spConstrained = links.isSubplotConstrained || matches.isSubplotConstrained;
editX = ew || spConstrained;
editY = ns || spConstrained;
var fullLayout = gd._fullLayout;
hasScatterGl = fullLayout._has('scattergl');
hasSplom = fullLayout._has('splom');
hasSVG = fullLayout._has('svg');
}
recomputeAxisLists();
var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag);
var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h);
// still need to make the element if the axes are disabled
// but nuke its events (except for maindrag which needs them for hover)
// and stop there
if (allFixedRanges && !isMainDrag) {
dragger.onmousedown = null;
dragger.style.pointerEvents = 'none';
return dragger;
}
var dragOptions = {
element: dragger,
gd: gd,
plotinfo: plotinfo
};
dragOptions.prepFn = function (e, startX, startY) {
var dragModePrev = dragOptions.dragmode;
var dragModeNow = gd._fullLayout.dragmode;
if (dragModeNow !== dragModePrev) {
dragOptions.dragmode = dragModeNow;
}
recomputeAxisLists();
scaleX = gd._fullLayout._invScaleX;
scaleY = gd._fullLayout._invScaleY;
if (!allFixedRanges) {
if (isMainDrag) {
// main dragger handles all drag modes, and changes
// to pan (or to zoom if it already is pan) on shift
if (e.shiftKey) {
if (dragModeNow === 'pan') dragModeNow = 'zoom';else if (!selectingOrDrawing(dragModeNow)) dragModeNow = 'pan';
} else if (e.ctrlKey) {
dragModeNow = 'pan';
}
} else {
// all other draggers just pan
dragModeNow = 'pan';
}
}
if (freeMode(dragModeNow)) dragOptions.minDrag = 1;else dragOptions.minDrag = undefined;
if (selectingOrDrawing(dragModeNow)) {
dragOptions.xaxes = xaxes;
dragOptions.yaxes = yaxes;
// this attaches moveFn, clickFn, doneFn on dragOptions
prepSelect(e, startX, startY, dragOptions, dragModeNow);
} else {
dragOptions.clickFn = clickFn;
if (selectingOrDrawing(dragModePrev)) {
// TODO Fix potential bug
// Note: clearing / resetting selection state only happens, when user
// triggers at least one interaction in pan/zoom mode. Otherwise, the
// select/lasso outlines are deleted (in plots.js.cleanPlot) but the selection
// cache isn't cleared. So when the user switches back to select/lasso and
// 'adds to a selection' with Shift, the "old", seemingly removed outlines
// are redrawn again because the selection cache still holds their coordinates.
// However, this isn't easily solved, since plots.js would need
// to have a reference to the dragOptions object (which holds the
// selection cache).
clearAndResetSelect();
}
if (!allFixedRanges) {
if (dragModeNow === 'zoom') {
dragOptions.moveFn = zoomMove;
dragOptions.doneFn = zoomDone;
// zoomMove takes care of the threshold, but we need to
// minimize this so that constrained zoom boxes will flip
// orientation at the right place
dragOptions.minDrag = 1;
zoomPrep(e, startX, startY);
} else if (dragModeNow === 'pan') {
dragOptions.moveFn = plotDrag;
dragOptions.doneFn = dragTail;
}
}
}
gd._fullLayout._redrag = function () {
var dragDataNow = gd._dragdata;
if (dragDataNow && dragDataNow.element === dragger) {
var dragModeNow = gd._fullLayout.dragmode;
if (!selectingOrDrawing(dragModeNow)) {
recomputeAxisLists();
updateSubplots([0, 0, pw, ph]);
dragOptions.moveFn(dragDataNow.dx, dragDataNow.dy);
}
}
};
};
function clearAndResetSelect() {
// clear selection polygon cache (if any)
dragOptions.plotinfo.selection = false;
// clear selection outlines
clearOutline(gd);
}
function clickFn(numClicks, evt) {
var gd = dragOptions.gd;
if (gd._fullLayout._activeShapeIndex >= 0) {
gd._fullLayout._deactivateShape(gd);
return;
}
var clickmode = gd._fullLayout.clickmode;
removeZoombox(gd);
if (numClicks === 2 && !singleEnd) doubleClick();
if (isMainDrag) {
if (clickmode.indexOf('select') > -1) {
selectOnClick(evt, gd, xaxes, yaxes, plotinfo.id, dragOptions);
}
if (clickmode.indexOf('event') > -1) {
Fx.click(gd, evt, plotinfo.id);
}
} else if (numClicks === 1 && singleEnd) {
var ax = ns ? ya0 : xa0;
var end = ns === 's' || ew === 'w' ? 0 : 1;
var attrStr = ax._name + '.range[' + end + ']';
var initialText = getEndText(ax, end);
var hAlign = 'left';
var vAlign = 'middle';
if (ax.fixedrange) return;
if (ns) {
vAlign = ns === 'n' ? 'top' : 'bottom';
if (ax.side === 'right') hAlign = 'right';
} else if (ew === 'e') hAlign = 'right';
if (gd._context.showAxisRangeEntryBoxes) {
d3.select(dragger).call(svgTextUtils.makeEditable, {
gd: gd,
immediate: true,
background: gd._fullLayout.paper_bgcolor,
text: String(initialText),
fill: ax.tickfont ? ax.tickfont.color : '#444',
horizontalAlign: hAlign,
verticalAlign: vAlign
}).on('edit', function (text) {
var v = ax.d2r(text);
if (v !== undefined) {
Registry.call('_guiRelayout', gd, attrStr, v);
}
});
}
}
}
dragElement.init(dragOptions);
// x/y px position at start of drag
var x0, y0;
// bbox object of the zoombox
var box;
// luminance of bg behind zoombox
var lum;
// zoombox path outline
var path0;
// is zoombox dimmed (during drag)
var dimmed;
// 'x'-only, 'y' or 'xy' zooming
var zoomMode;
// zoombox d3 selection
var zb;
// zoombox corner d3 selection
var corners;
// zoom takes over minDrag, so it also has to take over gd._dragged
var zoomDragged;
function zoomPrep(e, startX, startY) {
var dragBBox = dragger.getBoundingClientRect();
x0 = startX - dragBBox.left;
y0 = startY - dragBBox.top;
gd._fullLayout._calcInverseTransform(gd);
var transformedCoords = Lib.apply3DTransform(gd._fullLayout._invTransform)(x0, y0);
x0 = transformedCoords[0];
y0 = transformedCoords[1];
box = {
l: x0,
r: x0,
w: 0,
t: y0,
b: y0,
h: 0
};
lum = gd._hmpixcount ? gd._hmlumcount / gd._hmpixcount : tinycolor(gd._fullLayout.plot_bgcolor).getLuminance();
path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0';
dimmed = false;
zoomMode = 'xy';
zoomDragged = false;
zb = makeZoombox(zoomlayer, lum, xs, ys, path0);
corners = makeCorners(zoomlayer, xs, ys);
}
function zoomMove(dx0, dy0) {
if (gd._transitioningWithDuration) {
return false;
}
var x1 = Math.max(0, Math.min(pw, scaleX * dx0 + x0));
var y1 = Math.max(0, Math.min(ph, scaleY * dy0 + y0));
var dx = Math.abs(x1 - x0);
var dy = Math.abs(y1 - y0);
box.l = Math.min(x0, x1);
box.r = Math.max(x0, x1);
box.t = Math.min(y0, y1);
box.b = Math.max(y0, y1);
function noZoom() {
zoomMode = '';
box.r = box.l;
box.t = box.b;
corners.attr('d', 'M0,0Z');
}
if (links.isSubplotConstrained) {
if (dx > MINZOOM || dy > MINZOOM) {
zoomMode = 'xy';
if (dx / pw > dy / ph) {
dy = dx * ph / pw;
if (y0 > y1) box.t = y0 - dy;else box.b = y0 + dy;
} else {
dx = dy * pw / ph;
if (x0 > x1) box.l = x0 - dx;else box.r = x0 + dx;
}
corners.attr('d', xyCorners(box));
} else {
noZoom();
}
} else if (matches.isSubplotConstrained) {
if (dx > MINZOOM || dy > MINZOOM) {
zoomMode = 'xy';
var r0 = Math.min(box.l / pw, (ph - box.b) / ph);
var r1 = Math.max(box.r / pw, (ph - box.t) / ph);
box.l = r0 * pw;
box.r = r1 * pw;
box.b = (1 - r0) * ph;
box.t = (1 - r1) * ph;
corners.attr('d', xyCorners(box));
} else {
noZoom();
}
} else if (!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) {
// look for small drags in one direction or the other,
// and only drag the other axis
if (dx < MINDRAG || !xActive) {
noZoom();
} else {
box.t = 0;
box.b = ph;
zoomMode = 'x';
corners.attr('d', xCorners(box, y0));
}
} else if (!xActive || dx < Math.min(dy * 0.6, MINZOOM)) {
box.l = 0;
box.r = pw;
zoomMode = 'y';
corners.attr('d', yCorners(box, x0));
} else {
zoomMode = 'xy';
corners.attr('d', xyCorners(box));
}
box.w = box.r - box.l;
box.h = box.b - box.t;
if (zoomMode) zoomDragged = true;
gd._dragged = zoomDragged;
updateZoombox(zb, corners, box, path0, dimmed, lum);
computeZoomUpdates();
gd.emit('plotly_relayouting', updates);
dimmed = true;
}
function computeZoomUpdates() {
updates = {};
// TODO: edit linked axes in zoomAxRanges and in dragTail
if (zoomMode === 'xy' || zoomMode === 'x') {
zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes);
updateMatchedAxRange('x', updates);
}
if (zoomMode === 'xy' || zoomMode === 'y') {
zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes);
updateMatchedAxRange('y', updates);
}
}
function zoomDone() {
computeZoomUpdates();
removeZoombox(gd);
dragTail();
showDoubleClickNotifier(gd);
}
// scroll zoom, on all draggers except corners
var scrollViewBox = [0, 0, pw, ph];
// wait a little after scrolling before redrawing
var redrawTimer = null;
var REDRAWDELAY = constants.REDRAWDELAY;
var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo;
function zoomWheel(e) {
// deactivate mousewheel scrolling on embedded graphs
// devs can override this with layout._enablescrollzoom,
// but _ ensures this setting won't leave their page
if (!gd._context._scrollZoom.cartesian && !gd._fullLayout._enablescrollzoom) {
return;
}
clearAndResetSelect();
// If a transition is in progress, then disable any behavior:
if (gd._transitioningWithDuration) {
e.preventDefault();
e.stopPropagation();
return;
}
recomputeAxisLists();
clearTimeout(redrawTimer);
var wheelDelta = -e.deltaY;
if (!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10;
if (!isFinite(wheelDelta)) {
Lib.log('Did not find wheel motion attributes: ', e);
return;
}
var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200);
var gbb = mainplot.draglayer.select('.nsewdrag').node().getBoundingClientRect();
var xfrac = (e.clientX - gbb.left) / gbb.width;
var yfrac = (gbb.bottom - e.clientY) / gbb.height;
var i;
function zoomWheelOneAxis(ax, centerFraction, zoom) {
if (ax.fixedrange) return;
var axRange = Lib.simpleMap(ax.range, ax.r2l);
var v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction;
function doZoom(v) {
return ax.l2r(v0 + (v - v0) * zoom);
}
ax.range = axRange.map(doZoom);
}
if (editX) {
// if we're only zooming this axis because of constraints,
// zoom it about the center
if (!ew) xfrac = 0.5;
for (i = 0; i < xaxes.length; i++) {
zoomWheelOneAxis(xaxes[i], xfrac, zoom);
}
updateMatchedAxRange('x');
scrollViewBox[2] *= zoom;
scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1);
}
if (editY) {
if (!ns) yfrac = 0.5;
for (i = 0; i < yaxes.length; i++) {
zoomWheelOneAxis(yaxes[i], yfrac, zoom);
}
updateMatchedAxRange('y');
scrollViewBox[3] *= zoom;
scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1);
}
// viewbox redraw at first
updateSubplots(scrollViewBox);
ticksAndAnnotations();
gd.emit('plotly_relayouting', updates);
// then replot after a delay to make sure
// no more scrolling is coming
redrawTimer = setTimeout(function () {
if (!gd._fullLayout) return;
scrollViewBox = [0, 0, pw, ph];
dragTail();
}, REDRAWDELAY);
e.preventDefault();
return;
}
// everything but the corners gets wheel zoom
if (ns.length * ew.length !== 1) {
attachWheelEventHandler(dragger, zoomWheel);
}
// plotDrag: move the plot in response to a drag
function plotDrag(dx, dy) {
dx = dx * scaleX;
dy = dy * scaleY;
// If a transition is in progress, then disable any behavior:
if (gd._transitioningWithDuration) {
return;
}
// prevent axis drawing from monkeying with margins until we're done
gd._fullLayout._replotting = true;
if (xActive === 'ew' || yActive === 'ns') {
var spDx = xActive ? -dx : 0;
var spDy = yActive ? -dy : 0;
if (matches.isSubplotConstrained) {
if (xActive && yActive) {
var frac = (dx / pw - dy / ph) / 2;
dx = frac * pw;
dy = -frac * ph;
spDx = -dx;
spDy = -dy;
}
if (yActive) {
spDx = -spDy * pw / ph;
} else {
spDy = -spDx * ph / pw;
}
}
if (xActive) {
dragAxList(xaxes, dx);
updateMatchedAxRange('x');
}
if (yActive) {
dragAxList(yaxes, dy);
updateMatchedAxRange('y');
}
updateSubplots([spDx, spDy, pw, ph]);
ticksAndAnnotations();
gd.emit('plotly_relayouting', updates);
return;
}
// dz: set a new value for one end (0 or 1) of an axis array axArray,
// and return a pixel shift for that end for the viewbox
// based on pixel drag distance d
// TODO: this makes (generally non-fatal) errors when you get
// near floating point limits
function dz(axArray, end, d) {
var otherEnd = 1 - end;
var movedAx;
var newLinearizedEnd;
for (var i = 0; i < axArray.length; i++) {
var axi = axArray[i];
if (axi.fixedrange) continue;
movedAx = axi;
newLinearizedEnd = axi._rl[otherEnd] + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length);
var newEnd = axi.l2r(newLinearizedEnd);
// if l2r comes back false or undefined, it means we've dragged off
// the end of valid ranges - so stop.
if (newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd;
}
return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / (movedAx._rl[end] - movedAx._rl[otherEnd]);
}
var dxySign = xActive === 'w' === (yActive === 'n') ? 1 : -1;
if (xActive && yActive && (links.isSubplotConstrained || matches.isSubplotConstrained)) {
// dragging a corner of a constrained subplot:
// respect the fixed corner, but harmonize dx and dy
var dxyFraction = (dx / pw + dxySign * dy / ph) / 2;
dx = dxyFraction * pw;
dy = dxySign * dxyFraction * ph;
}
var xStart, yStart;
if (xActive === 'w') dx = dz(xaxes, 0, dx);else if (xActive === 'e') dx = dz(xaxes, 1, -dx);else if (!xActive) dx = 0;
if (yActive === 'n') dy = dz(yaxes, 1, dy);else if (yActive === 's') dy = dz(yaxes, 0, -dy);else if (!yActive) dy = 0;
xStart = xActive === 'w' ? dx : 0;
yStart = yActive === 'n' ? dy : 0;
if (links.isSubplotConstrained && !matches.isSubplotConstrained ||
// NW or SE on matching axes - create a symmetric zoom
matches.isSubplotConstrained && xActive && yActive && dxySign > 0) {
var i;
if (matches.isSubplotConstrained || !xActive && yActive.length === 1) {
// dragging one end of the y axis of a constrained subplot
// scale the other axis the same about its middle
for (i = 0; i < xaxes.length; i++) {
xaxes[i].range = xaxes[i]._r.slice();
scaleZoom(xaxes[i], 1 - dy / ph);
}
dx = dy * pw / ph;
xStart = dx / 2;
}
if (matches.isSubplotConstrained || !yActive && xActive.length === 1) {
for (i = 0; i < yaxes.length; i++) {
yaxes[i].range = yaxes[i]._r.slice();
scaleZoom(yaxes[i], 1 - dx / pw);
}
dy = dx * ph / pw;
yStart = dy / 2;
}
}
if (!matches.isSubplotConstrained || !yActive) {
updateMatchedAxRange('x');
}
if (!matches.isSubplotConstrained || !xActive) {
updateMatchedAxRange('y');
}
var xSize = pw - dx;
var ySize = ph - dy;
if (matches.isSubplotConstrained && !(xActive && yActive)) {
if (xActive) {
yStart = xStart ? 0 : dx * ph / pw;
ySize = xSize * ph / pw;
} else {
xStart = yStart ? 0 : dy * pw / ph;
xSize = ySize * pw / ph;
}
}
updateSubplots([xStart, yStart, xSize, ySize]);
ticksAndAnnotations();
gd.emit('plotly_relayouting', updates);
}
function updateMatchedAxRange(axLetter, out) {
var matchedAxes = matches.isSubplotConstrained ? {
x: yaxes,
y: xaxes
}[axLetter] : matches[axLetter + 'axes'];
var constrainedAxes = matches.isSubplotConstrained ? {
x: xaxes,
y: yaxes
}[axLetter] : [];
for (var i = 0; i < matchedAxes.length; i++) {
var ax = matchedAxes[i];
var axId = ax._id;
var axId2 = matches.xLinks[axId] || matches.yLinks[axId];
var ax2 = constrainedAxes[0] || xaHash[axId2] || yaHash[axId2];
if (ax2) {
if (out) {
// zoombox case - don't mutate 'range', just add keys in 'updates'
out[ax._name + '.range[0]'] = out[ax2._name + '.range[0]'];
out[ax._name + '.range[1]'] = out[ax2._name + '.range[1]'];
} else {
ax.range = ax2.range.slice();
}
}
}
}
// Draw ticks and annotations (and other components) when ranges change.
// Also records the ranges that have changed for use by update at the end.
function ticksAndAnnotations() {
var activeAxIds = [];
var i;
function pushActiveAxIds(axList) {
for (i = 0; i < axList.length; i++) {
if (!axList[i].fixedrange) activeAxIds.push(axList[i]._id);
}
}
function pushActiveAxIdsSynced(axList, axisType) {
for (i = 0; i < axList.length; i++) {
var axListI = axList[i];
var axListIType = axListI[axisType];
if (!axListI.fixedrange && axListIType.tickmode === 'sync') activeAxIds.push(axListIType._id);
}
}
if (editX) {
pushActiveAxIds(xaxes);
pushActiveAxIds(links.xaxes);
pushActiveAxIds(matches.xaxes);
pushActiveAxIdsSynced(plotinfo.overlays, 'xaxis');
}
if (editY) {
pushActiveAxIds(yaxes);
pushActiveAxIds(links.yaxes);
pushActiveAxIds(matches.yaxes);
pushActiveAxIdsSynced(plotinfo.overlays, 'yaxis');
}
updates = {};
for (i = 0; i < activeAxIds.length; i++) {
var axId = activeAxIds[i];
var ax = getFromId(gd, axId);
Axes.drawOne(gd, ax, {
skipTitle: true
});
updates[ax._name + '.range[0]'] = ax.range[0];
updates[ax._name + '.range[1]'] = ax.range[1];
}
Axes.redrawComponents(gd, activeAxIds);
}
function doubleClick() {
if (gd._transitioningWithDuration) return;
var doubleClickConfig = gd._context.doubleClick;
var axList = [];
if (xActive) axList = axList.concat(xaxes);
if (yActive) axList = axList.concat(yaxes);
if (matches.xaxes) axList = axList.concat(matches.xaxes);
if (matches.yaxes) axList = axList.concat(matches.yaxes);
var attrs = {};
var ax, i;
// For reset+autosize mode:
// If *any* of the main axes is not at its initial range
// (or autoranged, if we have no initial range, to match the logic in
// doubleClickConfig === 'reset' below), we reset.
// If they are *all* at their initial ranges, then we autosize.
if (doubleClickConfig === 'reset+autosize') {
doubleClickConfig = 'autosize';
for (i = 0; i < axList.length; i++) {
ax = axList[i];
var r0 = ax._rangeInitial0;
var r1 = ax._rangeInitial1;
var hasRangeInitial = r0 !== undefined || r1 !== undefined;
if (hasRangeInitial && (r0 !== undefined && r0 !== ax.range[0] || r1 !== undefined && r1 !== ax.range[1]) || !hasRangeInitial && ax.autorange !== true) {
doubleClickConfig = 'reset';
break;
}
}
}
if (doubleClickConfig === 'autosize') {
// don't set the linked axes here, so relayout marks them as shrinkable
// and we autosize just to the requested axis/axes
for (i = 0; i < axList.length; i++) {
ax = axList[i];
if (!ax.fixedrange) attrs[ax._name + '.autorange'] = true;
}
} else if (doubleClickConfig === 'reset') {
// when we're resetting, reset all linked axes too, so we get back
// to the fully-auto-with-constraints situation
if (xActive || links.isSubplotConstrained) axList = axList.concat(links.xaxes);
if (yActive && !links.isSubplotConstrained) axList = axList.concat(links.yaxes);
if (links.isSubplotConstrained) {
if (!xActive) axList = axList.concat(xaxes);else if (!yActive) axList = axList.concat(yaxes);
}
for (i = 0; i < axList.length; i++) {
ax = axList[i];
if (!ax.fixedrange) {
var axName = ax._name;
var autorangeInitial = ax._autorangeInitial;
if (ax._rangeInitial0 === undefined && ax._rangeInitial1 === undefined) {
attrs[axName + '.autorange'] = true;
} else if (ax._rangeInitial0 === undefined) {
attrs[axName + '.autorange'] = autorangeInitial;
attrs[axName + '.range'] = [null, ax._rangeInitial1];
} else if (ax._rangeInitial1 === undefined) {
attrs[axName + '.range'] = [ax._rangeInitial0, null];
attrs[axName + '.autorange'] = autorangeInitial;
} else {
attrs[axName + '.range'] = [ax._rangeInitial0, ax._rangeInitial1];
}
}
}
}
gd.emit('plotly_doubleclick', null);
Registry.call('_guiRelayout', gd, attrs);
}
// dragTail - finish a drag event with a redraw
function dragTail() {
// put the subplot viewboxes back to default (Because we're going to)
// be repositioning the data in the relayout. But DON'T call
// ticksAndAnnotations again - it's unnecessary and would overwrite `updates`
updateSubplots([0, 0, pw, ph]);
// since we may have been redrawing some things during the drag, we may have
// accumulated MathJax promises - wait for them before we relayout.
Lib.syncOrAsync([Plots.previousPromises, function () {
gd._fullLayout._replotting = false;
Registry.call('_guiRelayout', gd, updates);
}], gd);
}
// updateSubplots - find all plot viewboxes that should be
// affected by this drag, and update them. look for all plots
// sharing an affected axis (including the one being dragged),
// includes also scattergl and splom logic.
function updateSubplots(viewBox) {
var fullLayout = gd._fullLayout;
var plotinfos = fullLayout._plots;
var subplots = fullLayout._subplots.cartesian;
var i, sp, xa, ya;
if (hasSplom) {
Registry.subplotsRegistry.splom.drag(gd);
}
if (hasScatterGl) {
for (i = 0; i < subplots.length; i++) {
sp = plotinfos[subplots[i]];
xa = sp.xaxis;
ya = sp.yaxis;
if (sp._scene) {
if (xa.limitRange) xa.limitRange();
if (ya.limitRange) ya.limitRange();
var xrng = Lib.simpleMap(xa.range, xa.r2l);
var yrng = Lib.simpleMap(ya.range, ya.r2l);
sp._scene.update({
range: [xrng[0], yrng[0], xrng[1], yrng[1]]
});
}
}
}
if (hasSplom || hasScatterGl) {
clearGlCanvases(gd);
redrawReglTraces(gd);
}
if (hasSVG) {
var xScaleFactor = viewBox[2] / xa0._length;
var yScaleFactor = viewBox[3] / ya0._length;
for (i = 0; i < subplots.length; i++) {
sp = plotinfos[subplots[i]];
xa = sp.xaxis;
ya = sp.yaxis;
var editX2 = (editX || matches.isSubplotConstrained) && !xa.fixedrange && xaHash[xa._id];
var editY2 = (editY || matches.isSubplotConstrained) && !ya.fixedrange && yaHash[ya._id];
var xScaleFactor2, yScaleFactor2;
var clipDx, clipDy;
if (editX2) {
xScaleFactor2 = xScaleFactor;
clipDx = ew || matches.isSubplotConstrained ? viewBox[0] : getShift(xa, xScaleFactor2);
} else if (matches.xaHash[xa._id]) {
xScaleFactor2 = xScaleFactor;
clipDx = viewBox[0] * xa._length / xa0._length;
} else if (matches.yaHash[xa._id]) {
xScaleFactor2 = yScaleFactor;
clipDx = yActive === 'ns' ? -viewBox[1] * xa._length / ya0._length : getShift(xa, xScaleFactor2, {
n: 'top',
s: 'bottom'
}[yActive]);
} else {
xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor);
clipDx = scaleAndGetShift(xa, xScaleFactor2);
}
if (xScaleFactor2 > 1 && (xa.maxallowed !== undefined && editX === (xa.range[0] < xa.range[1] ? 'e' : 'w') || xa.minallowed !== undefined && editX === (xa.range[0] < xa.range[1] ? 'w' : 'e'))) {
xScaleFactor2 = 1;
clipDx = 0;
}
if (editY2) {
yScaleFactor2 = yScaleFactor;
clipDy = ns || matches.isSubplotConstrained ? viewBox[1] : getShift(ya, yScaleFactor2);
} else if (matches.yaHash[ya._id]) {
yScaleFactor2 = yScaleFactor;
clipDy = viewBox[1] * ya._length / ya0._length;
} else if (matches.xaHash[ya._id]) {
yScaleFactor2 = xScaleFactor;
clipDy = xActive === 'ew' ? -viewBox[0] * ya._length / xa0._length : getShift(ya, yScaleFactor2, {
e: 'right',
w: 'left'
}[xActive]);
} else {
yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor);
clipDy = scaleAndGetShift(ya, yScaleFactor2);
}
if (yScaleFactor2 > 1 && (ya.maxallowed !== undefined && editY === (ya.range[0] < ya.range[1] ? 'n' : 's') || ya.minallowed !== undefined && editY === (ya.range[0] < ya.range[1] ? 's' : 'n'))) {
yScaleFactor2 = 1;
clipDy = 0;
}
// don't scale at all if neither axis is scalable here
if (!xScaleFactor2 && !yScaleFactor2) {
continue;
}
// but if only one is, reset the other axis scaling
if (!xScaleFactor2) xScaleFactor2 = 1;
if (!yScaleFactor2) yScaleFactor2 = 1;
var plotDx = xa._offset - clipDx / xScaleFactor2;
var plotDy = ya._offset - clipDy / yScaleFactor2;
// TODO could be more efficient here:
// setTranslate and setScale do a lot of extra work
// when working independently, should perhaps combine
// them into a single routine.
sp.clipRect.call(Drawing.setTranslate, clipDx, clipDy).call(Drawing.setScale, xScaleFactor2, yScaleFactor2);
sp.plot.call(Drawing.setTranslate, plotDx, plotDy).call(Drawing.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2);
// apply an inverse scale to individual points to counteract
// the scale of the trace group.
// apply only when scale changes, as adjusting the scale of
// all the points can be expansive.
if (xScaleFactor2 !== sp.xScaleFactor || yScaleFactor2 !== sp.yScaleFactor) {
Drawing.setPointGroupScale(sp.zoomScalePts, xScaleFactor2, yScaleFactor2);
Drawing.setTextPointsScale(sp.zoomScaleTxt, xScaleFactor2, yScaleFactor2);
}
Drawing.hideOutsideRangePoints(sp.clipOnAxisFalseTraces, sp);
// update x/y scaleFactor stash
sp.xScaleFactor = xScaleFactor2;
sp.yScaleFactor = yScaleFactor2;
}
}
}
// Find the appropriate scaling for this axis, if it's linked to the
// dragged axes by constraints. 0 is special, it means this axis shouldn't
// ever be scaled (will be converted to 1 if the other axis is scaled)
function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) {
if (ax.fixedrange) return 0;
if (editX && links.xaHash[ax._id]) {
return xScaleFactor;
}
if (editY && (links.isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) {
return yScaleFactor;
}
return 0;
}
function scaleAndGetShift(ax, scaleFactor) {
if (scaleFactor) {
ax.range = ax._r.slice();
scaleZoom(ax, scaleFactor);
return getShift(ax, scaleFactor);
}
return 0;
}
function getShift(ax, scaleFactor, from) {
return ax._length * (1 - scaleFactor) * FROM_TL[from || ax.constraintoward || 'middle'];
}
return dragger;
}
function makeDragger(plotinfo, nodeName, dragClass, cursor) {
var dragger3 = Lib.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function (s) {
s.classed('drag', true).style({
fill: 'transparent',
'stroke-width': 0
}).attr('data-subplot', plotinfo.id);
});
dragger3.call(setCursor, cursor);
return dragger3.node();
}
function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) {
var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor);
d3.select(dragger).call(Drawing.setRect, x, y, w, h);
return dragger;
}
function isDirectionActive(axList, activeVal) {
for (var i = 0; i < axList.length; i++) {
if (!axList[i].fixedrange) return activeVal;
}
return '';
}
function getEndText(ax, end) {
var initialVal = ax.range[end];
var diff = Math.abs(initialVal - ax.range[1 - end]);
var dig;
// TODO: this should basically be ax.r2d but we're doing extra
// rounding here... can we clean up at all?
if (ax.type === 'date') {
return initialVal;
} else if (ax.type === 'log') {
dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
return numberFormat('.' + dig + 'g')(Math.pow(10, initialVal));
} else {
// linear numeric (or category... but just show numbers here)
dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - Math.floor(Math.log(diff) / Math.LN10) + 4;
return numberFormat('.' + String(dig) + 'g')(initialVal);
}
}
function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) {
for (var i = 0; i < axList.length; i++) {
var axi = axList[i];
if (axi.fixedrange) continue;
if (axi.rangebreaks) {
var isY = axi._id.charAt(0) === 'y';
var r0F = isY ? 1 - r0Fraction : r0Fraction;
var r1F = isY ? 1 - r1Fraction : r1Fraction;
updates[axi._name + '.range[0]'] = axi.l2r(axi.p2l(r0F * axi._length));
updates[axi._name + '.range[1]'] = axi.l2r(axi.p2l(r1F * axi._length));
} else {
var axRangeLinear0 = axi._rl[0];
var axRangeLinearSpan = axi._rl[1] - axRangeLinear0;
updates[axi._name + '.range[0]'] = axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction);
updates[axi._name + '.range[1]'] = axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction);
}
}
// zoom linked axes about their centers
if (linkedAxes && linkedAxes.length) {
var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2;
zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates, []);
}
}
function dragAxList(axList, pix) {
for (var i = 0; i < axList.length; i++) {
var axi = axList[i];
if (!axi.fixedrange) {
if (axi.rangebreaks) {
var p0 = 0;
var p1 = axi._length;
var d0 = axi.p2l(p0 + pix) - axi.p2l(p0);
var d1 = axi.p2l(p1 + pix) - axi.p2l(p1);
var delta = (d0 + d1) / 2;
axi.range = [axi.l2r(axi._rl[0] - delta), axi.l2r(axi._rl[1] - delta)];
} else {
axi.range = [axi.l2r(axi._rl[0] - pix / axi._m), axi.l2r(axi._rl[1] - pix / axi._m)];
}
if (axi.limitRange) axi.limitRange();
}
}
}
// common transform for dragging one end of an axis
// d>0 is compressing scale (cursor is over the plot,
// the axis end should move with the cursor)
// d<0 is expanding (cursor is off the plot, axis end moves
// nonlinearly so you can expand far)
function dZoom(d) {
return 1 - (d >= 0 ? Math.min(d, 0.9) : 1 / (1 / Math.max(d, -0.3) + 3.222));
}
function getDragCursor(nsew, dragmode, isMainDrag) {
if (!nsew) return 'pointer';
if (nsew === 'nsew') {
// in this case here, clear cursor and
// use the cursor style set on
if (isMainDrag) return '';
if (dragmode === 'pan') return 'move';
return 'crosshair';
}
return nsew.toLowerCase() + '-resize';
}
function makeZoombox(zoomlayer, lum, xs, ys, path0) {
return zoomlayer.append('path').attr('class', 'zoombox').style({
fill: lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
'stroke-width': 0
}).attr('transform', strTranslate(xs, ys)).attr('d', path0 + 'Z');
}
function makeCorners(zoomlayer, xs, ys) {
return zoomlayer.append('path').attr('class', 'zoombox-corners').style({
fill: Color.background,
stroke: Color.defaultLine,
'stroke-width': 1,
opacity: 0
}).attr('transform', strTranslate(xs, ys)).attr('d', 'M0,0Z');
}
function updateZoombox(zb, corners, box, path0, dimmed, lum) {
zb.attr('d', path0 + 'M' + box.l + ',' + box.t + 'v' + box.h + 'h' + box.w + 'v-' + box.h + 'h-' + box.w + 'Z');
transitionZoombox(zb, corners, dimmed, lum);
}
function transitionZoombox(zb, corners, dimmed, lum) {
if (!dimmed) {
zb.transition().style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : 'rgba(255,255,255,0.3)').duration(200);
corners.transition().style('opacity', 1).duration(200);
}
}
function removeZoombox(gd) {
d3.select(gd).selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners').remove();
}
function showDoubleClickNotifier(gd) {
if (SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
Lib.notifier(Lib._(gd, 'Double-click to zoom back out'), 'long');
SHOWZOOMOUTTIP = false;
}
}
function xCorners(box, y0) {
return 'M' + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z';
}
function yCorners(box, x0) {
return 'M' + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z';
}
function xyCorners(box) {
var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2);
return 'M' + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + -clen + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + -clen + 'h' + -clen + 'v-3h' + (clen + 3) + 'ZM' + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + 'h' + -clen + 'v3h' + (clen + 3) + 'ZM' + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + 'h' + clen + 'v3h-' + (clen + 3) + 'Z';
}
function calcLinks(gd, groups, xaHash, yaHash, exclude) {
var isSubplotConstrained = false;
var xLinks = {};
var yLinks = {};
var xID, yID, xLinkID, yLinkID;
var xExclude = (exclude || {}).xaHash;
var yExclude = (exclude || {}).yaHash;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
// check if any of the x axes we're dragging is in this constraint group
for (xID in xaHash) {
if (group[xID]) {
// put the rest of these axes into xLinks, if we're not already
// dragging them, so we know to scale these axes automatically too
// to match the changes in the dragged x axes
for (xLinkID in group) {
if (!(exclude && (xExclude[xLinkID] || yExclude[xLinkID])) && !(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) {
xLinks[xLinkID] = xID;
}
}
// check if the x and y axes of THIS drag are linked
for (yID in yaHash) {
if (!(exclude && (xExclude[yID] || yExclude[yID])) && group[yID]) {
isSubplotConstrained = true;
}
}
}
}
// now check if any of the y axes we're dragging is in this constraint group
// only look for outside links, as we've already checked for links within the dragger
for (yID in yaHash) {
if (group[yID]) {
for (yLinkID in group) {
if (!(exclude && (xExclude[yLinkID] || yExclude[yLinkID])) && !(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) {
yLinks[yLinkID] = yID;
}
}
}
}
}
if (isSubplotConstrained) {
// merge xLinks and yLinks if the subplot is constrained,
// since we'll always apply both anyway and the two will contain
// duplicates
Lib.extendFlat(xLinks, yLinks);
yLinks = {};
}
var xaHashLinked = {};
var xaxesLinked = [];
for (xLinkID in xLinks) {
var xa = getFromId(gd, xLinkID);
xaxesLinked.push(xa);
xaHashLinked[xa._id] = xa;
}
var yaHashLinked = {};
var yaxesLinked = [];
for (yLinkID in yLinks) {
var ya = getFromId(gd, yLinkID);
yaxesLinked.push(ya);
yaHashLinked[ya._id] = ya;
}
return {
xaHash: xaHashLinked,
yaHash: yaHashLinked,
xaxes: xaxesLinked,
yaxes: yaxesLinked,
xLinks: xLinks,
yLinks: yLinks,
isSubplotConstrained: isSubplotConstrained
};
}
// still seems to be some confusion about onwheel vs onmousewheel...
function attachWheelEventHandler(element, handler) {
if (!supportsPassive) {
if (element.onwheel !== undefined) element.onwheel = handler;else if (element.onmousewheel !== undefined) element.onmousewheel = handler;else if (!element.isAddedWheelEvent) {
element.isAddedWheelEvent = true;
element.addEventListener('wheel', handler, {
passive: false
});
}
} else {
var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel';
if (element._onwheel) {
element.removeEventListener(wheelEventName, element._onwheel);
}
element._onwheel = handler;
element.addEventListener(wheelEventName, handler, {
passive: false
});
}
}
function hashValues(hash) {
var out = [];
for (var k in hash) out.push(hash[k]);
return out;
}
module.exports = {
makeDragBox: makeDragBox,
makeDragger: makeDragger,
makeRectDragger: makeRectDragger,
makeZoombox: makeZoombox,
makeCorners: makeCorners,
updateZoombox: updateZoombox,
xyCorners: xyCorners,
transitionZoombox: transitionZoombox,
removeZoombox: removeZoombox,
showDoubleClickNotifier: showDoubleClickNotifier,
attachWheelEventHandler: attachWheelEventHandler
};
/***/ }),
/***/ 42464:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Fx = __webpack_require__(93024);
var dragElement = __webpack_require__(86476);
var setCursor = __webpack_require__(93972);
var makeDragBox = (__webpack_require__(51184).makeDragBox);
var DRAGGERSIZE = (__webpack_require__(33816).DRAGGERSIZE);
exports.initInteractions = function initInteractions(gd) {
var fullLayout = gd._fullLayout;
if (gd._context.staticPlot) {
// this sweeps up more than just cartesian drag elements...
d3.select(gd).selectAll('.drag').remove();
return;
}
if (!fullLayout._has('cartesian') && !fullLayout._has('splom')) return;
var subplots = Object.keys(fullLayout._plots || {}).sort(function (a, b) {
// sort overlays last, then by x axis number, then y axis number
if ((fullLayout._plots[a].mainplot && true) === (fullLayout._plots[b].mainplot && true)) {
var aParts = a.split('y');
var bParts = b.split('y');
return aParts[0] === bParts[0] ? Number(aParts[1] || 1) - Number(bParts[1] || 1) : Number(aParts[0] || 1) - Number(bParts[0] || 1);
}
return fullLayout._plots[a].mainplot ? 1 : -1;
});
subplots.forEach(function (subplot) {
var plotinfo = fullLayout._plots[subplot];
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
// main and corner draggers need not be repeated for
// overlaid subplots - these draggers drag them all
if (!plotinfo.mainplot) {
// main dragger goes over the grids and data, so we use its
// mousemove events for all data hover effects
var maindrag = makeDragBox(gd, plotinfo, xa._offset, ya._offset, xa._length, ya._length, 'ns', 'ew');
maindrag.onmousemove = function (evt) {
// This is on `gd._fullLayout`, *not* fullLayout because the reference
// changes by the time this is called again.
gd._fullLayout._rehover = function () {
if (gd._fullLayout._hoversubplot === subplot && gd._fullLayout._plots[subplot]) {
Fx.hover(gd, evt, subplot);
}
};
Fx.hover(gd, evt, subplot);
// Note that we have *not* used the cached fullLayout variable here
// since that may be outdated when this is called as a callback later on
gd._fullLayout._lasthover = maindrag;
gd._fullLayout._hoversubplot = subplot;
};
/*
* IMPORTANT:
* We must check for the presence of the drag cover here.
* If we don't, a 'mouseout' event is triggered on the
* maindrag before each 'click' event, which has the effect
* of clearing the hoverdata; thus, cancelling the click event.
*/
maindrag.onmouseout = function (evt) {
if (gd._dragging) return;
// When the mouse leaves this maindrag, unset the hovered subplot.
// This may cause problems if it leaves the subplot directly *onto*
// another subplot, but that's a tiny corner case at the moment.
gd._fullLayout._hoversubplot = null;
dragElement.unhover(gd, evt);
};
// corner draggers
if (gd._context.showAxisDragHandles) {
makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
}
}
if (gd._context.showAxisDragHandles) {
// x axis draggers - if you have overlaid plots,
// these drag each axis separately
if (subplot === xa._mainSubplot) {
// the y position of the main x axis line
var y0 = xa._mainLinePosition;
if (xa.side === 'top') y0 -= DRAGGERSIZE;
makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.1, y0, xa._length * 0.8, DRAGGERSIZE, '', 'ew');
makeDragBox(gd, plotinfo, xa._offset, y0, xa._length * 0.1, DRAGGERSIZE, '', 'w');
makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.9, y0, xa._length * 0.1, DRAGGERSIZE, '', 'e');
}
// y axis draggers
if (subplot === ya._mainSubplot) {
// the x position of the main y axis line
var x0 = ya._mainLinePosition;
if (ya.side !== 'right') x0 -= DRAGGERSIZE;
makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.1, DRAGGERSIZE, ya._length * 0.8, 'ns', '');
makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.9, DRAGGERSIZE, ya._length * 0.1, 's', '');
makeDragBox(gd, plotinfo, x0, ya._offset, DRAGGERSIZE, ya._length * 0.1, 'n', '');
}
}
});
// In case you mousemove over some hovertext, send it to Fx.hover too
// we do this so that we can put the hover text in front of everything,
// but still be able to interact with everything as if it isn't there
var hoverLayer = fullLayout._hoverlayer.node();
hoverLayer.onmousemove = function (evt) {
evt.target = gd._fullLayout._lasthover;
Fx.hover(gd, evt, fullLayout._hoversubplot);
};
hoverLayer.onclick = function (evt) {
evt.target = gd._fullLayout._lasthover;
Fx.click(gd, evt);
};
// also delegate mousedowns... TODO: does this actually work?
hoverLayer.onmousedown = function (evt) {
gd._fullLayout._lasthover.onmousedown(evt);
};
exports.updateFx(gd);
};
// Minimal set of update needed on 'modebar' edits.
// We only need to update the cursor style.
//
// Note that changing the axis configuration and/or the fixedrange attribute
// should trigger a full initInteractions.
exports.updateFx = function (gd) {
var fullLayout = gd._fullLayout;
var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
setCursor(fullLayout._draggers, cursor);
};
/***/ }),
/***/ 36632:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var axisIds = __webpack_require__(79811);
/**
* Factory function for checking component arrays for subplot references.
*
* @param {string} containerArrayName: the top-level array in gd.layout to check
* If an item in this container is found that references a cartesian x and/or y axis,
* ensure cartesian is marked as a base plot module and record the axes (and subplot
* if both refs are axes) in gd._fullLayout
*
* @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout)
* as expected of a component includeBasePlot method
*/
module.exports = function makeIncludeComponents(containerArrayName) {
return function includeComponents(layoutIn, layoutOut) {
var array = layoutIn[containerArrayName];
if (!Array.isArray(array)) return;
var Cartesian = Registry.subplotsRegistry.cartesian;
var idRegex = Cartesian.idRegex;
var subplots = layoutOut._subplots;
var xaList = subplots.xaxis;
var yaList = subplots.yaxis;
var cartesianList = subplots.cartesian;
var hasCartesianOrGL2D = layoutOut._has('cartesian') || layoutOut._has('gl2d');
for (var i = 0; i < array.length; i++) {
var itemi = array[i];
if (!Lib.isPlainObject(itemi)) continue;
// call cleanId because if xref, or yref has something appended
// (e.g., ' domain') this will get removed.
var xref = axisIds.cleanId(itemi.xref, 'x', false);
var yref = axisIds.cleanId(itemi.yref, 'y', false);
var hasXref = idRegex.x.test(xref);
var hasYref = idRegex.y.test(yref);
if (hasXref || hasYref) {
if (!hasCartesianOrGL2D) Lib.pushUnique(layoutOut._basePlotModules, Cartesian);
var newAxis = false;
if (hasXref && xaList.indexOf(xref) === -1) {
xaList.push(xref);
newAxis = true;
}
if (hasYref && yaList.indexOf(yref) === -1) {
yaList.push(yref);
newAxis = true;
}
/*
* Notice the logic here: only add a subplot for a component if
* it's referencing both x and y axes AND it's creating a new axis
* so for example if your plot already has xy and x2y2, an annotation
* on x2y or xy2 will not create a new subplot.
*/
if (newAxis && hasXref && hasYref) {
cartesianList.push(xref + yref);
}
}
}
};
};
/***/ }),
/***/ 57952:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var Plots = __webpack_require__(7316);
var Drawing = __webpack_require__(43616);
var getModuleCalcData = (__webpack_require__(84888)/* .getModuleCalcData */ ._M);
var axisIds = __webpack_require__(79811);
var constants = __webpack_require__(33816);
var xmlnsNamespaces = __webpack_require__(9616);
var ensureSingle = Lib.ensureSingle;
function ensureSingleAndAddDatum(parent, nodeType, className) {
return Lib.ensureSingle(parent, nodeType, className, function (s) {
s.datum(className);
});
}
var zindexSeparator = constants.zindexSeparator;
exports.name = 'cartesian';
exports.attr = ['xaxis', 'yaxis'];
exports.idRoot = ['x', 'y'];
exports.idRegex = constants.idRegex;
exports.attrRegex = constants.attrRegex;
exports.attributes = __webpack_require__(26720);
exports.layoutAttributes = __webpack_require__(94724);
exports.supplyLayoutDefaults = __webpack_require__(67352);
exports.transitionAxes = __webpack_require__(73736);
exports.finalizeSubplots = function (layoutIn, layoutOut) {
var subplots = layoutOut._subplots;
var xList = subplots.xaxis;
var yList = subplots.yaxis;
var spSVG = subplots.cartesian;
var spAll = spSVG.concat(subplots.gl2d || []);
var allX = {};
var allY = {};
var i, xi, yi;
for (i = 0; i < spAll.length; i++) {
var parts = spAll[i].split('y');
allX[parts[0]] = 1;
allY['y' + parts[1]] = 1;
}
// check for x axes with no subplot, and make one from the anchor of that x axis
for (i = 0; i < xList.length; i++) {
xi = xList[i];
if (!allX[xi]) {
yi = (layoutIn[axisIds.id2name(xi)] || {}).anchor;
if (!constants.idRegex.y.test(yi)) yi = 'y';
spSVG.push(xi + yi);
spAll.push(xi + yi);
if (!allY[yi]) {
allY[yi] = 1;
Lib.pushUnique(yList, yi);
}
}
}
// same for y axes with no subplot
for (i = 0; i < yList.length; i++) {
yi = yList[i];
if (!allY[yi]) {
xi = (layoutIn[axisIds.id2name(yi)] || {}).anchor;
if (!constants.idRegex.x.test(xi)) xi = 'x';
spSVG.push(xi + yi);
spAll.push(xi + yi);
if (!allX[xi]) {
allX[xi] = 1;
Lib.pushUnique(xList, xi);
}
}
}
// finally, if we've gotten here we're supposed to show cartesian...
// so if there are NO subplots at all, make one from the first
// x & y axes in the input layout
if (!spAll.length) {
xi = '';
yi = '';
for (var ki in layoutIn) {
if (constants.attrRegex.test(ki)) {
var axLetter = ki.charAt(0);
if (axLetter === 'x') {
if (!xi || +ki.substr(5) < +xi.substr(5)) {
xi = ki;
}
} else if (!yi || +ki.substr(5) < +yi.substr(5)) {
yi = ki;
}
}
}
xi = xi ? axisIds.name2id(xi) : 'x';
yi = yi ? axisIds.name2id(yi) : 'y';
xList.push(xi);
yList.push(yi);
spSVG.push(xi + yi);
}
};
/**
* Cartesian.plot
*
* @param {DOM div | object} gd
* @param {array (optional)} traces
* array of traces indices to plot
* if undefined, plots all cartesian traces,
* @param {object} (optional) transitionOpts
* transition option object
* @param {function} (optional) makeOnCompleteCallback
* transition make callback function from Plots.transition
*/
exports.plot = function (gd, traces, transitionOpts, makeOnCompleteCallback) {
var fullLayout = gd._fullLayout;
var subplots = fullLayout._subplots.cartesian;
var calcdata = gd.calcdata;
var i;
// Traces is a list of trace indices to (re)plot. If it's not provided,
// then it's a complete replot so we create a new list and add all trace indices
// which are in calcdata.
if (!Array.isArray(traces)) {
// If traces is not provided, then it's a complete replot and missing
// traces are removed
traces = [];
for (i = 0; i < calcdata.length; i++) traces.push(i);
}
var zindices = fullLayout._zindices;
// Plot each zorder group in ascending order
for (var z = 0; z < zindices.length; z++) {
var zorder = zindices[z];
// For each subplot
for (i = 0; i < subplots.length; i++) {
var subplot = subplots[i];
var subplotInfo = fullLayout._plots[subplot];
if (z > 0) {
var idWithZ = subplotInfo.id;
if (idWithZ.indexOf(zindexSeparator) !== -1) continue;
idWithZ += zindexSeparator + (z + 1);
subplotInfo = Lib.extendFlat({}, subplotInfo, {
id: idWithZ,
plot: fullLayout._cartesianlayer.selectAll('.subplot').select('.' + idWithZ)
});
}
// Get all calcdata (traces) for this subplot:
var cdSubplot = [];
var pcd;
// For each trace
for (var j = 0; j < calcdata.length; j++) {
var cd = calcdata[j];
var trace = cd[0].trace;
if (zorder !== (trace.zorder || 0)) continue;
// Skip trace if whitelist provided and it's not whitelisted:
// if (Array.isArray(traces) && traces.indexOf(i) === -1) continue;
if (trace.xaxis + trace.yaxis === subplot) {
// XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet
// axis has actually changed:
//
// If this trace is specifically requested, add it to the list:
if (traces.indexOf(trace.index) !== -1 || trace.carpet) {
// Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate
// traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill
// is outdated. So this retroactively adds the previous trace if the
// traces are interdependent.
if (pcd && pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && cdSubplot.indexOf(pcd) === -1) {
cdSubplot.push(pcd);
}
cdSubplot.push(cd);
}
// Track the previous trace on this subplot for the retroactive-add step
// above:
pcd = cd;
}
}
// Plot the traces for this subplot
plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback);
}
}
};
function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) {
var traceLayerClasses = constants.traceLayerClasses;
var fullLayout = gd._fullLayout;
var zindices = fullLayout._zindices;
var modules = fullLayout._modules;
var _module, cdModuleAndOthers, cdModule;
var layerData = [];
var zoomScaleQueryParts = [];
// Plot each zorder group in ascending order
for (var z = 0; z < zindices.length; z++) {
var zorder = zindices[z];
// For each "module" (trace type)
for (var i = 0; i < modules.length; i++) {
_module = modules[i];
var name = _module.name;
var categories = Registry.modules[name].categories;
if (categories.svg) {
var classBaseName = _module.layerName || name + 'layer';
var className = classBaseName + (z ? Number(z) + 1 : '');
var plotMethod = _module.plot;
// plot all visible traces of this type on this subplot at once
cdModuleAndOthers = getModuleCalcData(cdSubplot, plotMethod, zorder);
cdModule = cdModuleAndOthers[0];
// don't need to search the found traces again - in fact we need to NOT
// so that if two modules share the same plotter we don't double-plot
cdSubplot = cdModuleAndOthers[1];
if (cdModule.length) {
layerData.push({
i: traceLayerClasses.indexOf(classBaseName),
zorder: z,
className: className,
plotMethod: plotMethod,
cdModule: cdModule
});
}
if (categories.zoomScale) {
zoomScaleQueryParts.push('.' + className);
}
}
}
}
// Sort the layers primarily by z, then by i
layerData.sort(function (a, b) {
return (a.zorder || 0) - (b.zorder || 0) || a.i - b.i;
});
var layers = plotinfo.plot.selectAll('g.mlayer').data(layerData, function (d) {
return d.className;
});
layers.enter().append('g').attr('class', function (d) {
return d.className;
}).classed('mlayer', true).classed('rangeplot', plotinfo.isRangePlot);
layers.exit().remove();
layers.order();
layers.each(function (d) {
var sel = d3.select(this);
var className = d.className;
d.plotMethod(gd, plotinfo, d.cdModule, sel, transitionOpts, makeOnCompleteCallback);
// layers that allow `cliponaxis: false`
if (constants.clipOnAxisFalseQuery.indexOf('.' + className) === -1) {
Drawing.setClipUrl(sel, plotinfo.layerClipId, gd);
}
});
// call Scattergl.plot separately
if (fullLayout._has('scattergl')) {
_module = Registry.getModule('scattergl');
cdModule = getModuleCalcData(cdSubplot, _module)[0];
_module.plot(gd, plotinfo, cdModule);
}
// stash "hot" selections for faster interaction on drag and scroll
if (!gd._context.staticPlot) {
if (plotinfo._hasClipOnAxisFalse) {
plotinfo.clipOnAxisFalseTraces = plotinfo.plot.selectAll(constants.clipOnAxisFalseQuery.join(',')).selectAll('.trace');
}
if (zoomScaleQueryParts.length) {
var traces = plotinfo.plot.selectAll(zoomScaleQueryParts.join(',')).selectAll('.trace');
plotinfo.zoomScalePts = traces.selectAll('path.point');
plotinfo.zoomScaleTxt = traces.selectAll('.textpoint');
}
}
}
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldPlots = oldFullLayout._plots || {};
var newPlots = newFullLayout._plots || {};
var oldSubplotList = oldFullLayout._subplots || {};
var plotinfo;
var i, k;
// when going from a large splom graph to something else,
// we need to clear so that the new cartesian subplot
// can have the correct layer ordering
if (oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) {
for (k in oldPlots) {
plotinfo = oldPlots[k];
if (plotinfo.plotgroup) plotinfo.plotgroup.remove();
}
}
var hadGl = oldFullLayout._has && oldFullLayout._has('gl');
var hasGl = newFullLayout._has && newFullLayout._has('gl');
if (hadGl && !hasGl) {
for (k in oldPlots) {
plotinfo = oldPlots[k];
if (plotinfo._scene) plotinfo._scene.destroy();
}
}
// delete any titles we don't need anymore
// check if axis list has changed, and if so clear old titles
if (oldSubplotList.xaxis && oldSubplotList.yaxis) {
var oldAxIDs = axisIds.listIds({
_fullLayout: oldFullLayout
});
for (i = 0; i < oldAxIDs.length; i++) {
var oldAxId = oldAxIDs[i];
if (!newFullLayout[axisIds.id2name(oldAxId)]) {
oldFullLayout._infolayer.selectAll('.g-' + oldAxId + 'title').remove();
}
}
}
var hadCartesian = oldFullLayout._has && oldFullLayout._has('cartesian');
var hasCartesian = newFullLayout._has && newFullLayout._has('cartesian');
if (hadCartesian && !hasCartesian) {
// if we've gotten rid of all cartesian traces, remove all the subplot svg items
purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout);
oldFullLayout._defs.selectAll('.axesclip').remove();
delete oldFullLayout._axisConstraintGroups;
delete oldFullLayout._axisMatchGroups;
} else if (oldSubplotList.cartesian) {
// otherwise look for subplots we need to remove
for (i = 0; i < oldSubplotList.cartesian.length; i++) {
var oldSubplotId = oldSubplotList.cartesian[i];
// skip zindex layes in this process
if (oldSubplotId.indexOf(zindexSeparator) !== -1) continue;
if (!newPlots[oldSubplotId]) {
var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y';
oldFullLayout._cartesianlayer.selectAll(selector).remove();
removeSubplotExtras(oldSubplotId, oldFullLayout);
}
}
}
};
exports.drawFramework = function (gd) {
var fullLayout = gd._fullLayout;
var calcdata = gd.calcdata;
var i;
// Separate traces by zorder and plot each zorder group separately
var traceZorderGroups = {};
for (i = 0; i < calcdata.length; i++) {
var cdi = calcdata[i][0];
var trace = cdi.trace;
var zi = trace.zorder || 0;
if (!traceZorderGroups[zi]) traceZorderGroups[zi] = [];
traceZorderGroups[zi].push(cdi);
}
// Group by zorder group in ascending order
var zindices = Object.keys(traceZorderGroups).map(Number).sort(Lib.sorterAsc);
if (!zindices.length) zindices = [0];
fullLayout._zindices = zindices;
var initialSubplotData = makeSubplotData(gd);
var len = initialSubplotData.length;
var subplotData = [];
for (i = 0; i < len; i++) {
subplotData[i] = initialSubplotData[i].slice();
}
for (var z = 1; z < zindices.length; z++) {
var newSubplotData = [];
for (i = 0; i < len; i++) {
newSubplotData[i] = initialSubplotData[i].slice();
newSubplotData[i][0] += zindexSeparator + (z + 1);
}
subplotData = subplotData.concat(newSubplotData);
}
var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot').data(subplotData, String);
subplotLayers.enter().append('g').attr('class', function (d) {
return 'subplot ' + d[0];
});
subplotLayers.order();
subplotLayers.exit().call(purgeSubplotLayers, fullLayout);
subplotLayers.each(function (d) {
var id = d[0];
var posZ = id.indexOf(zindexSeparator);
var hasZ = posZ !== -1;
var idWithoutZ = hasZ ? id.slice(0, posZ) : id;
var plotinfo = fullLayout._plots[id];
if (!plotinfo) {
plotinfo = Lib.extendFlat({}, fullLayout._plots[idWithoutZ]);
if (plotinfo) {
plotinfo.id = id;
fullLayout._plots[id] = plotinfo;
fullLayout._subplots.cartesian.push(id);
}
}
if (plotinfo) {
plotinfo.plotgroup = d3.select(this);
makeSubplotLayer(gd, plotinfo);
if (!hasZ) {
// make separate drag layers for each subplot,
// but append them to paper rather than the plot groups,
// so they end up on top of the rest
plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', id);
}
}
});
};
exports.rangePlot = function (gd, plotinfo, cdSubplot) {
makeSubplotLayer(gd, plotinfo);
plotOne(gd, plotinfo, cdSubplot);
Plots.style(gd);
};
function makeSubplotData(gd) {
var fullLayout = gd._fullLayout;
var numZ = fullLayout._zindices.length;
var ids = fullLayout._subplots.cartesian;
var len = ids.length;
var i, j, id, plotinfo, xa, ya;
// split 'regular' and 'overlaying' subplots
var regulars = [];
var overlays = [];
for (i = 0; i < len; i++) {
id = ids[i];
plotinfo = fullLayout._plots[id];
xa = plotinfo.xaxis;
ya = plotinfo.yaxis;
var xa2 = xa._mainAxis;
var ya2 = ya._mainAxis;
var mainplot = xa2._id + ya2._id;
var mainplotinfo = fullLayout._plots[mainplot];
plotinfo.overlays = [];
if (mainplot !== id && mainplotinfo) {
plotinfo.mainplot = mainplot;
plotinfo.mainplotinfo = mainplotinfo;
overlays.push(id);
} else {
plotinfo.mainplot = undefined;
plotinfo.mainplotinfo = undefined;
regulars.push(id);
}
}
// fill in list of overlaying subplots in 'main plot'
for (i = 0; i < overlays.length; i++) {
id = overlays[i];
plotinfo = fullLayout._plots[id];
plotinfo.mainplotinfo.overlays.push(plotinfo);
}
// put 'regular' subplot data before 'overlaying'
var subplotIds = regulars.concat(overlays);
var subplotData = [];
for (i = 0; i < len; i++) {
id = subplotIds[i];
plotinfo = fullLayout._plots[id];
xa = plotinfo.xaxis;
ya = plotinfo.yaxis;
var d = [];
for (var z = 1; z <= numZ; z++) {
var zStr = '';
if (z > 1) zStr += zindexSeparator + z;
// use info about axis layer and overlaying pattern
// to clean what need to be cleaned up in exit selection
d.push(id + zStr);
for (j = 0; j < plotinfo.overlays.length; j++) {
d.push(plotinfo.overlays[j].id + zStr);
}
}
d = d.concat([xa.layer, ya.layer, xa.overlaying || '', ya.overlaying || '']);
subplotData.push(d);
}
return subplotData;
}
function makeSubplotLayer(gd, plotinfo) {
var plotgroup = plotinfo.plotgroup;
var id = plotinfo.id;
var posZ = id.indexOf(zindexSeparator);
var hasZ = posZ !== -1;
var xLayer = constants.layerValue2layerClass[plotinfo.xaxis.layer];
var yLayer = constants.layerValue2layerClass[plotinfo.yaxis.layer];
var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms;
if (!plotinfo.mainplot) {
if (hasOnlyLargeSploms) {
// TODO could do even better
// - we don't need plot (but we would have to mock it in lsInner
// and other places
// - we don't (x|y)lines and (x|y)axislayer for most subplots
// usually just the bottom x and left y axes.
plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above');
plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above');
} else {
if (!hasZ) {
var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot');
plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer');
plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer');
plotinfo.minorGridlayer = ensureSingle(plotgroup, 'g', 'minor-gridlayer');
plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer');
plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer');
var betweenLayer = ensureSingle(plotgroup, 'g', 'layer-between');
plotinfo.shapelayerBetween = ensureSingle(betweenLayer, 'g', 'shapelayer');
plotinfo.imagelayerBetween = ensureSingle(betweenLayer, 'g', 'imagelayer');
ensureSingle(plotgroup, 'path', 'xlines-below');
ensureSingle(plotgroup, 'path', 'ylines-below');
plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below');
ensureSingle(plotgroup, 'g', 'xaxislayer-below');
ensureSingle(plotgroup, 'g', 'yaxislayer-below');
plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below');
}
plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot');
plotinfo.plot = ensureSingle(plotinfo.overplot, 'g', id);
if (!hasZ) {
plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above');
ensureSingle(plotgroup, 'g', 'xaxislayer-above');
ensureSingle(plotgroup, 'g', 'yaxislayer-above');
plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above');
// set refs to correct layers as determined by 'axis.layer'
plotinfo.xlines = plotgroup.select('.xlines-' + xLayer);
plotinfo.ylines = plotgroup.select('.ylines-' + yLayer);
plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer);
plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer);
}
}
} else {
var mainplotinfo = plotinfo.mainplotinfo;
var mainplotgroup = mainplotinfo.plotgroup;
var xId = id + '-x';
var yId = id + '-y';
// now make the components of overlaid subplots
// overlays don't have backgrounds, and append all
// their other components to the corresponding
// extra groups of their main plots.
plotinfo.minorGridlayer = mainplotinfo.minorGridlayer;
plotinfo.gridlayer = mainplotinfo.gridlayer;
plotinfo.zerolinelayer = mainplotinfo.zerolinelayer;
ensureSingle(mainplotinfo.overlinesBelow, 'path', xId);
ensureSingle(mainplotinfo.overlinesBelow, 'path', yId);
ensureSingle(mainplotinfo.overaxesBelow, 'g', xId);
ensureSingle(mainplotinfo.overaxesBelow, 'g', yId);
plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id);
ensureSingle(mainplotinfo.overlinesAbove, 'path', xId);
ensureSingle(mainplotinfo.overlinesAbove, 'path', yId);
ensureSingle(mainplotinfo.overaxesAbove, 'g', xId);
ensureSingle(mainplotinfo.overaxesAbove, 'g', yId);
// set refs to correct layers as determined by 'abovetraces'
plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId);
plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId);
plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId);
plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId);
}
if (!hasZ) {
// common attributes for all subplots, overlays or not
if (!hasOnlyLargeSploms) {
ensureSingleAndAddDatum(plotinfo.minorGridlayer, 'g', plotinfo.xaxis._id);
ensureSingleAndAddDatum(plotinfo.minorGridlayer, 'g', plotinfo.yaxis._id);
plotinfo.minorGridlayer.selectAll('g').map(function (d) {
return d[0];
}).sort(axisIds.idSort);
ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id);
ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id);
plotinfo.gridlayer.selectAll('g').map(function (d) {
return d[0];
}).sort(axisIds.idSort);
}
plotinfo.xlines.style('fill', 'none').classed('crisp', true);
plotinfo.ylines.style('fill', 'none').classed('crisp', true);
}
}
function purgeSubplotLayers(layers, fullLayout) {
if (!layers) return;
var overlayIdsToRemove = {};
layers.each(function (d) {
var id = d[0];
var plotgroup = d3.select(this);
plotgroup.remove();
removeSubplotExtras(id, fullLayout);
overlayIdsToRemove[id] = true;
// do not remove individual axis s here
// as other subplots may need them
});
// must remove overlaid subplot trace layers 'manually'
for (var k in fullLayout._plots) {
var subplotInfo = fullLayout._plots[k];
var overlays = subplotInfo.overlays || [];
for (var j = 0; j < overlays.length; j++) {
var overlayInfo = overlays[j];
if (overlayIdsToRemove[overlayInfo.id]) {
overlayInfo.plot.selectAll('.trace').remove();
}
}
}
}
function removeSubplotExtras(subplotId, fullLayout) {
fullLayout._draggers.selectAll('g.' + subplotId).remove();
fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove();
}
exports.toSVG = function (gd) {
var imageRoot = gd._fullLayout._glimages;
var root = d3.select(gd).selectAll('.svg-container');
var canvases = root.filter(function (d, i) {
return i === root.size() - 1;
}).selectAll('.gl-canvas-context, .gl-canvas-focus');
function canvasToImage() {
var canvas = this;
var imageData = canvas.toDataURL('image/png');
var image = imageRoot.append('svg:image');
image.attr({
xmlns: xmlnsNamespaces.svg,
'xlink:href': imageData,
preserveAspectRatio: 'none',
x: 0,
y: 0,
width: canvas.style.width,
height: canvas.style.height
});
}
canvases.each(canvasToImage);
};
exports.updateFx = __webpack_require__(42464).updateFx;
/***/ }),
/***/ 94724:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var colorAttrs = __webpack_require__(22548);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
var templatedArray = (__webpack_require__(31780).templatedArray);
var descriptionWithDates = (__webpack_require__(29736).descriptionWithDates);
var ONEDAY = (__webpack_require__(39032).ONEDAY);
var constants = __webpack_require__(33816);
var HOUR = constants.HOUR_PATTERN;
var DAY_OF_WEEK = constants.WEEKDAY_PATTERN;
var minorTickmode = {
valType: 'enumerated',
values: ['auto', 'linear', 'array'],
editType: 'ticks',
impliedEdits: {
tick0: undefined,
dtick: undefined
}
};
var tickmode = extendFlat({}, minorTickmode, {
values: minorTickmode.values.slice().concat(['sync'])
});
function makeNticks(minor) {
return {
valType: 'integer',
min: 0,
dflt: minor ? 5 : 0,
editType: 'ticks'
};
}
var tick0 = {
valType: 'any',
editType: 'ticks',
impliedEdits: {
tickmode: 'linear'
}
};
var dtick = {
valType: 'any',
editType: 'ticks',
impliedEdits: {
tickmode: 'linear'
}
};
var tickvals = {
valType: 'data_array',
editType: 'ticks'
};
var ticks = {
valType: 'enumerated',
values: ['outside', 'inside', ''],
editType: 'ticks'
};
function makeTicklen(minor) {
var obj = {
valType: 'number',
min: 0,
editType: 'ticks'
};
if (!minor) obj.dflt = 5;
return obj;
}
function makeTickwidth(minor) {
var obj = {
valType: 'number',
min: 0,
editType: 'ticks'
};
if (!minor) obj.dflt = 1;
return obj;
}
var tickcolor = {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'ticks'
};
var gridcolor = {
valType: 'color',
dflt: colorAttrs.lightLine,
editType: 'ticks'
};
function makeGridwidth(minor) {
var obj = {
valType: 'number',
min: 0,
editType: 'ticks'
};
if (!minor) obj.dflt = 1;
return obj;
}
var griddash = extendFlat({}, dash, {
editType: 'ticks'
});
var showgrid = {
valType: 'boolean',
editType: 'ticks'
};
module.exports = {
visible: {
valType: 'boolean',
editType: 'plot'
},
color: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'ticks'
},
title: {
text: {
valType: 'string',
editType: 'ticks'
},
font: fontAttrs({
editType: 'ticks'
}),
standoff: {
valType: 'number',
min: 0,
editType: 'ticks'
},
editType: 'ticks'
},
type: {
valType: 'enumerated',
// '-' means we haven't yet run autotype or couldn't find any data
// it gets turned into linear in gd._fullLayout but not copied back
// to gd.data like the others are.
values: ['-', 'linear', 'log', 'date', 'category', 'multicategory'],
dflt: '-',
editType: 'calc',
// we forget when an axis has been autotyped, just writing the auto
// value back to the input - so it doesn't make sense to template this.
// Note: we do NOT prohibit this in `coerce`, so if someone enters a
// type in the template explicitly it will be honored as the default.
_noTemplating: true
},
autotypenumbers: {
valType: 'enumerated',
values: ['convert types', 'strict'],
dflt: 'convert types',
editType: 'calc'
},
autorange: {
valType: 'enumerated',
values: [true, false, 'reversed', 'min reversed', 'max reversed', 'min', 'max'],
dflt: true,
editType: 'axrange',
impliedEdits: {
'range[0]': undefined,
'range[1]': undefined
}
},
autorangeoptions: {
minallowed: {
valType: 'any',
editType: 'plot',
impliedEdits: {
'range[0]': undefined,
'range[1]': undefined
}
},
maxallowed: {
valType: 'any',
editType: 'plot',
impliedEdits: {
'range[0]': undefined,
'range[1]': undefined
}
},
clipmin: {
valType: 'any',
editType: 'plot',
impliedEdits: {
'range[0]': undefined,
'range[1]': undefined
}
},
clipmax: {
valType: 'any',
editType: 'plot',
impliedEdits: {
'range[0]': undefined,
'range[1]': undefined
}
},
include: {
valType: 'any',
arrayOk: true,
editType: 'plot',
impliedEdits: {
'range[0]': undefined,
'range[1]': undefined
}
},
editType: 'plot'
},
rangemode: {
valType: 'enumerated',
values: ['normal', 'tozero', 'nonnegative'],
dflt: 'normal',
editType: 'plot'
},
range: {
valType: 'info_array',
items: [{
valType: 'any',
editType: 'axrange',
impliedEdits: {
'^autorange': false
},
anim: true
}, {
valType: 'any',
editType: 'axrange',
impliedEdits: {
'^autorange': false
},
anim: true
}],
editType: 'axrange',
impliedEdits: {
autorange: false
},
anim: true
},
minallowed: {
valType: 'any',
editType: 'plot',
impliedEdits: {
'^autorange': false
}
},
maxallowed: {
valType: 'any',
editType: 'plot',
impliedEdits: {
'^autorange': false
}
},
fixedrange: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
insiderange: {
valType: 'info_array',
items: [{
valType: 'any',
editType: 'plot'
}, {
valType: 'any',
editType: 'plot'
}],
editType: 'plot'
},
// scaleanchor: not used directly, just put here for reference
// values are any opposite-letter axis id, or `false`.
scaleanchor: {
valType: 'enumerated',
values: [constants.idRegex.x.toString(), constants.idRegex.y.toString(), false],
editType: 'plot'
},
scaleratio: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'plot'
},
constrain: {
valType: 'enumerated',
values: ['range', 'domain'],
editType: 'plot'
},
// constraintoward: not used directly, just put here for reference
constraintoward: {
valType: 'enumerated',
values: ['left', 'center', 'right', 'top', 'middle', 'bottom'],
editType: 'plot'
},
matches: {
valType: 'enumerated',
values: [constants.idRegex.x.toString(), constants.idRegex.y.toString()],
editType: 'calc'
},
rangebreaks: templatedArray('rangebreak', {
enabled: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
bounds: {
valType: 'info_array',
items: [{
valType: 'any',
editType: 'calc'
}, {
valType: 'any',
editType: 'calc'
}],
editType: 'calc'
},
pattern: {
valType: 'enumerated',
values: [DAY_OF_WEEK, HOUR, ''],
editType: 'calc'
},
values: {
valType: 'info_array',
freeLength: true,
editType: 'calc',
items: {
valType: 'any',
editType: 'calc'
}
},
dvalue: {
// TODO could become 'any' to add support for 'months', 'years'
valType: 'number',
editType: 'calc',
min: 0,
dflt: ONEDAY
},
/*
gap: {
valType: 'number',
min: 0,
dflt: 0, // for *date* axes, maybe something else for *linear*
editType: 'calc',
},
gapmode: {
valType: 'enumerated',
values: ['pixels', 'fraction'],
dflt: 'pixels',
editType: 'calc',
},
*/
// To complete https://github.com/plotly/plotly.js/issues/4210
// we additionally need `gap` and make this work on *linear*, and
// possibly all other cartesian axis types. We possibly would also need
// some style attributes controlling the zig-zag on the corresponding
// axis.
editType: 'calc'
}),
// ticks
tickmode: tickmode,
nticks: makeNticks(),
tick0: tick0,
dtick: dtick,
ticklabelstep: {
valType: 'integer',
min: 1,
dflt: 1,
editType: 'ticks'
},
tickvals: tickvals,
ticktext: {
valType: 'data_array',
editType: 'ticks'
},
ticks: ticks,
tickson: {
valType: 'enumerated',
values: ['labels', 'boundaries'],
dflt: 'labels',
editType: 'ticks'
},
ticklabelmode: {
valType: 'enumerated',
values: ['instant', 'period'],
dflt: 'instant',
editType: 'ticks'
},
// ticklabelposition: not used directly, as values depend on direction (similar to side)
// left/right options are for x axes, and top/bottom options are for y axes
ticklabelposition: {
valType: 'enumerated',
values: ['outside', 'inside', 'outside top', 'inside top', 'outside left', 'inside left', 'outside right', 'inside right', 'outside bottom', 'inside bottom'],
dflt: 'outside',
editType: 'calc'
},
ticklabeloverflow: {
valType: 'enumerated',
values: ['allow', 'hide past div', 'hide past domain'],
editType: 'calc'
},
ticklabelshift: {
valType: 'integer',
dflt: 0,
editType: 'ticks'
},
ticklabelstandoff: {
valType: 'integer',
dflt: 0,
editType: 'ticks'
},
ticklabelindex: {
// in the future maybe add `extras: ['all', 'minor']` to allow showing labels for all ticks
// or for all minor ticks.
valType: 'integer',
arrayOk: true,
editType: 'calc'
},
mirror: {
valType: 'enumerated',
values: [true, 'ticks', false, 'all', 'allticks'],
dflt: false,
editType: 'ticks+layoutstyle'
},
ticklen: makeTicklen(),
tickwidth: makeTickwidth(),
tickcolor: tickcolor,
showticklabels: {
valType: 'boolean',
dflt: true,
editType: 'ticks'
},
labelalias: {
valType: 'any',
dflt: false,
editType: 'ticks'
},
automargin: {
valType: 'flaglist',
flags: ['height', 'width', 'left', 'right', 'top', 'bottom'],
extras: [true, false],
dflt: false,
editType: 'ticks'
},
showspikes: {
valType: 'boolean',
dflt: false,
editType: 'modebar'
},
spikecolor: {
valType: 'color',
dflt: null,
editType: 'none'
},
spikethickness: {
valType: 'number',
dflt: 3,
editType: 'none'
},
spikedash: extendFlat({}, dash, {
dflt: 'dash',
editType: 'none'
}),
spikemode: {
valType: 'flaglist',
flags: ['toaxis', 'across', 'marker'],
dflt: 'toaxis',
editType: 'none'
},
spikesnap: {
valType: 'enumerated',
values: ['data', 'cursor', 'hovered data'],
dflt: 'hovered data',
editType: 'none'
},
tickfont: fontAttrs({
editType: 'ticks'
}),
tickangle: {
valType: 'angle',
dflt: 'auto',
editType: 'ticks'
},
autotickangles: {
valType: 'info_array',
freeLength: true,
items: {
valType: 'angle'
},
dflt: [0, 30, 90],
editType: 'ticks'
},
tickprefix: {
valType: 'string',
dflt: '',
editType: 'ticks'
},
showtickprefix: {
valType: 'enumerated',
values: ['all', 'first', 'last', 'none'],
dflt: 'all',
editType: 'ticks'
},
ticksuffix: {
valType: 'string',
dflt: '',
editType: 'ticks'
},
showticksuffix: {
valType: 'enumerated',
values: ['all', 'first', 'last', 'none'],
dflt: 'all',
editType: 'ticks'
},
showexponent: {
valType: 'enumerated',
values: ['all', 'first', 'last', 'none'],
dflt: 'all',
editType: 'ticks'
},
exponentformat: {
valType: 'enumerated',
values: ['none', 'e', 'E', 'power', 'SI', 'B'],
dflt: 'B',
editType: 'ticks'
},
minexponent: {
valType: 'number',
dflt: 3,
min: 0,
editType: 'ticks'
},
separatethousands: {
valType: 'boolean',
dflt: false,
editType: 'ticks'
},
tickformat: {
valType: 'string',
dflt: '',
editType: 'ticks',
description: descriptionWithDates('tick label')
},
tickformatstops: templatedArray('tickformatstop', {
enabled: {
valType: 'boolean',
dflt: true,
editType: 'ticks'
},
dtickrange: {
valType: 'info_array',
items: [{
valType: 'any',
editType: 'ticks'
}, {
valType: 'any',
editType: 'ticks'
}],
editType: 'ticks'
},
value: {
valType: 'string',
dflt: '',
editType: 'ticks'
},
editType: 'ticks'
}),
hoverformat: {
valType: 'string',
dflt: '',
editType: 'none',
description: descriptionWithDates('hover text')
},
// lines and grids
showline: {
valType: 'boolean',
dflt: false,
editType: 'ticks+layoutstyle'
},
linecolor: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'layoutstyle'
},
linewidth: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'ticks+layoutstyle'
},
showgrid: showgrid,
gridcolor: gridcolor,
gridwidth: makeGridwidth(),
griddash: griddash,
zeroline: {
valType: 'boolean',
editType: 'ticks'
},
zerolinecolor: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'ticks'
},
zerolinewidth: {
valType: 'number',
dflt: 1,
editType: 'ticks'
},
showdividers: {
valType: 'boolean',
dflt: true,
editType: 'ticks'
},
dividercolor: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'ticks'
},
dividerwidth: {
valType: 'number',
dflt: 1,
editType: 'ticks'
},
// TODO dividerlen: that would override "to label base" length?
// positioning attributes
// anchor: not used directly, just put here for reference
// values are any opposite-letter axis id
anchor: {
valType: 'enumerated',
values: ['free', constants.idRegex.x.toString(), constants.idRegex.y.toString()],
editType: 'plot'
},
// side: not used directly, as values depend on direction
// values are top, bottom for x axes, and left, right for y
side: {
valType: 'enumerated',
values: ['top', 'bottom', 'left', 'right'],
editType: 'plot'
},
// overlaying: not used directly, just put here for reference
// values are false and any other same-letter axis id that's not
// itself overlaying anything
overlaying: {
valType: 'enumerated',
values: ['free', constants.idRegex.x.toString(), constants.idRegex.y.toString()],
editType: 'plot'
},
minor: {
tickmode: minorTickmode,
nticks: makeNticks('minor'),
tick0: tick0,
dtick: dtick,
tickvals: tickvals,
ticks: ticks,
ticklen: makeTicklen('minor'),
tickwidth: makeTickwidth('minor'),
tickcolor: tickcolor,
gridcolor: gridcolor,
gridwidth: makeGridwidth('minor'),
griddash: griddash,
showgrid: showgrid,
editType: 'ticks'
},
layer: {
valType: 'enumerated',
values: ['above traces', 'below traces'],
dflt: 'above traces',
editType: 'plot'
},
domain: {
valType: 'info_array',
items: [{
valType: 'number',
min: 0,
max: 1,
editType: 'plot'
}, {
valType: 'number',
min: 0,
max: 1,
editType: 'plot'
}],
dflt: [0, 1],
editType: 'plot'
},
position: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
editType: 'plot'
},
autoshift: {
valType: 'boolean',
dflt: false,
editType: 'plot'
},
shift: {
valType: 'number',
editType: 'plot'
},
categoryorder: {
valType: 'enumerated',
values: ['trace', 'category ascending', 'category descending', 'array', 'total ascending', 'total descending', 'min ascending', 'min descending', 'max ascending', 'max descending', 'sum ascending', 'sum descending', 'mean ascending', 'mean descending', 'geometric mean ascending', 'geometric mean descending', 'median ascending', 'median descending'],
dflt: 'trace',
editType: 'calc'
},
categoryarray: {
valType: 'data_array',
editType: 'calc'
},
uirevision: {
valType: 'any',
editType: 'none'
},
editType: 'calc',
_deprecated: {
autotick: {
valType: 'boolean',
editType: 'ticks'
},
title: {
valType: 'string',
editType: 'ticks'
},
titlefont: fontAttrs({
editType: 'ticks'
})
}
};
/***/ }),
/***/ 67352:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var isUnifiedHover = (__webpack_require__(10624).isUnifiedHover);
var handleHoverModeDefaults = __webpack_require__(41008);
var Template = __webpack_require__(31780);
var basePlotLayoutAttributes = __webpack_require__(64859);
var layoutAttributes = __webpack_require__(94724);
var handleTypeDefaults = __webpack_require__(14944);
var handleAxisDefaults = __webpack_require__(28336);
var constraints = __webpack_require__(71888);
var handlePositionDefaults = __webpack_require__(37668);
var axisIds = __webpack_require__(79811);
var id2name = axisIds.id2name;
var name2id = axisIds.name2id;
var AX_ID_PATTERN = (__webpack_require__(33816).AX_ID_PATTERN);
var Registry = __webpack_require__(24040);
var traceIs = Registry.traceIs;
var getComponentMethod = Registry.getComponentMethod;
function appendList(cont, k, item) {
if (Array.isArray(cont[k])) cont[k].push(item);else cont[k] = [item];
}
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
var autotypenumbersDflt = layoutOut.autotypenumbers;
var ax2traces = {};
var xaMayHide = {};
var yaMayHide = {};
var xaMustDisplay = {};
var yaMustDisplay = {};
var yaMustNotReverse = {};
var yaMayReverse = {};
var axHasImage = {};
var outerTicks = {};
var noGrids = {};
var i, j;
// look for axes in the data
for (i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (!traceIs(trace, 'cartesian') && !traceIs(trace, 'gl2d')) continue;
var xaName;
if (trace.xaxis) {
xaName = id2name(trace.xaxis);
appendList(ax2traces, xaName, trace);
} else if (trace.xaxes) {
for (j = 0; j < trace.xaxes.length; j++) {
appendList(ax2traces, id2name(trace.xaxes[j]), trace);
}
}
var yaName;
if (trace.yaxis) {
yaName = id2name(trace.yaxis);
appendList(ax2traces, yaName, trace);
} else if (trace.yaxes) {
for (j = 0; j < trace.yaxes.length; j++) {
appendList(ax2traces, id2name(trace.yaxes[j]), trace);
}
}
// logic for funnels
if (trace.type === 'funnel') {
if (trace.orientation === 'h') {
if (xaName) xaMayHide[xaName] = true;
if (yaName) yaMayReverse[yaName] = true;
} else {
if (yaName) yaMayHide[yaName] = true;
}
} else if (trace.type === 'image') {
if (yaName) axHasImage[yaName] = true;
if (xaName) axHasImage[xaName] = true;
} else {
if (yaName) {
yaMustDisplay[yaName] = true;
yaMustNotReverse[yaName] = true;
}
if (!traceIs(trace, 'carpet') || trace.type === 'carpet' && !trace._cheater) {
if (xaName) xaMustDisplay[xaName] = true;
}
}
// Two things trigger axis visibility:
// 1. is not carpet
// 2. carpet that's not cheater
// The above check for definitely-not-cheater is not adequate. This
// second list tracks which axes *could* be a cheater so that the
// full condition triggering hiding is:
// *could* be a cheater and *is not definitely visible*
if (trace.type === 'carpet' && trace._cheater) {
if (xaName) xaMayHide[xaName] = true;
}
// check for default formatting tweaks
if (traceIs(trace, '2dMap')) {
outerTicks[xaName] = true;
outerTicks[yaName] = true;
}
if (traceIs(trace, 'oriented')) {
var positionAxis = trace.orientation === 'h' ? yaName : xaName;
noGrids[positionAxis] = true;
}
}
var subplots = layoutOut._subplots;
var xIds = subplots.xaxis;
var yIds = subplots.yaxis;
var xNames = Lib.simpleMap(xIds, id2name);
var yNames = Lib.simpleMap(yIds, id2name);
var axNames = xNames.concat(yNames);
// plot_bgcolor only makes sense if there's a (2D) plot!
// TODO: bgcolor for each subplot, to inherit from the main one
var plotBgColor = Color.background;
if (xIds.length && yIds.length) {
plotBgColor = Lib.coerce(layoutIn, layoutOut, basePlotLayoutAttributes, 'plot_bgcolor');
}
var bgColor = Color.combine(plotBgColor, layoutOut.paper_bgcolor);
// name of single axis (e.g. 'xaxis', 'yaxis2')
var axName;
// id of single axis (e.g. 'y', 'x5')
var axId;
// 'x' or 'y'
var axLetter;
// input layout axis container
var axLayoutIn;
// full layout axis container
var axLayoutOut;
function newAxLayoutOut() {
var traces = ax2traces[axName] || [];
axLayoutOut._traceIndices = traces.map(function (t) {
return t._expandedIndex;
});
axLayoutOut._annIndices = [];
axLayoutOut._shapeIndices = [];
axLayoutOut._selectionIndices = [];
axLayoutOut._imgIndices = [];
axLayoutOut._subplotsWith = [];
axLayoutOut._counterAxes = [];
axLayoutOut._name = axLayoutOut._attr = axName;
axLayoutOut._id = axId;
}
function coerce(attr, dflt) {
return Lib.coerce(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
}
function coerce2(attr, dflt) {
return Lib.coerce2(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
}
function getCounterAxes(axLetter) {
return axLetter === 'x' ? yIds : xIds;
}
function getOverlayableAxes(axLetter, axName) {
var list = axLetter === 'x' ? xNames : yNames;
var out = [];
for (var j = 0; j < list.length; j++) {
var axName2 = list[j];
if (axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) {
out.push(name2id(axName2));
}
}
return out;
}
// list of available counter axis names
var counterAxes = {
x: getCounterAxes('x'),
y: getCounterAxes('y')
};
// list of all x AND y axis ids
var allAxisIds = counterAxes.x.concat(counterAxes.y);
// lookup and list of axis ids that axes in axNames have a reference to,
// even though they are missing from allAxisIds
var missingMatchedAxisIdsLookup = {};
var missingMatchedAxisIds = [];
// fill in 'missing' axis lookup when an axis is set to match an axis
// not part of the allAxisIds list, save axis type so that we can propagate
// it to the missing axes
function addMissingMatchedAxis() {
var matchesIn = axLayoutIn.matches;
if (AX_ID_PATTERN.test(matchesIn) && allAxisIds.indexOf(matchesIn) === -1) {
missingMatchedAxisIdsLookup[matchesIn] = axLayoutIn.type;
missingMatchedAxisIds = Object.keys(missingMatchedAxisIdsLookup);
}
}
var hovermode = handleHoverModeDefaults(layoutIn, layoutOut);
var unifiedHover = isUnifiedHover(hovermode);
// first pass creates the containers, determines types, and handles most of the settings
for (i = 0; i < axNames.length; i++) {
axName = axNames[i];
axId = name2id(axName);
axLetter = axName.charAt(0);
if (!Lib.isPlainObject(layoutIn[axName])) {
layoutIn[axName] = {};
}
axLayoutIn = layoutIn[axName];
axLayoutOut = Template.newContainer(layoutOut, axName, axLetter + 'axis');
newAxLayoutOut();
var visibleDflt = axLetter === 'x' && !xaMustDisplay[axName] && xaMayHide[axName] || axLetter === 'y' && !yaMustDisplay[axName] && yaMayHide[axName];
var reverseDflt = axLetter === 'y' && (!yaMustNotReverse[axName] && yaMayReverse[axName] || axHasImage[axName]);
var defaultOptions = {
hasMinor: true,
letter: axLetter,
font: layoutOut.font,
outerTicks: outerTicks[axName],
showGrid: !noGrids[axName],
data: ax2traces[axName] || [],
bgColor: bgColor,
calendar: layoutOut.calendar,
automargin: true,
visibleDflt: visibleDflt,
reverseDflt: reverseDflt,
autotypenumbersDflt: autotypenumbersDflt,
splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[axId],
noAutotickangles: axLetter === 'y'
};
coerce('uirevision', layoutOut.uirevision);
handleTypeDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions);
handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut);
var unifiedSpike = unifiedHover && axLetter === hovermode.charAt(0);
var spikecolor = coerce2('spikecolor', unifiedHover ? axLayoutOut.color : undefined);
var spikethickness = coerce2('spikethickness', unifiedHover ? 1.5 : undefined);
var spikedash = coerce2('spikedash', unifiedHover ? 'dot' : undefined);
var spikemode = coerce2('spikemode', unifiedHover ? 'across' : undefined);
var spikesnap = coerce2('spikesnap');
var showSpikes = coerce('showspikes', !!unifiedSpike || !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap);
if (!showSpikes) {
delete axLayoutOut.spikecolor;
delete axLayoutOut.spikethickness;
delete axLayoutOut.spikedash;
delete axLayoutOut.spikemode;
delete axLayoutOut.spikesnap;
}
// If it exists, the the domain of the axis for the anchor of the overlaying axis
var overlayingAxis = id2name(axLayoutIn.overlaying);
var overlayingAnchorDomain = [0, 1];
if (layoutOut[overlayingAxis] !== undefined) {
var overlayingAnchor = id2name(layoutOut[overlayingAxis].anchor);
if (layoutOut[overlayingAnchor] !== undefined) {
overlayingAnchorDomain = layoutOut[overlayingAnchor].domain;
}
}
handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, {
letter: axLetter,
counterAxes: counterAxes[axLetter],
overlayableAxes: getOverlayableAxes(axLetter, axName),
grid: layoutOut.grid,
overlayingDomain: overlayingAnchorDomain
});
coerce('title.standoff');
addMissingMatchedAxis();
axLayoutOut._input = axLayoutIn;
}
// coerce the 'missing' axes
i = 0;
while (i < missingMatchedAxisIds.length) {
axId = missingMatchedAxisIds[i++];
axName = id2name(axId);
axLetter = axName.charAt(0);
if (!Lib.isPlainObject(layoutIn[axName])) {
layoutIn[axName] = {};
}
axLayoutIn = layoutIn[axName];
axLayoutOut = Template.newContainer(layoutOut, axName, axLetter + 'axis');
newAxLayoutOut();
var defaultOptions2 = {
letter: axLetter,
font: layoutOut.font,
outerTicks: outerTicks[axName],
showGrid: !noGrids[axName],
data: [],
bgColor: bgColor,
calendar: layoutOut.calendar,
automargin: true,
visibleDflt: false,
reverseDflt: false,
autotypenumbersDflt: autotypenumbersDflt,
splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[axId]
};
coerce('uirevision', layoutOut.uirevision);
axLayoutOut.type = missingMatchedAxisIdsLookup[axId] || 'linear';
handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions2, layoutOut);
handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, {
letter: axLetter,
counterAxes: counterAxes[axLetter],
overlayableAxes: getOverlayableAxes(axLetter, axName),
grid: layoutOut.grid
});
coerce('fixedrange');
addMissingMatchedAxis();
axLayoutOut._input = axLayoutIn;
}
// quick second pass for range slider and selector defaults
var rangeSliderDefaults = getComponentMethod('rangeslider', 'handleDefaults');
var rangeSelectorDefaults = getComponentMethod('rangeselector', 'handleDefaults');
for (i = 0; i < xNames.length; i++) {
axName = xNames[i];
axLayoutIn = layoutIn[axName];
axLayoutOut = layoutOut[axName];
rangeSliderDefaults(layoutIn, layoutOut, axName);
if (axLayoutOut.type === 'date') {
rangeSelectorDefaults(axLayoutIn, axLayoutOut, layoutOut, yNames, axLayoutOut.calendar);
}
coerce('fixedrange');
}
for (i = 0; i < yNames.length; i++) {
axName = yNames[i];
axLayoutIn = layoutIn[axName];
axLayoutOut = layoutOut[axName];
var anchoredAxis = layoutOut[id2name(axLayoutOut.anchor)];
var fixedRangeDflt = getComponentMethod('rangeslider', 'isVisible')(anchoredAxis);
coerce('fixedrange', fixedRangeDflt);
}
// Finally, handle scale constraints and matching axes.
//
// We need to do this after all axes have coerced both `type`
// (so we link only axes of the same type) and
// `fixedrange` (so we can avoid linking from OR TO a fixed axis).
constraints.handleDefaults(layoutIn, layoutOut, {
axIds: allAxisIds.concat(missingMatchedAxisIds).sort(axisIds.idSort),
axHasImage: axHasImage
});
};
/***/ }),
/***/ 42136:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorMix = (__webpack_require__(49760).mix);
var colorAttrs = __webpack_require__(22548);
var Lib = __webpack_require__(3400);
/**
* @param {object} opts :
* - dfltColor {string} : default axis color
* - bgColor {string} : combined subplot bg color
* - blend {number, optional} : blend percentage (to compute dflt grid color)
* - showLine {boolean} : show line by default
* - showGrid {boolean} : show grid by default
* - noZeroLine {boolean} : don't coerce zeroline* attributes
* - attributes {object} : attribute object associated with input containers
*/
module.exports = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) {
opts = opts || {};
var dfltColor = opts.dfltColor;
function coerce2(attr, dflt) {
return Lib.coerce2(containerIn, containerOut, opts.attributes, attr, dflt);
}
var lineColor = coerce2('linecolor', dfltColor);
var lineWidth = coerce2('linewidth');
var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth);
if (!showLine) {
delete containerOut.linecolor;
delete containerOut.linewidth;
}
var gridColorDflt = colorMix(dfltColor, opts.bgColor, opts.blend || colorAttrs.lightFraction).toRgbString();
var gridColor = coerce2('gridcolor', gridColorDflt);
var gridWidth = coerce2('gridwidth');
var gridDash = coerce2('griddash');
var showGridLines = coerce('showgrid', opts.showGrid || !!gridColor || !!gridWidth || !!gridDash);
if (!showGridLines) {
delete containerOut.gridcolor;
delete containerOut.gridwidth;
delete containerOut.griddash;
}
if (opts.hasMinor) {
var minorGridColorDflt = colorMix(containerOut.gridcolor, opts.bgColor, 67).toRgbString();
var minorGridColor = coerce2('minor.gridcolor', minorGridColorDflt);
var minorGridWidth = coerce2('minor.gridwidth', containerOut.gridwidth || 1);
var minorGridDash = coerce2('minor.griddash', containerOut.griddash || 'solid');
var minorShowGridLines = coerce('minor.showgrid', !!minorGridColor || !!minorGridWidth || !!minorGridDash);
if (!minorShowGridLines) {
delete containerOut.minor.gridcolor;
delete containerOut.minor.gridwidth;
delete containerOut.minor.griddash;
}
}
if (!opts.noZeroLine) {
var zeroLineColor = coerce2('zerolinecolor', dfltColor);
var zeroLineWidth = coerce2('zerolinewidth');
var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth);
if (!showZeroLine) {
delete containerOut.zerolinecolor;
delete containerOut.zerolinewidth;
}
}
};
/***/ }),
/***/ 37668:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
module.exports = function handlePositionDefaults(containerIn, containerOut, coerce, options) {
var counterAxes = options.counterAxes || [];
var overlayableAxes = options.overlayableAxes || [];
var letter = options.letter;
var grid = options.grid;
var overlayingDomain = options.overlayingDomain;
var dfltAnchor, dfltDomain, dfltSide, dfltPosition, dfltShift, dfltAutomargin;
if (grid) {
dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]];
dfltAnchor = grid._anchors[containerOut._id];
if (dfltDomain) {
dfltSide = grid[letter + 'side'].split(' ')[0];
dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0];
}
}
// Even if there's a grid, this axis may not be in it - fall back on non-grid defaults
dfltDomain = dfltDomain || [0, 1];
dfltAnchor = dfltAnchor || (isNumeric(containerIn.position) ? 'free' : counterAxes[0] || 'free');
dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left');
dfltPosition = dfltPosition || 0;
dfltShift = 0;
dfltAutomargin = false;
var anchor = Lib.coerce(containerIn, containerOut, {
anchor: {
valType: 'enumerated',
values: ['free'].concat(counterAxes),
dflt: dfltAnchor
}
}, 'anchor');
var side = Lib.coerce(containerIn, containerOut, {
side: {
valType: 'enumerated',
values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'],
dflt: dfltSide
}
}, 'side');
if (anchor === 'free') {
if (letter === 'y') {
var autoshift = coerce('autoshift');
if (autoshift) {
dfltPosition = side === 'left' ? overlayingDomain[0] : overlayingDomain[1];
dfltAutomargin = containerOut.automargin ? containerOut.automargin : true;
dfltShift = side === 'left' ? -3 : 3;
}
coerce('shift', dfltShift);
}
coerce('position', dfltPosition);
}
coerce('automargin', dfltAutomargin);
var overlaying = false;
if (overlayableAxes.length) {
overlaying = Lib.coerce(containerIn, containerOut, {
overlaying: {
valType: 'enumerated',
values: [false].concat(overlayableAxes),
dflt: false
}
}, 'overlaying');
}
if (!overlaying) {
// TODO: right now I'm copying this domain over to overlaying axes
// in ax.setscale()... but this means we still need (imperfect) logic
// in the axes popover to hide domain for the overlaying axis.
// perhaps I should make a private version _domain that all axes get???
var domain = coerce('domain', dfltDomain);
// according to https://www.npmjs.com/package/canvas-size
// the minimum value of max canvas width across browsers and devices is 4096
// which applied in the calculation below:
if (domain[0] > domain[1] - 1 / 4096) containerOut.domain = dfltDomain;
Lib.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain);
// tickmode sync needs an overlaying axis, otherwise
// we should default it to 'auto'
if (containerOut.tickmode === 'sync') {
containerOut.tickmode = 'auto';
}
}
coerce('layer');
return containerOut;
};
/***/ }),
/***/ 42568:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var getShowAttrDflt = __webpack_require__(85024);
module.exports = function handlePrefixSuffixDefaults(containerIn, containerOut, coerce, axType, options) {
if (!options) options = {};
var tickSuffixDflt = options.tickSuffixDflt;
var showAttrDflt = getShowAttrDflt(containerIn);
var tickPrefix = coerce('tickprefix');
if (tickPrefix) coerce('showtickprefix', showAttrDflt);
var tickSuffix = coerce('ticksuffix', tickSuffixDflt);
if (tickSuffix) coerce('showticksuffix', showAttrDflt);
};
/***/ }),
/***/ 96312:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var handleAutorangeOptionsDefaults = __webpack_require__(76808);
module.exports = function handleRangeDefaults(containerIn, containerOut, coerce, options) {
var axTemplate = containerOut._template || {};
var axType = containerOut.type || axTemplate.type || '-';
coerce('minallowed');
coerce('maxallowed');
var range = coerce('range');
if (!range) {
var insiderange;
if (!options.noInsiderange && axType !== 'log') {
insiderange = coerce('insiderange');
// We may support partial insideranges in future
// For now it is out of scope
if (insiderange && (insiderange[0] === null || insiderange[1] === null)) {
containerOut.insiderange = false;
insiderange = undefined;
}
if (insiderange) range = coerce('range', insiderange);
}
}
var autorangeDflt = containerOut.getAutorangeDflt(range, options);
var autorange = coerce('autorange', autorangeDflt);
var shouldAutorange;
// validate range and set autorange true for invalid partial ranges
if (range && (range[0] === null && range[1] === null || (range[0] === null || range[1] === null) && (autorange === 'reversed' || autorange === true) || range[0] !== null && (autorange === 'min' || autorange === 'max reversed') || range[1] !== null && (autorange === 'max' || autorange === 'min reversed'))) {
range = undefined;
delete containerOut.range;
containerOut.autorange = true;
shouldAutorange = true;
}
if (!shouldAutorange) {
autorangeDflt = containerOut.getAutorangeDflt(range, options);
autorange = coerce('autorange', autorangeDflt);
}
if (autorange) {
handleAutorangeOptionsDefaults(coerce, autorange, range);
if (axType === 'linear' || axType === '-') coerce('rangemode');
}
containerOut.cleanRange();
};
/***/ }),
/***/ 21160:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var FROM_BL = (__webpack_require__(84284).FROM_BL);
module.exports = function scaleZoom(ax, factor, centerFraction) {
if (centerFraction === undefined) {
centerFraction = FROM_BL[ax.constraintoward || 'center'];
}
var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])];
var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction;
ax.range = ax._input.range = [ax.l2r(center + (rangeLinear[0] - center) * factor), ax.l2r(center + (rangeLinear[1] - center) * factor)];
ax.setScale();
};
/***/ }),
/***/ 78344:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var utcFormat = (__webpack_require__(94336)/* .utcFormat */ .E9);
var Lib = __webpack_require__(3400);
var numberFormat = Lib.numberFormat;
var isNumeric = __webpack_require__(38248);
var cleanNumber = Lib.cleanNumber;
var ms2DateTime = Lib.ms2DateTime;
var dateTime2ms = Lib.dateTime2ms;
var ensureNumber = Lib.ensureNumber;
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var numConstants = __webpack_require__(39032);
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;
var LOG_CLIP = numConstants.LOG_CLIP;
var ONEWEEK = numConstants.ONEWEEK;
var ONEDAY = numConstants.ONEDAY;
var ONEHOUR = numConstants.ONEHOUR;
var ONEMIN = numConstants.ONEMIN;
var ONESEC = numConstants.ONESEC;
var axisIds = __webpack_require__(79811);
var constants = __webpack_require__(33816);
var HOUR_PATTERN = constants.HOUR_PATTERN;
var WEEKDAY_PATTERN = constants.WEEKDAY_PATTERN;
function fromLog(v) {
return Math.pow(10, v);
}
function isValidCategory(v) {
return v !== null && v !== undefined;
}
/**
* Define the conversion functions for an axis data is used in 5 ways:
*
* d: data, in whatever form it's provided
* c: calcdata: turned into numbers, but not linearized
* l: linearized - same as c except for log axes (and other nonlinear
* mappings later?) this is used when we need to know if it's
* *possible* to show some data on this axis, without caring about
* the current range
* p: pixel value - mapped to the screen with current size and zoom
* r: ranges, tick0, and annotation positions match one of the above
* but are handled differently for different types:
* - linear and date: data format (d)
* - category: calcdata format (c), and will stay that way because
* the data format has no continuous mapping
* - log: linearized (l) format
* TODO: in v3.0 we plan to change it to data format. At that point
* shapes will work the same way as ranges, tick0, and annotations
* so they can use this conversion too.
*
* Creates/updates these conversion functions, and a few more utilities
* like cleanRange, and makeCalcdata
*
* also clears the autotick constraints ._minDtick, ._forceTick0
*/
module.exports = function setConvert(ax, fullLayout) {
fullLayout = fullLayout || {};
var axId = ax._id || 'x';
var axLetter = axId.charAt(0);
function toLog(v, clip) {
if (v > 0) return Math.log(v) / Math.LN10;else if (v <= 0 && clip && ax.range && ax.range.length === 2) {
// clip NaN (ie past negative infinity) to LOG_CLIP axis
// length past the negative edge
var r0 = ax.range[0];
var r1 = ax.range[1];
return 0.5 * (r0 + r1 - 2 * LOG_CLIP * Math.abs(r0 - r1));
} else return BADNUM;
}
/*
* wrapped dateTime2ms that:
* - accepts ms numbers for backward compatibility
* - inserts a dummy arg so calendar is the 3rd arg (see notes below).
* - defaults to ax.calendar
*/
function dt2ms(v, _, calendar, opts) {
if ((opts || {}).msUTC && isNumeric(v)) {
// For now it is only used
// to fix bar length in milliseconds & gl3d ticks
// It could be applied in other places in v3
return +v;
}
// NOTE: Changed this behavior: previously we took any numeric value
// to be a ms, even if it was a string that could be a bare year.
// Now we convert it as a date if at all possible, and only try
// as (local) ms if that fails.
var ms = dateTime2ms(v, calendar || ax.calendar);
if (ms === BADNUM) {
if (isNumeric(v)) {
v = +v;
// keep track of tenths of ms, that `new Date` will drop
// same logic as in Lib.ms2DateTime
var msecTenths = Math.floor(Lib.mod(v + 0.05, 1) * 10);
var msRounded = Math.round(v - msecTenths / 10);
ms = dateTime2ms(new Date(msRounded)) + msecTenths / 10;
} else return BADNUM;
}
return ms;
}
// wrapped ms2DateTime to insert default ax.calendar
function ms2dt(v, r, calendar) {
return ms2DateTime(v, r, calendar || ax.calendar);
}
function getCategoryName(v) {
return ax._categories[Math.round(v)];
}
/*
* setCategoryIndex: return the index of category v,
* inserting it in the list if it's not already there
*
* this will enter the categories in the order it
* encounters them, ie all the categories from the
* first data set, then all the ones from the second
* that aren't in the first etc.
*
* it is assumed that this function is being invoked in the
* already sorted category order; otherwise there would be
* a disconnect between the array and the index returned
*/
function setCategoryIndex(v) {
if (isValidCategory(v)) {
if (ax._categoriesMap === undefined) {
ax._categoriesMap = {};
}
if (ax._categoriesMap[v] !== undefined) {
return ax._categoriesMap[v];
} else {
ax._categories.push(typeof v === 'number' ? String(v) : v);
var curLength = ax._categories.length - 1;
ax._categoriesMap[v] = curLength;
return curLength;
}
}
return BADNUM;
}
function setMultiCategoryIndex(arrayIn, len) {
var arrayOut = new Array(len);
for (var i = 0; i < len; i++) {
var v0 = (arrayIn[0] || [])[i];
var v1 = (arrayIn[1] || [])[i];
arrayOut[i] = getCategoryIndex([v0, v1]);
}
return arrayOut;
}
function getCategoryIndex(v) {
if (ax._categoriesMap) {
return ax._categoriesMap[v];
}
}
function getCategoryPosition(v) {
// d2l/d2c variant that that won't add categories but will also
// allow numbers to be mapped to the linearized axis positions
var index = getCategoryIndex(v);
if (index !== undefined) return index;
if (isNumeric(v)) return +v;
}
function getRangePosition(v) {
return isNumeric(v) ? +v : getCategoryIndex(v);
}
// include 2 fractional digits on pixel, for PDF zooming etc
function _l2p(v, m, b) {
return d3.round(b + m * v, 2);
}
function _p2l(px, m, b) {
return (px - b) / m;
}
var l2p = function l2p(v) {
if (!isNumeric(v)) return BADNUM;
return _l2p(v, ax._m, ax._b);
};
var p2l = function (px) {
return _p2l(px, ax._m, ax._b);
};
if (ax.rangebreaks) {
var isY = axLetter === 'y';
l2p = function (v) {
if (!isNumeric(v)) return BADNUM;
var len = ax._rangebreaks.length;
if (!len) return _l2p(v, ax._m, ax._b);
var flip = isY;
if (ax.range[0] > ax.range[1]) flip = !flip;
var signAx = flip ? -1 : 1;
var pos = signAx * v;
var q = 0;
for (var i = 0; i < len; i++) {
var min = signAx * ax._rangebreaks[i].min;
var max = signAx * ax._rangebreaks[i].max;
if (pos < min) break;
if (pos > max) q = i + 1;else {
// when falls into break, pick 'closest' offset
q = pos < (min + max) / 2 ? i : i + 1;
break;
}
}
var b2 = ax._B[q] || 0;
if (!isFinite(b2)) return 0; // avoid NaN translate e.g. in positionLabels if one keep zooming exactly into a break
return _l2p(v, ax._m2, b2);
};
p2l = function (px) {
var len = ax._rangebreaks.length;
if (!len) return _p2l(px, ax._m, ax._b);
var q = 0;
for (var i = 0; i < len; i++) {
if (px < ax._rangebreaks[i].pmin) break;
if (px > ax._rangebreaks[i].pmax) q = i + 1;
}
return _p2l(px, ax._m2, ax._B[q]);
};
}
// conversions among c/l/p are fairly simple - do them together for all axis types
ax.c2l = ax.type === 'log' ? toLog : ensureNumber;
ax.l2c = ax.type === 'log' ? fromLog : ensureNumber;
ax.l2p = l2p;
ax.p2l = p2l;
ax.c2p = ax.type === 'log' ? function (v, clip) {
return l2p(toLog(v, clip));
} : l2p;
ax.p2c = ax.type === 'log' ? function (px) {
return fromLog(p2l(px));
} : p2l;
/*
* now type-specific conversions for **ALL** other combinations
* they're all written out, instead of being combinations of each other, for
* both clarity and speed.
*/
if (['linear', '-'].indexOf(ax.type) !== -1) {
// all are data vals, but d and r need cleaning
ax.d2r = ax.r2d = ax.d2c = ax.r2c = ax.d2l = ax.r2l = cleanNumber;
ax.c2d = ax.c2r = ax.l2d = ax.l2r = ensureNumber;
ax.d2p = ax.r2p = function (v) {
return ax.l2p(cleanNumber(v));
};
ax.p2d = ax.p2r = p2l;
ax.cleanPos = ensureNumber;
} else if (ax.type === 'log') {
// d and c are data vals, r and l are logged (but d and r need cleaning)
ax.d2r = ax.d2l = function (v, clip) {
return toLog(cleanNumber(v), clip);
};
ax.r2d = ax.r2c = function (v) {
return fromLog(cleanNumber(v));
};
ax.d2c = ax.r2l = cleanNumber;
ax.c2d = ax.l2r = ensureNumber;
ax.c2r = toLog;
ax.l2d = fromLog;
ax.d2p = function (v, clip) {
return ax.l2p(ax.d2r(v, clip));
};
ax.p2d = function (px) {
return fromLog(p2l(px));
};
ax.r2p = function (v) {
return ax.l2p(cleanNumber(v));
};
ax.p2r = p2l;
ax.cleanPos = ensureNumber;
} else if (ax.type === 'date') {
// r and d are date strings, l and c are ms
/*
* Any of these functions with r and d on either side, calendar is the
* **3rd** argument. log has reserved the second argument.
*
* Unless you need the special behavior of the second arg (ms2DateTime
* uses this to limit precision, toLog uses true to clip negatives
* to offscreen low rather than undefined), it's safe to pass 0.
*/
ax.d2r = ax.r2d = Lib.identity;
ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms;
ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt;
ax.d2p = ax.r2p = function (v, _, calendar) {
return ax.l2p(dt2ms(v, 0, calendar));
};
ax.p2d = ax.p2r = function (px, r, calendar) {
return ms2dt(p2l(px), r, calendar);
};
ax.cleanPos = function (v) {
return Lib.cleanDate(v, BADNUM, ax.calendar);
};
} else if (ax.type === 'category') {
// d is categories (string)
// c and l are indices (numbers)
// r is categories or numbers
ax.d2c = ax.d2l = setCategoryIndex;
ax.r2d = ax.c2d = ax.l2d = getCategoryName;
ax.d2r = ax.d2l_noadd = getCategoryPosition;
ax.r2c = function (v) {
var index = getRangePosition(v);
return index !== undefined ? index : ax.fraction2r(0.5);
};
ax.l2r = ax.c2r = ensureNumber;
ax.r2l = getRangePosition;
ax.d2p = function (v) {
return ax.l2p(ax.r2c(v));
};
ax.p2d = function (px) {
return getCategoryName(p2l(px));
};
ax.r2p = ax.d2p;
ax.p2r = p2l;
ax.cleanPos = function (v) {
if (typeof v === 'string' && v !== '') return v;
return ensureNumber(v);
};
} else if (ax.type === 'multicategory') {
// N.B. multicategory axes don't define d2c and d2l,
// as 'data-to-calcdata' conversion needs to take into
// account all data array items as in ax.makeCalcdata.
ax.r2d = ax.c2d = ax.l2d = getCategoryName;
ax.d2r = ax.d2l_noadd = getCategoryPosition;
ax.r2c = function (v) {
var index = getCategoryPosition(v);
return index !== undefined ? index : ax.fraction2r(0.5);
};
ax.r2c_just_indices = getCategoryIndex;
ax.l2r = ax.c2r = ensureNumber;
ax.r2l = getCategoryPosition;
ax.d2p = function (v) {
return ax.l2p(ax.r2c(v));
};
ax.p2d = function (px) {
return getCategoryName(p2l(px));
};
ax.r2p = ax.d2p;
ax.p2r = p2l;
ax.cleanPos = function (v) {
if (Array.isArray(v) || typeof v === 'string' && v !== '') return v;
return ensureNumber(v);
};
ax.setupMultiCategory = function (fullData) {
var traceIndices = ax._traceIndices;
var i, j;
var group = ax._matchGroup;
if (group && ax._categories.length === 0) {
for (var axId2 in group) {
if (axId2 !== axId) {
var ax2 = fullLayout[axisIds.id2name(axId2)];
traceIndices = traceIndices.concat(ax2._traceIndices);
}
}
}
// [ [cnt, {$cat: index}], for 1,2 ]
var seen = [[0, {}], [0, {}]];
// [ [arrayIn[0][i], arrayIn[1][i]], for i .. N ]
var list = [];
for (i = 0; i < traceIndices.length; i++) {
var trace = fullData[traceIndices[i]];
if (axLetter in trace) {
var arrayIn = trace[axLetter];
var len = trace._length || Lib.minRowLength(arrayIn);
if (isArrayOrTypedArray(arrayIn[0]) && isArrayOrTypedArray(arrayIn[1])) {
for (j = 0; j < len; j++) {
var v0 = arrayIn[0][j];
var v1 = arrayIn[1][j];
if (isValidCategory(v0) && isValidCategory(v1)) {
list.push([v0, v1]);
if (!(v0 in seen[0][1])) {
seen[0][1][v0] = seen[0][0]++;
}
if (!(v1 in seen[1][1])) {
seen[1][1][v1] = seen[1][0]++;
}
}
}
}
}
}
list.sort(function (a, b) {
var ind0 = seen[0][1];
var d = ind0[a[0]] - ind0[b[0]];
if (d) return d;
var ind1 = seen[1][1];
return ind1[a[1]] - ind1[b[1]];
});
for (i = 0; i < list.length; i++) {
setCategoryIndex(list[i]);
}
};
}
// find the range value at the specified (linear) fraction of the axis
ax.fraction2r = function (v) {
var rl0 = ax.r2l(ax.range[0]);
var rl1 = ax.r2l(ax.range[1]);
return ax.l2r(rl0 + v * (rl1 - rl0));
};
// find the fraction of the range at the specified range value
ax.r2fraction = function (v) {
var rl0 = ax.r2l(ax.range[0]);
var rl1 = ax.r2l(ax.range[1]);
return (ax.r2l(v) - rl0) / (rl1 - rl0);
};
ax.limitRange = function (rangeAttr) {
var minallowed = ax.minallowed;
var maxallowed = ax.maxallowed;
if (minallowed === undefined && maxallowed === undefined) return;
if (!rangeAttr) rangeAttr = 'range';
var range = Lib.nestedProperty(ax, rangeAttr).get();
var rng = Lib.simpleMap(range, ax.r2l);
var axrev = rng[1] < rng[0];
if (axrev) rng.reverse();
var bounds = Lib.simpleMap([minallowed, maxallowed], ax.r2l);
if (minallowed !== undefined && rng[0] < bounds[0]) range[axrev ? 1 : 0] = minallowed;
if (maxallowed !== undefined && rng[1] > bounds[1]) range[axrev ? 0 : 1] = maxallowed;
if (range[0] === range[1]) {
var minL = ax.l2r(minallowed);
var maxL = ax.l2r(maxallowed);
if (minallowed !== undefined) {
var _max = minL + 1;
if (maxallowed !== undefined) _max = Math.min(_max, maxL);
range[axrev ? 1 : 0] = _max;
}
if (maxallowed !== undefined) {
var _min = maxL + 1;
if (minallowed !== undefined) _min = Math.max(_min, minL);
range[axrev ? 0 : 1] = _min;
}
}
};
/*
* cleanRange: make sure range is a couplet of valid & distinct values
* keep numbers away from the limits of floating point numbers,
* and dates away from the ends of our date system (+/- 9999 years)
*
* optional param rangeAttr: operate on a different attribute, like
* ax._r, rather than ax.range
*/
ax.cleanRange = function (rangeAttr, opts) {
ax._cleanRange(rangeAttr, opts);
ax.limitRange(rangeAttr);
};
ax._cleanRange = function (rangeAttr, opts) {
if (!opts) opts = {};
if (!rangeAttr) rangeAttr = 'range';
var range = Lib.nestedProperty(ax, rangeAttr).get();
var i, dflt;
if (ax.type === 'date') dflt = Lib.dfltRange(ax.calendar);else if (axLetter === 'y') dflt = constants.DFLTRANGEY;else if (ax._name === 'realaxis') dflt = [0, 1];else dflt = opts.dfltRange || constants.DFLTRANGEX;
// make sure we don't later mutate the defaults
dflt = dflt.slice();
if (ax.rangemode === 'tozero' || ax.rangemode === 'nonnegative') {
dflt[0] = 0;
}
if (!range || range.length !== 2) {
Lib.nestedProperty(ax, rangeAttr).set(dflt);
return;
}
var nullRange0 = range[0] === null;
var nullRange1 = range[1] === null;
if (ax.type === 'date' && !ax.autorange) {
// check if milliseconds or js date objects are provided for range
// and convert to date strings
range[0] = Lib.cleanDate(range[0], BADNUM, ax.calendar);
range[1] = Lib.cleanDate(range[1], BADNUM, ax.calendar);
}
for (i = 0; i < 2; i++) {
if (ax.type === 'date') {
if (!Lib.isDateTime(range[i], ax.calendar)) {
ax[rangeAttr] = dflt;
break;
}
if (ax.r2l(range[0]) === ax.r2l(range[1])) {
// split by +/- 1 second
var linCenter = Lib.constrain(ax.r2l(range[0]), Lib.MIN_MS + 1000, Lib.MAX_MS - 1000);
range[0] = ax.l2r(linCenter - 1000);
range[1] = ax.l2r(linCenter + 1000);
break;
}
} else {
if (!isNumeric(range[i])) {
if (!(nullRange0 || nullRange1) && isNumeric(range[1 - i])) {
range[i] = range[1 - i] * (i ? 10 : 0.1);
} else {
ax[rangeAttr] = dflt;
break;
}
}
if (range[i] < -FP_SAFE) range[i] = -FP_SAFE;else if (range[i] > FP_SAFE) range[i] = FP_SAFE;
if (range[0] === range[1]) {
// somewhat arbitrary: split by 1 or 1ppm, whichever is bigger
var inc = Math.max(1, Math.abs(range[0] * 1e-6));
range[0] -= inc;
range[1] += inc;
}
}
}
};
// set scaling to pixels
ax.setScale = function (usePrivateRange) {
var gs = fullLayout._size;
// make sure we have a domain (pull it in from the axis
// this one is overlaying if necessary)
if (ax.overlaying) {
var ax2 = axisIds.getFromId({
_fullLayout: fullLayout
}, ax.overlaying);
ax.domain = ax2.domain;
}
// While transitions are occurring, we get a double-transform
// issue if we transform the drawn layer *and* use the new axis range to
// draw the data. This allows us to construct setConvert using the pre-
// interaction values of the range:
var rangeAttr = usePrivateRange && ax._r ? '_r' : 'range';
var calendar = ax.calendar;
ax.cleanRange(rangeAttr);
var rl0 = ax.r2l(ax[rangeAttr][0], calendar);
var rl1 = ax.r2l(ax[rangeAttr][1], calendar);
var isY = axLetter === 'y';
if (isY) {
ax._offset = gs.t + (1 - ax.domain[1]) * gs.h;
ax._length = gs.h * (ax.domain[1] - ax.domain[0]);
ax._m = ax._length / (rl0 - rl1);
ax._b = -ax._m * rl1;
} else {
ax._offset = gs.l + ax.domain[0] * gs.w;
ax._length = gs.w * (ax.domain[1] - ax.domain[0]);
ax._m = ax._length / (rl1 - rl0);
ax._b = -ax._m * rl0;
}
// set of "N" disjoint rangebreaks inside the range
ax._rangebreaks = [];
// length of these rangebreaks in value space - negative on reversed axes
ax._lBreaks = 0;
// l2p slope (same for all intervals)
ax._m2 = 0;
// set of l2p offsets (one for each of the (N+1) piecewise intervals)
ax._B = [];
if (ax.rangebreaks) {
var i, brk;
ax._rangebreaks = ax.locateBreaks(Math.min(rl0, rl1), Math.max(rl0, rl1));
if (ax._rangebreaks.length) {
for (i = 0; i < ax._rangebreaks.length; i++) {
brk = ax._rangebreaks[i];
ax._lBreaks += Math.abs(brk.max - brk.min);
}
var flip = isY;
if (rl0 > rl1) flip = !flip;
if (flip) ax._rangebreaks.reverse();
var sign = flip ? -1 : 1;
ax._m2 = sign * ax._length / (Math.abs(rl1 - rl0) - ax._lBreaks);
ax._B.push(-ax._m2 * (isY ? rl1 : rl0));
for (i = 0; i < ax._rangebreaks.length; i++) {
brk = ax._rangebreaks[i];
ax._B.push(ax._B[ax._B.length - 1] - sign * ax._m2 * (brk.max - brk.min));
}
// fill pixel (i.e. 'p') min/max here,
// to not have to loop through the _rangebreaks twice during `p2l`
for (i = 0; i < ax._rangebreaks.length; i++) {
brk = ax._rangebreaks[i];
brk.pmin = l2p(brk.min);
brk.pmax = l2p(brk.max);
}
}
}
if (!isFinite(ax._m) || !isFinite(ax._b) || ax._length < 0) {
fullLayout._replotting = false;
throw new Error('Something went wrong with axis scaling');
}
};
ax.maskBreaks = function (v) {
var rangebreaksIn = ax.rangebreaks || [];
var bnds, b0, b1, vb, vDate;
if (!rangebreaksIn._cachedPatterns) {
rangebreaksIn._cachedPatterns = rangebreaksIn.map(function (brk) {
return brk.enabled && brk.bounds ? Lib.simpleMap(brk.bounds, brk.pattern ? cleanNumber : ax.d2c // case of pattern: ''
) : null;
});
}
if (!rangebreaksIn._cachedValues) {
rangebreaksIn._cachedValues = rangebreaksIn.map(function (brk) {
return brk.enabled && brk.values ? Lib.simpleMap(brk.values, ax.d2c).sort(Lib.sorterAsc) : null;
});
}
for (var i = 0; i < rangebreaksIn.length; i++) {
var brk = rangebreaksIn[i];
if (brk.enabled) {
if (brk.bounds) {
var pattern = brk.pattern;
bnds = rangebreaksIn._cachedPatterns[i];
b0 = bnds[0];
b1 = bnds[1];
switch (pattern) {
case WEEKDAY_PATTERN:
vDate = new Date(v);
vb = vDate.getUTCDay();
if (b0 > b1) {
b1 += 7;
if (vb < b0) vb += 7;
}
break;
case HOUR_PATTERN:
vDate = new Date(v);
var hours = vDate.getUTCHours();
var minutes = vDate.getUTCMinutes();
var seconds = vDate.getUTCSeconds();
var milliseconds = vDate.getUTCMilliseconds();
vb = hours + (minutes / 60 + seconds / 3600 + milliseconds / 3600000);
if (b0 > b1) {
b1 += 24;
if (vb < b0) vb += 24;
}
break;
case '':
// N.B. should work on date axes as well!
// e.g. { bounds: ['2020-01-04', '2020-01-05 23:59'] }
// TODO should work with reversed-range axes
vb = v;
break;
}
if (vb >= b0 && vb < b1) return BADNUM;
} else {
var vals = rangebreaksIn._cachedValues[i];
for (var j = 0; j < vals.length; j++) {
b0 = vals[j];
b1 = b0 + brk.dvalue;
if (v >= b0 && v < b1) return BADNUM;
}
}
}
}
return v;
};
ax.locateBreaks = function (r0, r1) {
var i, bnds, b0, b1;
var rangebreaksOut = [];
if (!ax.rangebreaks) return rangebreaksOut;
var rangebreaksIn = ax.rangebreaks.slice().sort(function (a, b) {
if (a.pattern === WEEKDAY_PATTERN && b.pattern === HOUR_PATTERN) return -1;
if (b.pattern === WEEKDAY_PATTERN && a.pattern === HOUR_PATTERN) return 1;
return 0;
});
var addBreak = function (min, max) {
min = Lib.constrain(min, r0, r1);
max = Lib.constrain(max, r0, r1);
if (min === max) return;
var isNewBreak = true;
for (var j = 0; j < rangebreaksOut.length; j++) {
var brkj = rangebreaksOut[j];
if (min < brkj.max && max >= brkj.min) {
if (min < brkj.min) {
brkj.min = min;
}
if (max > brkj.max) {
brkj.max = max;
}
isNewBreak = false;
}
}
if (isNewBreak) {
rangebreaksOut.push({
min: min,
max: max
});
}
};
for (i = 0; i < rangebreaksIn.length; i++) {
var brk = rangebreaksIn[i];
if (brk.enabled) {
if (brk.bounds) {
var t0 = r0;
var t1 = r1;
if (brk.pattern) {
// to remove decimal (most often found in auto ranges)
t0 = Math.floor(t0);
}
bnds = Lib.simpleMap(brk.bounds, brk.pattern ? cleanNumber : ax.r2l);
b0 = bnds[0];
b1 = bnds[1];
// r0 value as date
var t0Date = new Date(t0);
// r0 value for break pattern
var bndDelta;
// step in ms between rangebreaks
var step;
switch (brk.pattern) {
case WEEKDAY_PATTERN:
step = ONEWEEK;
bndDelta = ((b1 < b0 ? 7 : 0) + (b1 - b0)) * ONEDAY;
t0 += b0 * ONEDAY - (t0Date.getUTCDay() * ONEDAY + t0Date.getUTCHours() * ONEHOUR + t0Date.getUTCMinutes() * ONEMIN + t0Date.getUTCSeconds() * ONESEC + t0Date.getUTCMilliseconds());
break;
case HOUR_PATTERN:
step = ONEDAY;
bndDelta = ((b1 < b0 ? 24 : 0) + (b1 - b0)) * ONEHOUR;
t0 += b0 * ONEHOUR - (t0Date.getUTCHours() * ONEHOUR + t0Date.getUTCMinutes() * ONEMIN + t0Date.getUTCSeconds() * ONESEC + t0Date.getUTCMilliseconds());
break;
default:
t0 = Math.min(bnds[0], bnds[1]);
t1 = Math.max(bnds[0], bnds[1]);
step = t1 - t0;
bndDelta = step;
}
for (var t = t0; t < t1; t += step) {
addBreak(t, t + bndDelta);
}
} else {
var vals = Lib.simpleMap(brk.values, ax.d2c);
for (var j = 0; j < vals.length; j++) {
b0 = vals[j];
b1 = b0 + brk.dvalue;
addBreak(b0, b1);
}
}
}
}
rangebreaksOut.sort(function (a, b) {
return a.min - b.min;
});
return rangebreaksOut;
};
// makeCalcdata: takes an x or y array and converts it
// to a position on the axis object "ax"
// inputs:
// trace - a data object from gd.data
// axLetter - a string, either 'x' or 'y', for which item
// to convert (TODO: is this now always the same as
// the first letter of ax._id?)
// in case the expected data isn't there, make a list of
// integers based on the opposite data
ax.makeCalcdata = function (trace, axLetter, opts) {
var arrayIn, arrayOut, i, len;
var axType = ax.type;
var cal = axType === 'date' && trace[axLetter + 'calendar'];
if (axLetter in trace) {
arrayIn = trace[axLetter];
len = trace._length || Lib.minRowLength(arrayIn);
if (Lib.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) {
if (len === arrayIn.length) {
return arrayIn;
} else if (arrayIn.subarray) {
return arrayIn.subarray(0, len);
}
}
if (axType === 'multicategory') {
return setMultiCategoryIndex(arrayIn, len);
}
arrayOut = new Array(len);
for (i = 0; i < len; i++) {
arrayOut[i] = ax.d2c(arrayIn[i], 0, cal, opts);
}
} else {
var v0 = axLetter + '0' in trace ? ax.d2c(trace[axLetter + '0'], 0, cal) : 0;
var dv = trace['d' + axLetter] ? Number(trace['d' + axLetter]) : 1;
// the opposing data, for size if we have x and dx etc
arrayIn = trace[{
x: 'y',
y: 'x'
}[axLetter]];
len = trace._length || arrayIn.length;
arrayOut = new Array(len);
for (i = 0; i < len; i++) {
arrayOut[i] = v0 + i * dv;
}
}
// mask (i.e. set to BADNUM) coords that fall inside rangebreaks
if (ax.rangebreaks) {
for (i = 0; i < len; i++) {
arrayOut[i] = ax.maskBreaks(arrayOut[i]);
}
}
return arrayOut;
};
ax.isValidRange = function (range, nullOk) {
return Array.isArray(range) && range.length === 2 && (nullOk && range[0] === null || isNumeric(ax.r2l(range[0]))) && (nullOk && range[1] === null || isNumeric(ax.r2l(range[1])));
};
ax.getAutorangeDflt = function (range, options) {
var autorangeDflt = !ax.isValidRange(range, 'nullOk');
if (autorangeDflt && options && options.reverseDflt) autorangeDflt = 'reversed';else if (range) {
if (range[0] === null && range[1] === null) {
autorangeDflt = true;
} else if (range[0] === null && range[1] !== null) {
autorangeDflt = 'min';
} else if (range[0] !== null && range[1] === null) {
autorangeDflt = 'max';
}
}
return autorangeDflt;
};
ax.isReversed = function () {
var autorange = ax.autorange;
return autorange === 'reversed' || autorange === 'min reversed' || autorange === 'max reversed';
};
ax.isPtWithinRange = function (d, calendar) {
var coord = ax.c2l(d[axLetter], null, calendar);
var r0 = ax.r2l(ax.range[0]);
var r1 = ax.r2l(ax.range[1]);
if (r0 < r1) {
return r0 <= coord && coord <= r1;
} else {
// Reversed axis case.
return r1 <= coord && coord <= r0;
}
};
ax._emptyCategories = function () {
ax._categories = [];
ax._categoriesMap = {};
};
// should skip if not category nor multicategory
ax.clearCalc = function () {
var group = ax._matchGroup;
if (group) {
var categories = null;
var categoriesMap = null;
for (var axId2 in group) {
var ax2 = fullLayout[axisIds.id2name(axId2)];
if (ax2._categories) {
categories = ax2._categories;
categoriesMap = ax2._categoriesMap;
break;
}
}
if (categories && categoriesMap) {
ax._categories = categories;
ax._categoriesMap = categoriesMap;
} else {
ax._emptyCategories();
}
} else {
ax._emptyCategories();
}
if (ax._initialCategories) {
for (var j = 0; j < ax._initialCategories.length; j++) {
setCategoryIndex(ax._initialCategories[j]);
}
}
};
// sort the axis (and all the matching ones) by _initialCategories
// returns the indices of the traces affected by the reordering
ax.sortByInitialCategories = function () {
var affectedTraces = [];
ax._emptyCategories();
if (ax._initialCategories) {
for (var j = 0; j < ax._initialCategories.length; j++) {
setCategoryIndex(ax._initialCategories[j]);
}
}
affectedTraces = affectedTraces.concat(ax._traceIndices);
// Propagate to matching axes
var group = ax._matchGroup;
for (var axId2 in group) {
if (axId === axId2) continue;
var ax2 = fullLayout[axisIds.id2name(axId2)];
ax2._categories = ax._categories;
ax2._categoriesMap = ax._categoriesMap;
affectedTraces = affectedTraces.concat(ax2._traceIndices);
}
return affectedTraces;
};
// Propagate localization into the axis so that
// methods in Axes can use it w/o having to pass fullLayout
// Default (non-d3) number formatting uses separators directly
// dates and d3-formatted numbers use the d3 locale
// Fall back on default format for dummy axes that don't care about formatting
var locale = fullLayout._d3locale;
if (ax.type === 'date') {
ax._dateFormat = locale ? locale.timeFormat : utcFormat;
ax._extraFormat = fullLayout._extraFormat;
}
// occasionally we need _numFormat to pass through
// even though it won't be needed by this axis
ax._separators = fullLayout.separators;
ax._numFormat = locale ? locale.numberFormat : numberFormat;
// and for bar charts and box plots: reset forced minimum tick spacing
delete ax._minDtick;
delete ax._forceTick0;
};
/***/ }),
/***/ 85024:
/***/ (function(module) {
"use strict";
/*
* Attributes 'showexponent', 'showtickprefix' and 'showticksuffix'
* share values.
*
* If only 1 attribute is set,
* the remaining attributes inherit that value.
*
* If 2 attributes are set to the same value,
* the remaining attribute inherits that value.
*
* If 2 attributes are set to different values,
* the remaining is set to its dflt value.
*
*/
module.exports = function getShowAttrDflt(containerIn) {
var showAttrsAll = ['showexponent', 'showtickprefix', 'showticksuffix'];
var showAttrs = showAttrsAll.filter(function (a) {
return containerIn[a] !== undefined;
});
var sameVal = function (a) {
return containerIn[a] === containerIn[showAttrs[0]];
};
if (showAttrs.every(sameVal) || showAttrs.length === 1) {
return containerIn[showAttrs[0]];
}
};
/***/ }),
/***/ 95936:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var contrast = (__webpack_require__(76308).contrast);
var layoutAttributes = __webpack_require__(94724);
var getShowAttrDflt = __webpack_require__(85024);
var handleArrayContainerDefaults = __webpack_require__(51272);
module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) {
if (!options) options = {};
var labelalias = coerce('labelalias');
if (!Lib.isPlainObject(labelalias)) delete containerOut.labelalias;
var showAttrDflt = getShowAttrDflt(containerIn);
var showTickLabels = coerce('showticklabels');
if (showTickLabels) {
if (!options.noTicklabelshift) {
coerce('ticklabelshift');
}
if (!options.noTicklabelstandoff) {
coerce('ticklabelstandoff');
}
var font = options.font || {};
var contColor = containerOut.color;
var position = containerOut.ticklabelposition || '';
var dfltFontColor = position.indexOf('inside') !== -1 ? contrast(options.bgColor) :
// as with titlefont.color, inherit axis.color only if one was
// explicitly provided
contColor && contColor !== layoutAttributes.color.dflt ? contColor : font.color;
Lib.coerceFont(coerce, 'tickfont', font, {
overrideDflt: {
color: dfltFontColor
}
});
if (!options.noTicklabelstep && axType !== 'multicategory' && axType !== 'log') {
coerce('ticklabelstep');
}
if (!options.noAng) {
var tickAngle = coerce('tickangle');
if (!options.noAutotickangles && tickAngle === 'auto') {
coerce('autotickangles');
}
}
if (axType !== 'category') {
var tickFormat = coerce('tickformat');
handleArrayContainerDefaults(containerIn, containerOut, {
name: 'tickformatstops',
inclusionAttr: 'enabled',
handleItemDefaults: tickformatstopDefaults
});
if (!containerOut.tickformatstops.length) {
delete containerOut.tickformatstops;
}
if (!options.noExp && !tickFormat && axType !== 'date') {
coerce('showexponent', showAttrDflt);
coerce('exponentformat');
coerce('minexponent');
coerce('separatethousands');
}
}
}
};
function tickformatstopDefaults(valueIn, valueOut) {
function coerce(attr, dflt) {
return Lib.coerce(valueIn, valueOut, layoutAttributes.tickformatstops, attr, dflt);
}
var enabled = coerce('enabled');
if (enabled) {
coerce('dtickrange');
coerce('value');
}
}
/***/ }),
/***/ 25404:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(94724);
/**
* options: inherits outerTicks from axes.handleAxisDefaults
*/
module.exports = function handleTickMarkDefaults(containerIn, containerOut, coerce, options) {
var isMinor = options.isMinor;
var cIn = isMinor ? containerIn.minor || {} : containerIn;
var cOut = isMinor ? containerOut.minor : containerOut;
var lAttr = isMinor ? layoutAttributes.minor : layoutAttributes;
var prefix = isMinor ? 'minor.' : '';
var tickLen = Lib.coerce2(cIn, cOut, lAttr, 'ticklen', isMinor ? (containerOut.ticklen || 5) * 0.6 : undefined);
var tickWidth = Lib.coerce2(cIn, cOut, lAttr, 'tickwidth', isMinor ? containerOut.tickwidth || 1 : undefined);
var tickColor = Lib.coerce2(cIn, cOut, lAttr, 'tickcolor', (isMinor ? containerOut.tickcolor : undefined) || cOut.color);
var showTicks = coerce(prefix + 'ticks', !isMinor && options.outerTicks || tickLen || tickWidth || tickColor ? 'outside' : '');
if (!showTicks) {
delete cOut.ticklen;
delete cOut.tickwidth;
delete cOut.tickcolor;
}
};
/***/ }),
/***/ 26332:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var cleanTicks = __webpack_require__(98728);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var isTypedArraySpec = (__webpack_require__(38116).isTypedArraySpec);
var decodeTypedArraySpec = (__webpack_require__(38116).decodeTypedArraySpec);
module.exports = function handleTickValueDefaults(containerIn, containerOut, coerce, axType, opts) {
if (!opts) opts = {};
var isMinor = opts.isMinor;
var cIn = isMinor ? containerIn.minor || {} : containerIn;
var cOut = isMinor ? containerOut.minor : containerOut;
var prefix = isMinor ? 'minor.' : '';
function readInput(attr) {
var v = cIn[attr];
if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
return v !== undefined ? v : (cOut._template || {})[attr];
}
var _tick0 = readInput('tick0');
var _dtick = readInput('dtick');
var _tickvals = readInput('tickvals');
var tickmodeDefault = isArrayOrTypedArray(_tickvals) ? 'array' : _dtick ? 'linear' : 'auto';
var tickmode = coerce(prefix + 'tickmode', tickmodeDefault);
if (tickmode === 'auto' || tickmode === 'sync') {
coerce(prefix + 'nticks');
} else if (tickmode === 'linear') {
// dtick is usually a positive number, but there are some
// special strings available for log or date axes
// tick0 also has special logic
var dtick = cOut.dtick = cleanTicks.dtick(_dtick, axType);
cOut.tick0 = cleanTicks.tick0(_tick0, axType, containerOut.calendar, dtick);
} else if (axType !== 'multicategory') {
var tickvals = coerce(prefix + 'tickvals');
if (tickvals === undefined) cOut.tickmode = 'auto';else if (!isMinor) coerce('ticktext');
}
};
/***/ }),
/***/ 73736:
/***/ (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 Drawing = __webpack_require__(43616);
var Axes = __webpack_require__(54460);
/**
* transitionAxes
*
* transition axes from one set of ranges to another, using a svg
* transformations, similar to during panning.
*
* @param {DOM element | object} gd
* @param {array} edits : array of 'edits', each item with
* - plotinfo {object} subplot object
* - xr0 {array} initial x-range
* - xr1 {array} end x-range
* - yr0 {array} initial y-range
* - yr1 {array} end y-range
* @param {object} transitionOpts
* @param {function} makeOnCompleteCallback
*/
module.exports = function transitionAxes(gd, edits, transitionOpts, makeOnCompleteCallback) {
var fullLayout = gd._fullLayout;
// special case for redraw:false Plotly.animate that relies on this
// to update axis-referenced layout components
if (edits.length === 0) {
Axes.redrawComponents(gd);
return;
}
function unsetSubplotTransform(subplot) {
var xa = subplot.xaxis;
var ya = subplot.yaxis;
fullLayout._defs.select('#' + subplot.clipId + '> rect').call(Drawing.setTranslate, 0, 0).call(Drawing.setScale, 1, 1);
subplot.plot.call(Drawing.setTranslate, xa._offset, ya._offset).call(Drawing.setScale, 1, 1);
var traceGroups = subplot.plot.selectAll('.scatterlayer .trace');
// This is specifically directed at scatter traces, applying an inverse
// scale to individual points to counteract the scale of the trace
// as a whole:
traceGroups.selectAll('.point').call(Drawing.setPointGroupScale, 1, 1);
traceGroups.selectAll('.textpoint').call(Drawing.setTextPointsScale, 1, 1);
traceGroups.call(Drawing.hideOutsideRangePoints, subplot);
}
function updateSubplot(edit, progress) {
var plotinfo = edit.plotinfo;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var xlen = xa._length;
var ylen = ya._length;
var editX = !!edit.xr1;
var editY = !!edit.yr1;
var viewBox = [];
if (editX) {
var xr0 = Lib.simpleMap(edit.xr0, xa.r2l);
var xr1 = Lib.simpleMap(edit.xr1, xa.r2l);
var dx0 = xr0[1] - xr0[0];
var dx1 = xr1[1] - xr1[0];
viewBox[0] = (xr0[0] * (1 - progress) + progress * xr1[0] - xr0[0]) / (xr0[1] - xr0[0]) * xlen;
viewBox[2] = xlen * (1 - progress + progress * dx1 / dx0);
xa.range[0] = xa.l2r(xr0[0] * (1 - progress) + progress * xr1[0]);
xa.range[1] = xa.l2r(xr0[1] * (1 - progress) + progress * xr1[1]);
} else {
viewBox[0] = 0;
viewBox[2] = xlen;
}
if (editY) {
var yr0 = Lib.simpleMap(edit.yr0, ya.r2l);
var yr1 = Lib.simpleMap(edit.yr1, ya.r2l);
var dy0 = yr0[1] - yr0[0];
var dy1 = yr1[1] - yr1[0];
viewBox[1] = (yr0[1] * (1 - progress) + progress * yr1[1] - yr0[1]) / (yr0[0] - yr0[1]) * ylen;
viewBox[3] = ylen * (1 - progress + progress * dy1 / dy0);
ya.range[0] = xa.l2r(yr0[0] * (1 - progress) + progress * yr1[0]);
ya.range[1] = ya.l2r(yr0[1] * (1 - progress) + progress * yr1[1]);
} else {
viewBox[1] = 0;
viewBox[3] = ylen;
}
Axes.drawOne(gd, xa, {
skipTitle: true
});
Axes.drawOne(gd, ya, {
skipTitle: true
});
Axes.redrawComponents(gd, [xa._id, ya._id]);
var xScaleFactor = editX ? xlen / viewBox[2] : 1;
var yScaleFactor = editY ? ylen / viewBox[3] : 1;
var clipDx = editX ? viewBox[0] : 0;
var clipDy = editY ? viewBox[1] : 0;
var fracDx = editX ? viewBox[0] / viewBox[2] * xlen : 0;
var fracDy = editY ? viewBox[1] / viewBox[3] * ylen : 0;
var plotDx = xa._offset - fracDx;
var plotDy = ya._offset - fracDy;
plotinfo.clipRect.call(Drawing.setTranslate, clipDx, clipDy).call(Drawing.setScale, 1 / xScaleFactor, 1 / yScaleFactor);
plotinfo.plot.call(Drawing.setTranslate, plotDx, plotDy).call(Drawing.setScale, xScaleFactor, yScaleFactor);
// apply an inverse scale to individual points to counteract
// the scale of the trace group.
Drawing.setPointGroupScale(plotinfo.zoomScalePts, 1 / xScaleFactor, 1 / yScaleFactor);
Drawing.setTextPointsScale(plotinfo.zoomScaleTxt, 1 / xScaleFactor, 1 / yScaleFactor);
}
var onComplete;
if (makeOnCompleteCallback) {
// This module makes the choice whether or not it notifies Plotly.transition
// about completion:
onComplete = makeOnCompleteCallback();
}
function transitionComplete() {
var aobj = {};
for (var i = 0; i < edits.length; i++) {
var edit = edits[i];
var xa = edit.plotinfo.xaxis;
var ya = edit.plotinfo.yaxis;
if (edit.xr1) aobj[xa._name + '.range'] = edit.xr1.slice();
if (edit.yr1) aobj[ya._name + '.range'] = edit.yr1.slice();
}
// Signal that this transition has completed:
onComplete && onComplete();
return Registry.call('relayout', gd, aobj).then(function () {
for (var i = 0; i < edits.length; i++) {
unsetSubplotTransform(edits[i].plotinfo);
}
});
}
function transitionInterrupt() {
var aobj = {};
for (var i = 0; i < edits.length; i++) {
var edit = edits[i];
var xa = edit.plotinfo.xaxis;
var ya = edit.plotinfo.yaxis;
if (edit.xr0) aobj[xa._name + '.range'] = edit.xr0.slice();
if (edit.yr0) aobj[ya._name + '.range'] = edit.yr0.slice();
}
return Registry.call('relayout', gd, aobj).then(function () {
for (var i = 0; i < edits.length; i++) {
unsetSubplotTransform(edits[i].plotinfo);
}
});
}
var t1, t2, raf;
var easeFn = d3.ease(transitionOpts.easing);
gd._transitionData._interruptCallbacks.push(function () {
window.cancelAnimationFrame(raf);
raf = null;
return transitionInterrupt();
});
function doFrame() {
t2 = Date.now();
var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration);
var progress = easeFn(tInterp);
for (var i = 0; i < edits.length; i++) {
updateSubplot(edits[i], progress);
}
if (t2 - t1 > transitionOpts.duration) {
transitionComplete();
raf = window.cancelAnimationFrame(doFrame);
} else {
raf = window.requestAnimationFrame(doFrame);
}
}
t1 = Date.now();
raf = window.requestAnimationFrame(doFrame);
return Promise.resolve();
};
/***/ }),
/***/ 14944:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var traceIs = (__webpack_require__(24040).traceIs);
var autoType = __webpack_require__(52976);
/*
* data: the plot data to use in choosing auto type
* name: axis object name (ie 'xaxis') if one should be stored
*/
module.exports = function handleTypeDefaults(containerIn, containerOut, coerce, options) {
coerce('autotypenumbers', options.autotypenumbersDflt);
var axType = coerce('type', (options.splomStash || {}).type);
if (axType === '-') {
setAutoType(containerOut, options.data);
if (containerOut.type === '-') {
containerOut.type = 'linear';
} else {
// copy autoType back to input axis
// note that if this object didn't exist
// in the input layout, we have to put it in
// this happens in the main supplyDefaults function
containerIn.type = containerOut.type;
}
}
};
function setAutoType(ax, data) {
// new logic: let people specify any type they want,
// only autotype if type is '-'
if (ax.type !== '-') return;
var id = ax._id;
var axLetter = id.charAt(0);
var i;
// support 3d
if (id.indexOf('scene') !== -1) id = axLetter;
var d0 = getFirstNonEmptyTrace(data, id, axLetter);
if (!d0) return;
// first check for histograms, as the count direction
// should always default to a linear axis
if (d0.type === 'histogram' && axLetter === {
v: 'y',
h: 'x'
}[d0.orientation || 'v']) {
ax.type = 'linear';
return;
}
var calAttr = axLetter + 'calendar';
var calendar = d0[calAttr];
var opts = {
noMultiCategory: !traceIs(d0, 'cartesian') || traceIs(d0, 'noMultiCategory')
};
// To not confuse 2D x/y used for per-box sample points for multicategory coordinates
if (d0.type === 'box' && d0._hasPreCompStats && axLetter === {
h: 'x',
v: 'y'
}[d0.orientation || 'v']) {
opts.noMultiCategory = true;
}
opts.autotypenumbers = ax.autotypenumbers;
// check all boxes on this x axis to see
// if they're dates, numbers, or categories
if (isBoxWithoutPositionCoords(d0, axLetter)) {
var posLetter = getBoxPosLetter(d0);
var boxPositions = [];
for (i = 0; i < data.length; i++) {
var trace = data[i];
if (!traceIs(trace, 'box-violin') || (trace[axLetter + 'axis'] || axLetter) !== id) continue;
if (trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]);else if (trace.name !== undefined) boxPositions.push(trace.name);else boxPositions.push('text');
if (trace[calAttr] !== calendar) calendar = undefined;
}
ax.type = autoType(boxPositions, calendar, opts);
} else if (d0.type === 'splom') {
var dimensions = d0.dimensions;
var dim = dimensions[d0._axesDim[id]];
if (dim.visible) ax.type = autoType(dim.values, calendar, opts);
} else {
ax.type = autoType(d0[axLetter] || [d0[axLetter + '0']], calendar, opts);
}
}
function getFirstNonEmptyTrace(data, id, axLetter) {
for (var i = 0; i < data.length; i++) {
var trace = data[i];
if (trace.type === 'splom' && trace._length > 0 && (trace['_' + axLetter + 'axes'] || {})[id]) {
return trace;
}
if ((trace[axLetter + 'axis'] || axLetter) === id) {
if (isBoxWithoutPositionCoords(trace, axLetter)) {
return trace;
} else if ((trace[axLetter] || []).length || trace[axLetter + '0']) {
return trace;
}
}
}
}
function getBoxPosLetter(trace) {
return {
v: 'x',
h: 'y'
}[trace.orientation || 'v'];
}
function isBoxWithoutPositionCoords(trace, axLetter) {
var posLetter = getBoxPosLetter(trace);
var isBox = traceIs(trace, 'box-violin');
var isCandlestick = traceIs(trace._fullInput || {}, 'candlestick');
return isBox && !isCandlestick && axLetter === posLetter && trace[posLetter] === undefined && trace[posLetter + '0'] === undefined;
}
/***/ }),
/***/ 62460:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
/*
* Create or update an observer. This function is designed to be
* idempotent so that it can be called over and over as the component
* updates, and will attach and detach listeners as needed.
*
* @param {optional object} container
* An object on which the observer is stored. This is the mechanism
* by which it is idempotent. If it already exists, another won't be
* added. Each time it's called, the value lookup table is updated.
* @param {array} commandList
* An array of commands, following either `buttons` of `updatemenus`
* or `steps` of `sliders`.
* @param {function} onchange
* A listener called when the value is changed. Receives data object
* with information about the new state.
*/
exports.manageCommandObserver = function (gd, container, commandList, onchange) {
var ret = {};
var enabled = true;
if (container && container._commandObserver) {
ret = container._commandObserver;
}
if (!ret.cache) {
ret.cache = {};
}
// Either create or just recompute this:
ret.lookupTable = {};
var binding = exports.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable);
if (container && container._commandObserver) {
if (!binding) {
// If container exists and there are no longer any bindings,
// remove existing:
if (container._commandObserver.remove) {
container._commandObserver.remove();
container._commandObserver = null;
return ret;
}
} else {
// If container exists and there *are* bindings, then the lookup
// table should have been updated and check is already attached,
// so there's nothing to be done:
return ret;
}
}
// Determine whether there's anything to do for this binding:
if (binding) {
// Build the cache:
bindingValueHasChanged(gd, binding, ret.cache);
ret.check = function check() {
if (!enabled) return;
var update = bindingValueHasChanged(gd, binding, ret.cache);
if (update.changed && onchange) {
// Disable checks for the duration of this command in order to avoid
// infinite loops:
if (ret.lookupTable[update.value] !== undefined) {
ret.disable();
Promise.resolve(onchange({
value: update.value,
type: binding.type,
prop: binding.prop,
traces: binding.traces,
index: ret.lookupTable[update.value]
})).then(ret.enable, ret.enable);
}
}
return update.changed;
};
var checkEvents = ['plotly_relayout', 'plotly_redraw', 'plotly_restyle', 'plotly_update', 'plotly_animatingframe', 'plotly_afterplot'];
for (var i = 0; i < checkEvents.length; i++) {
gd._internalOn(checkEvents[i], ret.check);
}
ret.remove = function () {
for (var i = 0; i < checkEvents.length; i++) {
gd._removeInternalListener(checkEvents[i], ret.check);
}
};
} else {
// TODO: It'd be really neat to actually give a *reason* for this, but at least a warning
// is a start
Lib.log('Unable to automatically bind plot updates to API command');
ret.lookupTable = {};
ret.remove = function () {};
}
ret.disable = function disable() {
enabled = false;
};
ret.enable = function enable() {
enabled = true;
};
if (container) {
container._commandObserver = ret;
}
return ret;
};
/*
* This function checks to see if an array of objects containing
* method and args properties is compatible with automatic two-way
* binding. The criteria right now are that
*
* 1. multiple traces may be affected
* 2. only one property may be affected
* 3. the same property must be affected by all commands
*/
exports.hasSimpleAPICommandBindings = function (gd, commandList, bindingsByValue) {
var i;
var n = commandList.length;
var refBinding;
for (i = 0; i < n; i++) {
var binding;
var command = commandList[i];
var method = command.method;
var args = command.args;
if (!Array.isArray(args)) args = [];
// If any command has no method, refuse to bind:
if (!method) {
return false;
}
var bindings = exports.computeAPICommandBindings(gd, method, args);
// Right now, handle one and *only* one property being set:
if (bindings.length !== 1) {
return false;
}
if (!refBinding) {
refBinding = bindings[0];
if (Array.isArray(refBinding.traces)) {
refBinding.traces.sort();
}
} else {
binding = bindings[0];
if (binding.type !== refBinding.type) {
return false;
}
if (binding.prop !== refBinding.prop) {
return false;
}
if (Array.isArray(refBinding.traces)) {
if (Array.isArray(binding.traces)) {
binding.traces.sort();
for (var j = 0; j < refBinding.traces.length; j++) {
if (refBinding.traces[j] !== binding.traces[j]) {
return false;
}
}
} else {
return false;
}
} else {
if (binding.prop !== refBinding.prop) {
return false;
}
}
}
binding = bindings[0];
var value = binding.value;
if (Array.isArray(value)) {
if (value.length === 1) {
value = value[0];
} else {
return false;
}
}
if (bindingsByValue) {
bindingsByValue[value] = i;
}
}
return refBinding;
};
function bindingValueHasChanged(gd, binding, cache) {
var container, value, obj;
var changed = false;
if (binding.type === 'data') {
// If it's data, we need to get a trace. Based on the limited scope
// of what we cover, we can just take the first trace from the list,
// or otherwise just the first trace:
container = gd._fullData[binding.traces !== null ? binding.traces[0] : 0];
} else if (binding.type === 'layout') {
container = gd._fullLayout;
} else {
return false;
}
value = Lib.nestedProperty(container, binding.prop).get();
obj = cache[binding.type] = cache[binding.type] || {};
if (obj.hasOwnProperty(binding.prop)) {
if (obj[binding.prop] !== value) {
changed = true;
}
}
obj[binding.prop] = value;
return {
changed: changed,
value: value
};
}
/*
* Execute an API command. There's really not much to this; it just provides
* a common hook so that implementations don't need to be synchronized across
* multiple components with the ability to invoke API commands.
*
* @param {string} method
* The name of the plotly command to execute. Must be one of 'animate',
* 'restyle', 'relayout', 'update'.
* @param {array} args
* A list of arguments passed to the API command
*/
exports.executeAPICommand = function (gd, method, args) {
if (method === 'skip') return Promise.resolve();
var _method = Registry.apiMethodRegistry[method];
var allArgs = [gd];
if (!Array.isArray(args)) args = [];
for (var i = 0; i < args.length; i++) {
allArgs.push(args[i]);
}
return _method.apply(null, allArgs).catch(function (err) {
Lib.warn('API call to Plotly.' + method + ' rejected.', err);
return Promise.reject(err);
});
};
exports.computeAPICommandBindings = function (gd, method, args) {
var bindings;
if (!Array.isArray(args)) args = [];
switch (method) {
case 'restyle':
bindings = computeDataBindings(gd, args);
break;
case 'relayout':
bindings = computeLayoutBindings(gd, args);
break;
case 'update':
bindings = computeDataBindings(gd, [args[0], args[2]]).concat(computeLayoutBindings(gd, [args[1]]));
break;
case 'animate':
bindings = computeAnimateBindings(gd, args);
break;
default:
// This is the case where intelligent logic about what affects
// this command is not implemented. It causes no ill effects.
// For example, addFrames simply won't bind to a control component.
bindings = [];
}
return bindings;
};
function computeAnimateBindings(gd, args) {
// We'll assume that the only relevant modification an animation
// makes that's meaningfully tracked is the frame:
if (Array.isArray(args[0]) && args[0].length === 1 && ['string', 'number'].indexOf(typeof args[0][0]) !== -1) {
return [{
type: 'layout',
prop: '_currentFrame',
value: args[0][0].toString()
}];
} else {
return [];
}
}
function computeLayoutBindings(gd, args) {
var bindings = [];
var astr = args[0];
var aobj = {};
if (typeof astr === 'string') {
aobj[astr] = args[1];
} else if (Lib.isPlainObject(astr)) {
aobj = astr;
} else {
return bindings;
}
crawl(aobj, function (path, attrName, attr) {
bindings.push({
type: 'layout',
prop: path,
value: attr
});
}, '', 0);
return bindings;
}
function computeDataBindings(gd, args) {
var traces, astr, val, aobj;
var bindings = [];
// Logic copied from Plotly.restyle:
astr = args[0];
val = args[1];
traces = args[2];
aobj = {};
if (typeof astr === 'string') {
aobj[astr] = val;
} else if (Lib.isPlainObject(astr)) {
// the 3-arg form
aobj = astr;
if (traces === undefined) {
traces = val;
}
} else {
return bindings;
}
if (traces === undefined) {
// Explicitly assign this to null instead of undefined:
traces = null;
}
crawl(aobj, function (path, attrName, _attr) {
var thisTraces;
var attr;
if (Array.isArray(_attr)) {
attr = _attr.slice();
var nAttr = Math.min(attr.length, gd.data.length);
if (traces) {
nAttr = Math.min(nAttr, traces.length);
}
thisTraces = [];
for (var j = 0; j < nAttr; j++) {
thisTraces[j] = traces ? traces[j] : j;
}
} else {
attr = _attr;
thisTraces = traces ? traces.slice() : null;
}
// Convert [7] to just 7 when traces is null:
if (thisTraces === null) {
if (Array.isArray(attr)) {
attr = attr[0];
}
} else if (Array.isArray(thisTraces)) {
if (!Array.isArray(attr)) {
var tmp = attr;
attr = [];
for (var i = 0; i < thisTraces.length; i++) {
attr[i] = tmp;
}
}
attr.length = Math.min(thisTraces.length, attr.length);
}
bindings.push({
type: 'data',
prop: path,
traces: thisTraces,
value: attr
});
}, '', 0);
return bindings;
}
function crawl(attrs, callback, path, depth) {
Object.keys(attrs).forEach(function (attrName) {
var attr = attrs[attrName];
if (attrName[0] === '_') return;
var thisPath = path + (depth > 0 ? '.' : '') + attrName;
if (Lib.isPlainObject(attr)) {
crawl(attr, callback, thisPath, depth + 1);
} else {
// Only execute the callback on leaf nodes:
callback(thisPath, attrName, attr);
}
});
}
/***/ }),
/***/ 86968:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var extendFlat = (__webpack_require__(92880).extendFlat);
/**
* Make a xy domain attribute group
*
* @param {object} opts
* @param {string}
* opts.name: name to be inserted in the default description
* @param {boolean}
* opts.trace: set to true for trace containers
* @param {string}
* opts.editType: editType for all pieces
* @param {boolean}
* opts.noGridCell: set to true to omit `row` and `column`
*
* @param {object} extra
* @param {string}
* extra.description: extra description. N.B we use
* a separate extra container to make it compatible with
* the compress_attributes transform.
*
* @return {object} attributes object containing {x,y} as specified
*/
exports.u = function (opts, extra) {
opts = opts || {};
extra = extra || {};
var base = {
valType: 'info_array',
editType: opts.editType,
items: [{
valType: 'number',
min: 0,
max: 1,
editType: opts.editType
}, {
valType: 'number',
min: 0,
max: 1,
editType: opts.editType
}],
dflt: [0, 1]
};
var namePart = opts.name ? opts.name + ' ' : '';
var contPart = opts.trace ? 'trace ' : 'subplot ';
var descPart = extra.description ? ' ' + extra.description : '';
var out = {
x: extendFlat({}, base, {}),
y: extendFlat({}, base, {}),
editType: opts.editType
};
if (!opts.noGridCell) {
out.row = {
valType: 'integer',
min: 0,
dflt: 0,
editType: opts.editType
};
out.column = {
valType: 'integer',
min: 0,
dflt: 0,
editType: opts.editType
};
}
return out;
};
exports.Q = function (containerOut, layout, coerce, dfltDomains) {
var dfltX = dfltDomains && dfltDomains.x || [0, 1];
var dfltY = dfltDomains && dfltDomains.y || [0, 1];
var grid = layout.grid;
if (grid) {
var column = coerce('domain.column');
if (column !== undefined) {
if (column < grid.columns) dfltX = grid._domains.x[column];else delete containerOut.domain.column;
}
var row = coerce('domain.row');
if (row !== undefined) {
if (row < grid.rows) dfltY = grid._domains.y[row];else delete containerOut.domain.row;
}
}
var x = coerce('domain.x', dfltX);
var y = coerce('domain.y', dfltY);
// don't accept bad input data
if (!(x[0] < x[1])) containerOut.domain.x = dfltX.slice();
if (!(y[0] < y[1])) containerOut.domain.y = dfltY.slice();
};
/***/ }),
/***/ 25376:
/***/ (function(module) {
"use strict";
/*
* make a font attribute group
*
* @param {object} opts
* @param {string}
* opts.description: where & how this font is used
* @param {optional bool} arrayOk:
* should each part (family, size, color) be arrayOk? default false.
* @param {string} editType:
* the editType for all pieces of this font
* @param {optional string} colorEditType:
* a separate editType just for color
*
* @return {object} attributes object containing {family, size, color} as specified
*/
module.exports = function (opts) {
var variantValues = opts.variantValues;
var editType = opts.editType;
var colorEditType = opts.colorEditType;
if (colorEditType === undefined) colorEditType = editType;
var weight = {
editType: editType,
valType: 'integer',
min: 1,
max: 1000,
extras: ['normal', 'bold'],
dflt: 'normal'
};
if (opts.noNumericWeightValues) {
weight.valType = 'enumerated';
weight.values = weight.extras;
weight.extras = undefined;
weight.min = undefined;
weight.max = undefined;
}
var attrs = {
family: {
valType: 'string',
noBlank: true,
strict: true,
editType: editType
},
size: {
valType: 'number',
min: 1,
editType: editType
},
color: {
valType: 'color',
editType: colorEditType
},
weight: weight,
style: {
editType: editType,
valType: 'enumerated',
values: ['normal', 'italic'],
dflt: 'normal'
},
variant: opts.noFontVariant ? undefined : {
editType: editType,
valType: 'enumerated',
values: variantValues || ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'],
dflt: 'normal'
},
textcase: opts.noFontTextcase ? undefined : {
editType: editType,
valType: 'enumerated',
values: ['normal', 'word caps', 'upper', 'lower'],
dflt: 'normal'
},
lineposition: opts.noFontLineposition ? undefined : {
editType: editType,
valType: 'flaglist',
flags: ['under', 'over', 'through'],
extras: ['none'],
dflt: 'none'
},
shadow: opts.noFontShadow ? undefined : {
editType: editType,
valType: 'string',
dflt: opts.autoShadowDflt ? 'auto' : 'none'
},
editType: editType
// blank strings so compress_attributes can remove
// TODO - that's uber hacky... better solution?
};
if (opts.autoSize) attrs.size.dflt = 'auto';
if (opts.autoColor) attrs.color.dflt = 'auto';
if (opts.arrayOk) {
attrs.family.arrayOk = true;
attrs.weight.arrayOk = true;
attrs.style.arrayOk = true;
if (!opts.noFontVariant) {
attrs.variant.arrayOk = true;
}
if (!opts.noFontTextcase) {
attrs.textcase.arrayOk = true;
}
if (!opts.noFontLineposition) {
attrs.lineposition.arrayOk = true;
}
if (!opts.noFontShadow) {
attrs.shadow.arrayOk = true;
}
attrs.size.arrayOk = true;
attrs.color.arrayOk = true;
}
return attrs;
};
/***/ }),
/***/ 16672:
/***/ (function(module) {
"use strict";
module.exports = {
_isLinkedToArray: 'frames_entry',
group: {
valType: 'string'
},
name: {
valType: 'string'
},
traces: {
valType: 'any'
},
baseframe: {
valType: 'string'
},
data: {
valType: 'any'
},
layout: {
valType: 'any'
}
};
/***/ }),
/***/ 79552:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
// projection names to d3 function name
exports.projNames = {
airy: 'airy',
aitoff: 'aitoff',
'albers usa': 'albersUsa',
albers: 'albers',
// 'armadillo': 'armadillo',
august: 'august',
'azimuthal equal area': 'azimuthalEqualArea',
'azimuthal equidistant': 'azimuthalEquidistant',
baker: 'baker',
// 'berghaus': 'berghaus',
bertin1953: 'bertin1953',
boggs: 'boggs',
bonne: 'bonne',
bottomley: 'bottomley',
bromley: 'bromley',
// 'chamberlin africa': 'chamberlinAfrica',
// 'chamberlin': 'chamberlin',
collignon: 'collignon',
'conic conformal': 'conicConformal',
'conic equal area': 'conicEqualArea',
'conic equidistant': 'conicEquidistant',
craig: 'craig',
craster: 'craster',
'cylindrical equal area': 'cylindricalEqualArea',
'cylindrical stereographic': 'cylindricalStereographic',
eckert1: 'eckert1',
eckert2: 'eckert2',
eckert3: 'eckert3',
eckert4: 'eckert4',
eckert5: 'eckert5',
eckert6: 'eckert6',
eisenlohr: 'eisenlohr',
'equal earth': 'equalEarth',
equirectangular: 'equirectangular',
fahey: 'fahey',
'foucaut sinusoidal': 'foucautSinusoidal',
foucaut: 'foucaut',
// 'gilbert': 'gilbert',
// 'gingery': 'gingery',
ginzburg4: 'ginzburg4',
ginzburg5: 'ginzburg5',
ginzburg6: 'ginzburg6',
ginzburg8: 'ginzburg8',
ginzburg9: 'ginzburg9',
gnomonic: 'gnomonic',
'gringorten quincuncial': 'gringortenQuincuncial',
gringorten: 'gringorten',
guyou: 'guyou',
// 'hammer retroazimuthal': 'hammerRetroazimuthal',
hammer: 'hammer',
// 'healpix': 'healpix',
hill: 'hill',
homolosine: 'homolosine',
hufnagel: 'hufnagel',
hyperelliptical: 'hyperelliptical',
// 'interrupted boggs': 'interruptedBoggs',
// 'interrupted homolosine': 'interruptedHomolosine',
// 'interrupted mollweide hemispheres': 'interruptedMollweideHemispheres',
// 'interrupted mollweide': 'interruptedMollweide',
// 'interrupted quartic authalic': 'interruptedQuarticAuthalic',
// 'interrupted sinu mollweide': 'interruptedSinuMollweide',
// 'interrupted sinusoidal': 'interruptedSinusoidal',
kavrayskiy7: 'kavrayskiy7',
lagrange: 'lagrange',
larrivee: 'larrivee',
laskowski: 'laskowski',
// 'littrow': 'littrow',
loximuthal: 'loximuthal',
mercator: 'mercator',
miller: 'miller',
// 'modified stereographic alaska': 'modifiedStereographicAlaska',
// 'modified stereographic gs48': 'modifiedStereographicGs48',
// 'modified stereographic gs50': 'modifiedStereographicGs50',
// 'modified stereographic lee': 'modifiedStereographicLee',
// 'modified stereographic miller': 'modifiedStereographicMiller',
// 'modified stereographic': 'modifiedStereographic',
mollweide: 'mollweide',
'mt flat polar parabolic': 'mtFlatPolarParabolic',
'mt flat polar quartic': 'mtFlatPolarQuartic',
'mt flat polar sinusoidal': 'mtFlatPolarSinusoidal',
'natural earth': 'naturalEarth',
'natural earth1': 'naturalEarth1',
'natural earth2': 'naturalEarth2',
'nell hammer': 'nellHammer',
nicolosi: 'nicolosi',
orthographic: 'orthographic',
patterson: 'patterson',
'peirce quincuncial': 'peirceQuincuncial',
polyconic: 'polyconic',
// 'polyhedral butterfly': 'polyhedralButterfly',
// 'polyhedral collignon': 'polyhedralCollignon',
// 'polyhedral waterman': 'polyhedralWaterman',
'rectangular polyconic': 'rectangularPolyconic',
robinson: 'robinson',
satellite: 'satellite',
'sinu mollweide': 'sinuMollweide',
sinusoidal: 'sinusoidal',
stereographic: 'stereographic',
times: 'times',
'transverse mercator': 'transverseMercator',
// 'two point azimuthalUsa': 'twoPointAzimuthalUsa',
// 'two point azimuthal': 'twoPointAzimuthal',
// 'two point equidistantUsa': 'twoPointEquidistantUsa',
// 'two point equidistant': 'twoPointEquidistant',
'van der grinten': 'vanDerGrinten',
'van der grinten2': 'vanDerGrinten2',
'van der grinten3': 'vanDerGrinten3',
'van der grinten4': 'vanDerGrinten4',
wagner4: 'wagner4',
wagner6: 'wagner6',
// 'wagner7': 'wagner7',
// 'wagner': 'wagner',
wiechel: 'wiechel',
'winkel tripel': 'winkel3',
winkel3: 'winkel3'
};
// name of the axes
exports.axesNames = ['lonaxis', 'lataxis'];
// max longitudinal angular span (EXPERIMENTAL)
exports.lonaxisSpan = {
orthographic: 180,
'azimuthal equal area': 360,
'azimuthal equidistant': 360,
'conic conformal': 180,
gnomonic: 160,
stereographic: 180,
'transverse mercator': 180,
'*': 360
};
// max latitudinal angular span (EXPERIMENTAL)
exports.lataxisSpan = {
'conic conformal': 150,
stereographic: 179.5,
'*': 180
};
// defaults for each scope
exports.scopeDefaults = {
world: {
lonaxisRange: [-180, 180],
lataxisRange: [-90, 90],
projType: 'equirectangular',
projRotate: [0, 0, 0]
},
usa: {
lonaxisRange: [-180, -50],
lataxisRange: [15, 80],
projType: 'albers usa'
},
europe: {
lonaxisRange: [-30, 60],
lataxisRange: [30, 85],
projType: 'conic conformal',
projRotate: [15, 0, 0],
projParallels: [0, 60]
},
asia: {
lonaxisRange: [22, 160],
lataxisRange: [-15, 55],
projType: 'mercator',
projRotate: [0, 0, 0]
},
africa: {
lonaxisRange: [-30, 60],
lataxisRange: [-40, 40],
projType: 'mercator',
projRotate: [0, 0, 0]
},
'north america': {
lonaxisRange: [-180, -45],
lataxisRange: [5, 85],
projType: 'conic conformal',
projRotate: [-100, 0, 0],
projParallels: [29.5, 45.5]
},
'south america': {
lonaxisRange: [-100, -30],
lataxisRange: [-60, 15],
projType: 'mercator',
projRotate: [0, 0, 0]
}
};
// angular pad to avoid rounding error around clip angles
exports.clipPad = 1e-3;
// map projection precision
exports.precision = 0.1;
// default land and water fill colors
exports.landColor = '#F0DC82';
exports.waterColor = '#3399FF';
// locationmode to layer name
exports.locationmodeToLayer = {
'ISO-3': 'countries',
'USA-states': 'subunits',
'country names': 'countries'
};
// SVG element for a sphere (use to frame maps)
exports.sphereSVG = {
type: 'Sphere'
};
// N.B. base layer names must be the same as in the topojson files
// base layer with a fill color
exports.fillLayers = {
ocean: 1,
land: 1,
lakes: 1
};
// base layer with a only a line color
exports.lineLayers = {
subunits: 1,
countries: 1,
coastlines: 1,
rivers: 1,
frame: 1
};
exports.layers = ['bg', 'ocean', 'land', 'lakes', 'subunits', 'countries', 'coastlines', 'rivers', 'lataxis', 'lonaxis', 'frame', 'backplot', 'frontplot'];
exports.layersForChoropleth = ['bg', 'ocean', 'land', 'subunits', 'countries', 'coastlines', 'lataxis', 'lonaxis', 'frame', 'backplot', 'rivers', 'lakes', 'frontplot'];
exports.layerNameToAdjective = {
ocean: 'ocean',
land: 'land',
lakes: 'lake',
subunits: 'subunit',
countries: 'country',
coastlines: 'coastline',
rivers: 'river',
frame: 'frame'
};
/***/ }),
/***/ 43520:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* global PlotlyGeoAssets:false */
var d3 = __webpack_require__(33428);
var geo = __webpack_require__(83356);
var geoPath = geo.geoPath;
var geoDistance = geo.geoDistance;
var geoProjection = __webpack_require__(87108);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Fx = __webpack_require__(93024);
var Plots = __webpack_require__(7316);
var Axes = __webpack_require__(54460);
var getAutoRange = (__webpack_require__(19280).getAutoRange);
var dragElement = __webpack_require__(86476);
var prepSelect = (__webpack_require__(22676).prepSelect);
var clearOutline = (__webpack_require__(22676).clearOutline);
var selectOnClick = (__webpack_require__(22676).selectOnClick);
var createGeoZoom = __webpack_require__(79248);
var constants = __webpack_require__(79552);
var geoUtils = __webpack_require__(27144);
var topojsonUtils = __webpack_require__(59972);
var topojsonFeature = (__webpack_require__(55712)/* .feature */ .NO);
function Geo(opts) {
this.id = opts.id;
this.graphDiv = opts.graphDiv;
this.container = opts.container;
this.topojsonURL = opts.topojsonURL;
this.isStatic = opts.staticPlot;
this.topojsonName = null;
this.topojson = null;
this.projection = null;
this.scope = null;
this.viewInitial = null;
this.fitScale = null;
this.bounds = null;
this.midPt = null;
this.hasChoropleth = false;
this.traceHash = {};
this.layers = {};
this.basePaths = {};
this.dataPaths = {};
this.dataPoints = {};
this.clipDef = null;
this.clipRect = null;
this.bgRect = null;
this.makeFramework();
}
var proto = Geo.prototype;
module.exports = function createGeo(opts) {
return new Geo(opts);
};
proto.plot = function (geoCalcData, fullLayout, promises, replot) {
var _this = this;
if (replot) return _this.update(geoCalcData, fullLayout, true);
_this._geoCalcData = geoCalcData;
_this._fullLayout = fullLayout;
var geoLayout = fullLayout[this.id];
var geoPromises = [];
var needsTopojson = false;
for (var k in constants.layerNameToAdjective) {
if (k !== 'frame' && geoLayout['show' + k]) {
needsTopojson = true;
break;
}
}
var hasMarkerAngles = false;
for (var i = 0; i < geoCalcData.length; i++) {
var trace = geoCalcData[0][0].trace;
trace._geo = _this;
if (trace.locationmode) {
needsTopojson = true;
}
var marker = trace.marker;
if (marker) {
var angle = marker.angle;
var angleref = marker.angleref;
if (angle || angleref === 'north' || angleref === 'previous') hasMarkerAngles = true;
}
}
this._hasMarkerAngles = hasMarkerAngles;
if (needsTopojson) {
var topojsonNameNew = topojsonUtils.getTopojsonName(geoLayout);
if (_this.topojson === null || topojsonNameNew !== _this.topojsonName) {
_this.topojsonName = topojsonNameNew;
if (PlotlyGeoAssets.topojson[_this.topojsonName] === undefined) {
geoPromises.push(_this.fetchTopojson());
}
}
}
geoPromises = geoPromises.concat(geoUtils.fetchTraceGeoData(geoCalcData));
promises.push(new Promise(function (resolve, reject) {
Promise.all(geoPromises).then(function () {
_this.topojson = PlotlyGeoAssets.topojson[_this.topojsonName];
_this.update(geoCalcData, fullLayout);
resolve();
}).catch(reject);
}));
};
proto.fetchTopojson = function () {
var _this = this;
var topojsonPath = topojsonUtils.getTopojsonPath(_this.topojsonURL, _this.topojsonName);
return new Promise(function (resolve, reject) {
d3.json(topojsonPath, function (err, topojson) {
if (err) {
if (err.status === 404) {
return reject(new Error(['plotly.js could not find topojson file at', topojsonPath + '.', 'Make sure the *topojsonURL* plot config option', 'is set properly.'].join(' ')));
} else {
return reject(new Error(['unexpected error while fetching topojson file at', topojsonPath].join(' ')));
}
}
PlotlyGeoAssets.topojson[_this.topojsonName] = topojson;
resolve();
});
});
};
proto.update = function (geoCalcData, fullLayout, replot) {
var geoLayout = fullLayout[this.id];
// important: maps with choropleth traces have a different layer order
this.hasChoropleth = false;
for (var i = 0; i < geoCalcData.length; i++) {
var calcTrace = geoCalcData[i];
var trace = calcTrace[0].trace;
if (trace.type === 'choropleth') {
this.hasChoropleth = true;
}
if (trace.visible === true && trace._length > 0) {
trace._module.calcGeoJSON(calcTrace, fullLayout);
}
}
if (!replot) {
var hasInvalidBounds = this.updateProjection(geoCalcData, fullLayout);
if (hasInvalidBounds) return;
if (!this.viewInitial || this.scope !== geoLayout.scope) {
this.saveViewInitial(geoLayout);
}
}
this.scope = geoLayout.scope;
this.updateBaseLayers(fullLayout, geoLayout);
this.updateDims(fullLayout, geoLayout);
this.updateFx(fullLayout, geoLayout);
Plots.generalUpdatePerTraceModule(this.graphDiv, this, geoCalcData, geoLayout);
var scatterLayer = this.layers.frontplot.select('.scatterlayer');
this.dataPoints.point = scatterLayer.selectAll('.point');
this.dataPoints.text = scatterLayer.selectAll('text');
this.dataPaths.line = scatterLayer.selectAll('.js-line');
var choroplethLayer = this.layers.backplot.select('.choroplethlayer');
this.dataPaths.choropleth = choroplethLayer.selectAll('path');
this._render();
};
proto.updateProjection = function (geoCalcData, fullLayout) {
var gd = this.graphDiv;
var geoLayout = fullLayout[this.id];
var gs = fullLayout._size;
var domain = geoLayout.domain;
var projLayout = geoLayout.projection;
var lonaxis = geoLayout.lonaxis;
var lataxis = geoLayout.lataxis;
var axLon = lonaxis._ax;
var axLat = lataxis._ax;
var projection = this.projection = getProjection(geoLayout);
// setup subplot extent [[x0,y0], [x1,y1]]
var extent = [[gs.l + gs.w * domain.x[0], gs.t + gs.h * (1 - domain.y[1])], [gs.l + gs.w * domain.x[1], gs.t + gs.h * (1 - domain.y[0])]];
var center = geoLayout.center || {};
var rotation = projLayout.rotation || {};
var lonaxisRange = lonaxis.range || [];
var lataxisRange = lataxis.range || [];
if (geoLayout.fitbounds) {
axLon._length = extent[1][0] - extent[0][0];
axLat._length = extent[1][1] - extent[0][1];
axLon.range = getAutoRange(gd, axLon);
axLat.range = getAutoRange(gd, axLat);
var midLon = (axLon.range[0] + axLon.range[1]) / 2;
var midLat = (axLat.range[0] + axLat.range[1]) / 2;
if (geoLayout._isScoped) {
center = {
lon: midLon,
lat: midLat
};
} else if (geoLayout._isClipped) {
center = {
lon: midLon,
lat: midLat
};
rotation = {
lon: midLon,
lat: midLat,
roll: rotation.roll
};
var projType = projLayout.type;
var lonHalfSpan = constants.lonaxisSpan[projType] / 2 || 180;
var latHalfSpan = constants.lataxisSpan[projType] / 2 || 90;
lonaxisRange = [midLon - lonHalfSpan, midLon + lonHalfSpan];
lataxisRange = [midLat - latHalfSpan, midLat + latHalfSpan];
} else {
center = {
lon: midLon,
lat: midLat
};
rotation = {
lon: midLon,
lat: rotation.lat,
roll: rotation.roll
};
}
}
// set 'pre-fit' projection
projection.center([center.lon - rotation.lon, center.lat - rotation.lat]).rotate([-rotation.lon, -rotation.lat, rotation.roll]).parallels(projLayout.parallels);
// fit projection 'scale' and 'translate' to set lon/lat ranges
var rangeBox = makeRangeBox(lonaxisRange, lataxisRange);
projection.fitExtent(extent, rangeBox);
var b = this.bounds = projection.getBounds(rangeBox);
var s = this.fitScale = projection.scale();
var t = projection.translate();
if (geoLayout.fitbounds) {
var b2 = projection.getBounds(makeRangeBox(axLon.range, axLat.range));
var k2 = Math.min((b[1][0] - b[0][0]) / (b2[1][0] - b2[0][0]), (b[1][1] - b[0][1]) / (b2[1][1] - b2[0][1]));
if (isFinite(k2)) {
projection.scale(k2 * s);
} else {
Lib.warn('Something went wrong during' + this.id + 'fitbounds computations.');
}
} else {
// adjust projection to user setting
projection.scale(projLayout.scale * s);
}
// px coordinates of view mid-point,
// useful to update `geo.center` after interactions
var midPt = this.midPt = [(b[0][0] + b[1][0]) / 2, (b[0][1] + b[1][1]) / 2];
projection.translate([t[0] + (midPt[0] - t[0]), t[1] + (midPt[1] - t[1])]).clipExtent(b);
// the 'albers usa' projection does not expose a 'center' method
// so here's this hack to make it respond to 'geoLayout.center'
if (geoLayout._isAlbersUsa) {
var centerPx = projection([center.lon, center.lat]);
var tt = projection.translate();
projection.translate([tt[0] - (centerPx[0] - tt[0]), tt[1] - (centerPx[1] - tt[1])]);
}
};
proto.updateBaseLayers = function (fullLayout, geoLayout) {
var _this = this;
var topojson = _this.topojson;
var layers = _this.layers;
var basePaths = _this.basePaths;
function isAxisLayer(d) {
return d === 'lonaxis' || d === 'lataxis';
}
function isLineLayer(d) {
return Boolean(constants.lineLayers[d]);
}
function isFillLayer(d) {
return Boolean(constants.fillLayers[d]);
}
var allLayers = this.hasChoropleth ? constants.layersForChoropleth : constants.layers;
var layerData = allLayers.filter(function (d) {
return isLineLayer(d) || isFillLayer(d) ? geoLayout['show' + d] : isAxisLayer(d) ? geoLayout[d].showgrid : true;
});
var join = _this.framework.selectAll('.layer').data(layerData, String);
join.exit().each(function (d) {
delete layers[d];
delete basePaths[d];
d3.select(this).remove();
});
join.enter().append('g').attr('class', function (d) {
return 'layer ' + d;
}).each(function (d) {
var layer = layers[d] = d3.select(this);
if (d === 'bg') {
_this.bgRect = layer.append('rect').style('pointer-events', 'all');
} else if (isAxisLayer(d)) {
basePaths[d] = layer.append('path').style('fill', 'none');
} else if (d === 'backplot') {
layer.append('g').classed('choroplethlayer', true);
} else if (d === 'frontplot') {
layer.append('g').classed('scatterlayer', true);
} else if (isLineLayer(d)) {
basePaths[d] = layer.append('path').style('fill', 'none').style('stroke-miterlimit', 2);
} else if (isFillLayer(d)) {
basePaths[d] = layer.append('path').style('stroke', 'none');
}
});
join.order();
join.each(function (d) {
var path = basePaths[d];
var adj = constants.layerNameToAdjective[d];
if (d === 'frame') {
path.datum(constants.sphereSVG);
} else if (isLineLayer(d) || isFillLayer(d)) {
path.datum(topojsonFeature(topojson, topojson.objects[d]));
} else if (isAxisLayer(d)) {
path.datum(makeGraticule(d, geoLayout, fullLayout)).call(Color.stroke, geoLayout[d].gridcolor).call(Drawing.dashLine, geoLayout[d].griddash, geoLayout[d].gridwidth);
}
if (isLineLayer(d)) {
path.call(Color.stroke, geoLayout[adj + 'color']).call(Drawing.dashLine, '', geoLayout[adj + 'width']);
} else if (isFillLayer(d)) {
path.call(Color.fill, geoLayout[adj + 'color']);
}
});
};
proto.updateDims = function (fullLayout, geoLayout) {
var b = this.bounds;
var hFrameWidth = (geoLayout.framewidth || 0) / 2;
var l = b[0][0] - hFrameWidth;
var t = b[0][1] - hFrameWidth;
var w = b[1][0] - l + hFrameWidth;
var h = b[1][1] - t + hFrameWidth;
Drawing.setRect(this.clipRect, l, t, w, h);
this.bgRect.call(Drawing.setRect, l, t, w, h).call(Color.fill, geoLayout.bgcolor);
this.xaxis._offset = l;
this.xaxis._length = w;
this.yaxis._offset = t;
this.yaxis._length = h;
};
proto.updateFx = function (fullLayout, geoLayout) {
var _this = this;
var gd = _this.graphDiv;
var bgRect = _this.bgRect;
var dragMode = fullLayout.dragmode;
var clickMode = fullLayout.clickmode;
if (_this.isStatic) return;
function zoomReset() {
var viewInitial = _this.viewInitial;
var updateObj = {};
for (var k in viewInitial) {
updateObj[_this.id + '.' + k] = viewInitial[k];
}
Registry.call('_guiRelayout', gd, updateObj);
gd.emit('plotly_doubleclick', null);
}
function invert(lonlat) {
return _this.projection.invert([lonlat[0] + _this.xaxis._offset, lonlat[1] + _this.yaxis._offset]);
}
var fillRangeItems = function (eventData, poly) {
if (poly.isRect) {
var ranges = eventData.range = {};
ranges[_this.id] = [invert([poly.xmin, poly.ymin]), invert([poly.xmax, poly.ymax])];
} else {
var dataPts = eventData.lassoPoints = {};
dataPts[_this.id] = poly.map(invert);
}
};
// Note: dragOptions is needed to be declared for all dragmodes because
// it's the object that holds persistent selection state.
var dragOptions = {
element: _this.bgRect.node(),
gd: gd,
plotinfo: {
id: _this.id,
xaxis: _this.xaxis,
yaxis: _this.yaxis,
fillRangeItems: fillRangeItems
},
xaxes: [_this.xaxis],
yaxes: [_this.yaxis],
subplot: _this.id,
clickFn: function (numClicks) {
if (numClicks === 2) {
clearOutline(gd);
}
}
};
if (dragMode === 'pan') {
bgRect.node().onmousedown = null;
bgRect.call(createGeoZoom(_this, geoLayout));
bgRect.on('dblclick.zoom', zoomReset);
if (!gd._context._scrollZoom.geo) {
bgRect.on('wheel.zoom', null);
}
} else if (dragMode === 'select' || dragMode === 'lasso') {
bgRect.on('.zoom', null);
dragOptions.prepFn = function (e, startX, startY) {
prepSelect(e, startX, startY, dragOptions, dragMode);
};
dragElement.init(dragOptions);
}
bgRect.on('mousemove', function () {
var lonlat = _this.projection.invert(Lib.getPositionFromD3Event());
if (!lonlat) {
return dragElement.unhover(gd, d3.event);
}
_this.xaxis.p2c = function () {
return lonlat[0];
};
_this.yaxis.p2c = function () {
return lonlat[1];
};
Fx.hover(gd, d3.event, _this.id);
});
bgRect.on('mouseout', function () {
if (gd._dragging) return;
dragElement.unhover(gd, d3.event);
});
bgRect.on('click', function () {
// For select and lasso the dragElement is handling clicks
if (dragMode !== 'select' && dragMode !== 'lasso') {
if (clickMode.indexOf('select') > -1) {
selectOnClick(d3.event, gd, [_this.xaxis], [_this.yaxis], _this.id, dragOptions);
}
if (clickMode.indexOf('event') > -1) {
// TODO: like pie and mapbox, this doesn't support right-click
// actually this one is worse, as right-click starts a pan, or leaves
// select in a weird state.
// Also, only tangentially related, we should cancel hover during pan
Fx.click(gd, d3.event);
}
}
});
};
proto.makeFramework = function () {
var _this = this;
var gd = _this.graphDiv;
var fullLayout = gd._fullLayout;
var clipId = 'clip' + fullLayout._uid + _this.id;
_this.clipDef = fullLayout._clips.append('clipPath').attr('id', clipId);
_this.clipRect = _this.clipDef.append('rect');
_this.framework = d3.select(_this.container).append('g').attr('class', 'geo ' + _this.id).call(Drawing.setClipUrl, clipId, gd);
// sane lonlat to px
_this.project = function (v) {
var px = _this.projection(v);
return px ? [px[0] - _this.xaxis._offset, px[1] - _this.yaxis._offset] : [null, null];
};
_this.xaxis = {
_id: 'x',
c2p: function (v) {
return _this.project(v)[0];
}
};
_this.yaxis = {
_id: 'y',
c2p: function (v) {
return _this.project(v)[1];
}
};
// mock axis for hover formatting
_this.mockAxis = {
type: 'linear',
showexponent: 'all',
exponentformat: 'B'
};
Axes.setConvert(_this.mockAxis, fullLayout);
};
proto.saveViewInitial = function (geoLayout) {
var center = geoLayout.center || {};
var projLayout = geoLayout.projection;
var rotation = projLayout.rotation || {};
this.viewInitial = {
fitbounds: geoLayout.fitbounds,
'projection.scale': projLayout.scale
};
var extra;
if (geoLayout._isScoped) {
extra = {
'center.lon': center.lon,
'center.lat': center.lat
};
} else if (geoLayout._isClipped) {
extra = {
'projection.rotation.lon': rotation.lon,
'projection.rotation.lat': rotation.lat
};
} else {
extra = {
'center.lon': center.lon,
'center.lat': center.lat,
'projection.rotation.lon': rotation.lon
};
}
Lib.extendFlat(this.viewInitial, extra);
};
proto.render = function (mayRedrawOnUpdates) {
if (this._hasMarkerAngles && mayRedrawOnUpdates) {
this.plot(this._geoCalcData, this._fullLayout, [], true);
} else {
this._render();
}
};
// [hot code path] (re)draw all paths which depend on the projection
proto._render = function () {
var projection = this.projection;
var pathFn = projection.getPath();
var k;
function translatePoints(d) {
var lonlatPx = projection(d.lonlat);
return lonlatPx ? strTranslate(lonlatPx[0], lonlatPx[1]) : null;
}
function hideShowPoints(d) {
return projection.isLonLatOverEdges(d.lonlat) ? 'none' : null;
}
for (k in this.basePaths) {
this.basePaths[k].attr('d', pathFn);
}
for (k in this.dataPaths) {
this.dataPaths[k].attr('d', function (d) {
return pathFn(d.geojson);
});
}
for (k in this.dataPoints) {
this.dataPoints[k].attr('display', hideShowPoints).attr('transform', translatePoints); // TODO: need to redraw points with marker angle instead of calling translatePoints
}
};
// Helper that wraps d3[geo + /* Projection name /*]() which:
//
// - adds 'getPath', 'getBounds' convenience methods
// - scopes logic related to 'clipAngle'
// - adds 'isLonLatOverEdges' method
// - sets projection precision
// - sets methods that aren't always defined depending
// on the projection type to a dummy 'd3-esque' function,
//
// This wrapper alleviates subsequent code of (many) annoying if-statements.
function getProjection(geoLayout) {
var projLayout = geoLayout.projection;
var projType = projLayout.type;
var projName = constants.projNames[projType];
// uppercase the first letter and add geo to the start of method name
projName = 'geo' + Lib.titleCase(projName);
var projFn = geo[projName] || geoProjection[projName];
var projection = projFn();
var clipAngle = geoLayout._isSatellite ? Math.acos(1 / projLayout.distance) * 180 / Math.PI : geoLayout._isClipped ? constants.lonaxisSpan[projType] / 2 : null;
var methods = ['center', 'rotate', 'parallels', 'clipExtent'];
var dummyFn = function (_) {
return _ ? projection : [];
};
for (var i = 0; i < methods.length; i++) {
var m = methods[i];
if (typeof projection[m] !== 'function') {
projection[m] = dummyFn;
}
}
projection.isLonLatOverEdges = function (lonlat) {
if (projection(lonlat) === null) {
return true;
}
if (clipAngle) {
var r = projection.rotate();
var angle = geoDistance(lonlat, [-r[0], -r[1]]);
var maxAngle = clipAngle * Math.PI / 180;
return angle > maxAngle;
} else {
return false;
}
};
projection.getPath = function () {
return geoPath().projection(projection);
};
projection.getBounds = function (object) {
return projection.getPath().bounds(object);
};
projection.precision(constants.precision);
if (geoLayout._isSatellite) {
projection.tilt(projLayout.tilt).distance(projLayout.distance);
}
if (clipAngle) {
projection.clipAngle(clipAngle - constants.clipPad);
}
return projection;
}
function makeGraticule(axisName, geoLayout, fullLayout) {
// equivalent to the d3 "ε"
var epsilon = 1e-6;
// same as the geoGraticule default
var precision = 2.5;
var axLayout = geoLayout[axisName];
var scopeDefaults = constants.scopeDefaults[geoLayout.scope];
var rng;
var oppRng;
var coordFn;
if (axisName === 'lonaxis') {
rng = scopeDefaults.lonaxisRange;
oppRng = scopeDefaults.lataxisRange;
coordFn = function (v, l) {
return [v, l];
};
} else if (axisName === 'lataxis') {
rng = scopeDefaults.lataxisRange;
oppRng = scopeDefaults.lonaxisRange;
coordFn = function (v, l) {
return [l, v];
};
}
var dummyAx = {
type: 'linear',
range: [rng[0], rng[1] - epsilon],
tick0: axLayout.tick0,
dtick: axLayout.dtick
};
Axes.setConvert(dummyAx, fullLayout);
var vals = Axes.calcTicks(dummyAx);
// remove duplicate on antimeridian
if (!geoLayout.isScoped && axisName === 'lonaxis') {
vals.pop();
}
var len = vals.length;
var coords = new Array(len);
for (var i = 0; i < len; i++) {
var v = vals[i].x;
var line = coords[i] = [];
for (var l = oppRng[0]; l < oppRng[1] + precision; l += precision) {
line.push(coordFn(v, l));
}
}
return {
type: 'MultiLineString',
coordinates: coords
};
}
// Returns polygon GeoJSON corresponding to lon/lat range box
// with well-defined direction
//
// Note that clipPad padding is added around range to avoid aliasing.
function makeRangeBox(lon, lat) {
var clipPad = constants.clipPad;
var lon0 = lon[0] + clipPad;
var lon1 = lon[1] - clipPad;
var lat0 = lat[0] + clipPad;
var lat1 = lat[1] - clipPad;
// to cross antimeridian w/o ambiguity
if (lon0 > 0 && lon1 < 0) lon1 += 360;
var dlon4 = (lon1 - lon0) / 4;
return {
type: 'Polygon',
coordinates: [[[lon0, lat0], [lon0, lat1], [lon0 + dlon4, lat1], [lon0 + 2 * dlon4, lat1], [lon0 + 3 * dlon4, lat1], [lon1, lat1], [lon1, lat0], [lon1 - dlon4, lat0], [lon1 - 2 * dlon4, lat0], [lon1 - 3 * dlon4, lat0], [lon0, lat0]]]
};
}
/***/ }),
/***/ 10816:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var getSubplotCalcData = (__webpack_require__(84888)/* .getSubplotCalcData */ .KY);
var counterRegex = (__webpack_require__(3400).counterRegex);
var createGeo = __webpack_require__(43520);
var GEO = 'geo';
var counter = counterRegex(GEO);
var attributes = {};
attributes[GEO] = {
valType: 'subplotid',
dflt: GEO,
editType: 'calc'
};
function plotGeo(gd) {
var fullLayout = gd._fullLayout;
var calcData = gd.calcdata;
var geoIds = fullLayout._subplots[GEO];
for (var i = 0; i < geoIds.length; i++) {
var geoId = geoIds[i];
var geoCalcData = getSubplotCalcData(calcData, GEO, geoId);
var geoLayout = fullLayout[geoId];
var geo = geoLayout._subplot;
if (!geo) {
geo = createGeo({
id: geoId,
graphDiv: gd,
container: fullLayout._geolayer.node(),
topojsonURL: gd._context.topojsonURL,
staticPlot: gd._context.staticPlot
});
fullLayout[geoId]._subplot = geo;
}
geo.plot(geoCalcData, fullLayout, gd._promises);
}
}
function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldGeoKeys = oldFullLayout._subplots[GEO] || [];
for (var i = 0; i < oldGeoKeys.length; i++) {
var oldGeoKey = oldGeoKeys[i];
var oldGeo = oldFullLayout[oldGeoKey]._subplot;
if (!newFullLayout[oldGeoKey] && !!oldGeo) {
oldGeo.framework.remove();
oldGeo.clipDef.remove();
}
}
}
function updateFx(gd) {
var fullLayout = gd._fullLayout;
var subplotIds = fullLayout._subplots[GEO];
for (var i = 0; i < subplotIds.length; i++) {
var subplotLayout = fullLayout[subplotIds[i]];
var subplotObj = subplotLayout._subplot;
subplotObj.updateFx(fullLayout, subplotLayout);
}
}
module.exports = {
attr: GEO,
name: GEO,
idRoot: GEO,
idRegex: counter,
attrRegex: counter,
attributes: attributes,
layoutAttributes: __webpack_require__(40384),
supplyLayoutDefaults: __webpack_require__(86920),
plot: plotGeo,
updateFx: updateFx,
clean: clean
};
/***/ }),
/***/ 40384:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorAttrs = __webpack_require__(22548);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var constants = __webpack_require__(79552);
var overrideAll = (__webpack_require__(67824).overrideAll);
var sortObjectKeys = __webpack_require__(95376);
var geoAxesAttrs = {
range: {
valType: 'info_array',
items: [{
valType: 'number'
}, {
valType: 'number'
}]
},
showgrid: {
valType: 'boolean',
dflt: false
},
tick0: {
valType: 'number',
dflt: 0
},
dtick: {
valType: 'number'
},
gridcolor: {
valType: 'color',
dflt: colorAttrs.lightLine
},
gridwidth: {
valType: 'number',
min: 0,
dflt: 1
},
griddash: dash
};
var attrs = module.exports = overrideAll({
domain: domainAttrs({
name: 'geo'
}, {}),
fitbounds: {
valType: 'enumerated',
values: [false, 'locations', 'geojson'],
dflt: false,
editType: 'plot'
},
resolution: {
valType: 'enumerated',
values: [110, 50],
dflt: 110,
coerceNumber: true
},
scope: {
valType: 'enumerated',
values: sortObjectKeys(constants.scopeDefaults),
dflt: 'world'
},
projection: {
type: {
valType: 'enumerated',
values: sortObjectKeys(constants.projNames)
},
rotation: {
lon: {
valType: 'number'
},
lat: {
valType: 'number'
},
roll: {
valType: 'number'
}
},
tilt: {
valType: 'number',
dflt: 0
},
distance: {
valType: 'number',
min: 1.001,
dflt: 2
},
parallels: {
valType: 'info_array',
items: [{
valType: 'number'
}, {
valType: 'number'
}]
},
scale: {
valType: 'number',
min: 0,
dflt: 1
}
},
center: {
lon: {
valType: 'number'
},
lat: {
valType: 'number'
}
},
visible: {
valType: 'boolean',
dflt: true
},
showcoastlines: {
valType: 'boolean'
},
coastlinecolor: {
valType: 'color',
dflt: colorAttrs.defaultLine
},
coastlinewidth: {
valType: 'number',
min: 0,
dflt: 1
},
showland: {
valType: 'boolean',
dflt: false
},
landcolor: {
valType: 'color',
dflt: constants.landColor
},
showocean: {
valType: 'boolean',
dflt: false
},
oceancolor: {
valType: 'color',
dflt: constants.waterColor
},
showlakes: {
valType: 'boolean',
dflt: false
},
lakecolor: {
valType: 'color',
dflt: constants.waterColor
},
showrivers: {
valType: 'boolean',
dflt: false
},
rivercolor: {
valType: 'color',
dflt: constants.waterColor
},
riverwidth: {
valType: 'number',
min: 0,
dflt: 1
},
showcountries: {
valType: 'boolean'
},
countrycolor: {
valType: 'color',
dflt: colorAttrs.defaultLine
},
countrywidth: {
valType: 'number',
min: 0,
dflt: 1
},
showsubunits: {
valType: 'boolean'
},
subunitcolor: {
valType: 'color',
dflt: colorAttrs.defaultLine
},
subunitwidth: {
valType: 'number',
min: 0,
dflt: 1
},
showframe: {
valType: 'boolean'
},
framecolor: {
valType: 'color',
dflt: colorAttrs.defaultLine
},
framewidth: {
valType: 'number',
min: 0,
dflt: 1
},
bgcolor: {
valType: 'color',
dflt: colorAttrs.background
},
lonaxis: geoAxesAttrs,
lataxis: geoAxesAttrs
}, 'plot', 'from-root');
// set uirevision outside of overrideAll so it can be `editType: 'none'`
attrs.uirevision = {
valType: 'any',
editType: 'none'
};
/***/ }),
/***/ 86920:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleSubplotDefaults = __webpack_require__(168);
var getSubplotData = (__webpack_require__(84888)/* .getSubplotData */ .op);
var constants = __webpack_require__(79552);
var layoutAttributes = __webpack_require__(40384);
var axesNames = constants.axesNames;
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
handleSubplotDefaults(layoutIn, layoutOut, fullData, {
type: 'geo',
attributes: layoutAttributes,
handleDefaults: handleGeoDefaults,
fullData: fullData,
partition: 'y'
});
};
function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce, opts) {
var subplotData = getSubplotData(opts.fullData, 'geo', opts.id);
var traceIndices = subplotData.map(function (t) {
return t._expandedIndex;
});
var resolution = coerce('resolution');
var scope = coerce('scope');
var scopeParams = constants.scopeDefaults[scope];
var projType = coerce('projection.type', scopeParams.projType);
var isAlbersUsa = geoLayoutOut._isAlbersUsa = projType === 'albers usa';
// no other scopes are allowed for 'albers usa' projection
if (isAlbersUsa) scope = geoLayoutOut.scope = 'usa';
var isScoped = geoLayoutOut._isScoped = scope !== 'world';
var isSatellite = geoLayoutOut._isSatellite = projType === 'satellite';
var isConic = geoLayoutOut._isConic = projType.indexOf('conic') !== -1 || projType === 'albers';
var isClipped = geoLayoutOut._isClipped = !!constants.lonaxisSpan[projType];
if (geoLayoutIn.visible === false) {
// should override template.layout.geo.show* - see issue 4482
// make a copy
var newTemplate = Lib.extendDeep({}, geoLayoutOut._template);
// override show*
newTemplate.showcoastlines = false;
newTemplate.showcountries = false;
newTemplate.showframe = false;
newTemplate.showlakes = false;
newTemplate.showland = false;
newTemplate.showocean = false;
newTemplate.showrivers = false;
newTemplate.showsubunits = false;
if (newTemplate.lonaxis) newTemplate.lonaxis.showgrid = false;
if (newTemplate.lataxis) newTemplate.lataxis.showgrid = false;
// set ref to copy
geoLayoutOut._template = newTemplate;
}
var visible = coerce('visible');
var show;
for (var i = 0; i < axesNames.length; i++) {
var axisName = axesNames[i];
var dtickDflt = [30, 10][i];
var rangeDflt;
if (isScoped) {
rangeDflt = scopeParams[axisName + 'Range'];
} else {
var dfltSpans = constants[axisName + 'Span'];
var hSpan = (dfltSpans[projType] || dfltSpans['*']) / 2;
var rot = coerce('projection.rotation.' + axisName.substr(0, 3), scopeParams.projRotate[i]);
rangeDflt = [rot - hSpan, rot + hSpan];
}
var range = coerce(axisName + '.range', rangeDflt);
coerce(axisName + '.tick0');
coerce(axisName + '.dtick', dtickDflt);
show = coerce(axisName + '.showgrid', !visible ? false : undefined);
if (show) {
coerce(axisName + '.gridcolor');
coerce(axisName + '.gridwidth');
coerce(axisName + '.griddash');
}
// mock axis for autorange computations
geoLayoutOut[axisName]._ax = {
type: 'linear',
_id: axisName.slice(0, 3),
_traceIndices: traceIndices,
setScale: Lib.identity,
c2l: Lib.identity,
r2l: Lib.identity,
autorange: true,
range: range.slice(),
_m: 1,
_input: {}
};
}
var lonRange = geoLayoutOut.lonaxis.range;
var latRange = geoLayoutOut.lataxis.range;
// to cross antimeridian w/o ambiguity
var lon0 = lonRange[0];
var lon1 = lonRange[1];
if (lon0 > 0 && lon1 < 0) lon1 += 360;
var centerLon = (lon0 + lon1) / 2;
var projLon;
if (!isAlbersUsa) {
var dfltProjRotate = isScoped ? scopeParams.projRotate : [centerLon, 0, 0];
projLon = coerce('projection.rotation.lon', dfltProjRotate[0]);
coerce('projection.rotation.lat', dfltProjRotate[1]);
coerce('projection.rotation.roll', dfltProjRotate[2]);
show = coerce('showcoastlines', !isScoped && visible);
if (show) {
coerce('coastlinecolor');
coerce('coastlinewidth');
}
show = coerce('showocean', !visible ? false : undefined);
if (show) coerce('oceancolor');
}
var centerLonDflt;
var centerLatDflt;
if (isAlbersUsa) {
// 'albers usa' does not have a 'center',
// these values were found using via:
// projection.invert([geoLayout.center.lon, geoLayoutIn.center.lat])
centerLonDflt = -96.6;
centerLatDflt = 38.7;
} else {
centerLonDflt = isScoped ? centerLon : projLon;
centerLatDflt = (latRange[0] + latRange[1]) / 2;
}
coerce('center.lon', centerLonDflt);
coerce('center.lat', centerLatDflt);
if (isSatellite) {
coerce('projection.tilt');
coerce('projection.distance');
}
if (isConic) {
var dfltProjParallels = scopeParams.projParallels || [0, 60];
coerce('projection.parallels', dfltProjParallels);
}
coerce('projection.scale');
show = coerce('showland', !visible ? false : undefined);
if (show) coerce('landcolor');
show = coerce('showlakes', !visible ? false : undefined);
if (show) coerce('lakecolor');
show = coerce('showrivers', !visible ? false : undefined);
if (show) {
coerce('rivercolor');
coerce('riverwidth');
}
show = coerce('showcountries', isScoped && scope !== 'usa' && visible);
if (show) {
coerce('countrycolor');
coerce('countrywidth');
}
if (scope === 'usa' || scope === 'north america' && resolution === 50) {
// Only works for:
// USA states at 110m
// USA states + Canada provinces at 50m
coerce('showsubunits', visible);
coerce('subunitcolor');
coerce('subunitwidth');
}
if (!isScoped) {
// Does not work in non-world scopes
show = coerce('showframe', visible);
if (show) {
coerce('framecolor');
coerce('framewidth');
}
}
coerce('bgcolor');
var fitBounds = coerce('fitbounds');
// clear attributes that will get auto-filled later
if (fitBounds) {
delete geoLayoutOut.projection.scale;
if (isScoped) {
delete geoLayoutOut.center.lon;
delete geoLayoutOut.center.lat;
} else if (isClipped) {
delete geoLayoutOut.center.lon;
delete geoLayoutOut.center.lat;
delete geoLayoutOut.projection.rotation.lon;
delete geoLayoutOut.projection.rotation.lat;
delete geoLayoutOut.lonaxis.range;
delete geoLayoutOut.lataxis.range;
} else {
delete geoLayoutOut.center.lon;
delete geoLayoutOut.center.lat;
delete geoLayoutOut.projection.rotation.lon;
}
}
}
/***/ }),
/***/ 79248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var radians = Math.PI / 180;
var degrees = 180 / Math.PI;
var zoomstartStyle = {
cursor: 'pointer'
};
var zoomendStyle = {
cursor: 'auto'
};
function createGeoZoom(geo, geoLayout) {
var projection = geo.projection;
var zoomConstructor;
if (geoLayout._isScoped) {
zoomConstructor = zoomScoped;
} else if (geoLayout._isClipped) {
zoomConstructor = zoomClipped;
} else {
zoomConstructor = zoomNonClipped;
}
// TODO add a conic-specific zoom
return zoomConstructor(geo, projection);
}
module.exports = createGeoZoom;
// common to all zoom types
function initZoom(geo, projection) {
return d3.behavior.zoom().translate(projection.translate()).scale(projection.scale());
}
// sync zoom updates with user & full layout
function sync(geo, projection, cb) {
var id = geo.id;
var gd = geo.graphDiv;
var layout = gd.layout;
var userOpts = layout[id];
var fullLayout = gd._fullLayout;
var fullOpts = fullLayout[id];
var preGUI = {};
var eventData = {};
function set(propStr, val) {
preGUI[id + '.' + propStr] = Lib.nestedProperty(userOpts, propStr).get();
Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, preGUI);
var fullNp = Lib.nestedProperty(fullOpts, propStr);
if (fullNp.get() !== val) {
fullNp.set(val);
Lib.nestedProperty(userOpts, propStr).set(val);
eventData[id + '.' + propStr] = val;
}
}
cb(set);
set('projection.scale', projection.scale() / geo.fitScale);
set('fitbounds', false);
gd.emit('plotly_relayout', eventData);
}
// zoom for scoped projections
function zoomScoped(geo, projection) {
var zoom = initZoom(geo, projection);
function handleZoomstart() {
d3.select(this).style(zoomstartStyle);
}
function handleZoom() {
projection.scale(d3.event.scale).translate(d3.event.translate);
geo.render(true);
var center = projection.invert(geo.midPt);
geo.graphDiv.emit('plotly_relayouting', {
'geo.projection.scale': projection.scale() / geo.fitScale,
'geo.center.lon': center[0],
'geo.center.lat': center[1]
});
}
function syncCb(set) {
var center = projection.invert(geo.midPt);
set('center.lon', center[0]);
set('center.lat', center[1]);
}
function handleZoomend() {
d3.select(this).style(zoomendStyle);
sync(geo, projection, syncCb);
}
zoom.on('zoomstart', handleZoomstart).on('zoom', handleZoom).on('zoomend', handleZoomend);
return zoom;
}
// zoom for non-clipped projections
function zoomNonClipped(geo, projection) {
var zoom = initZoom(geo, projection);
var INSIDETOLORANCEPXS = 2;
var mouse0, rotate0, translate0, lastRotate, zoomPoint, mouse1, rotate1, point1, didZoom;
function position(x) {
return projection.invert(x);
}
function outside(x) {
var pos = position(x);
if (!pos) return true;
var pt = projection(pos);
return Math.abs(pt[0] - x[0]) > INSIDETOLORANCEPXS || Math.abs(pt[1] - x[1]) > INSIDETOLORANCEPXS;
}
function handleZoomstart() {
d3.select(this).style(zoomstartStyle);
mouse0 = d3.mouse(this);
rotate0 = projection.rotate();
translate0 = projection.translate();
lastRotate = rotate0;
zoomPoint = position(mouse0);
}
function handleZoom() {
mouse1 = d3.mouse(this);
if (outside(mouse0)) {
zoom.scale(projection.scale());
zoom.translate(projection.translate());
return;
}
projection.scale(d3.event.scale);
projection.translate([translate0[0], d3.event.translate[1]]);
if (!zoomPoint) {
mouse0 = mouse1;
zoomPoint = position(mouse0);
} else if (position(mouse1)) {
point1 = position(mouse1);
rotate1 = [lastRotate[0] + (point1[0] - zoomPoint[0]), rotate0[1], rotate0[2]];
projection.rotate(rotate1);
lastRotate = rotate1;
}
didZoom = true;
geo.render(true);
var rotate = projection.rotate();
var center = projection.invert(geo.midPt);
geo.graphDiv.emit('plotly_relayouting', {
'geo.projection.scale': projection.scale() / geo.fitScale,
'geo.center.lon': center[0],
'geo.center.lat': center[1],
'geo.projection.rotation.lon': -rotate[0]
});
}
function handleZoomend() {
d3.select(this).style(zoomendStyle);
if (didZoom) sync(geo, projection, syncCb);
}
function syncCb(set) {
var rotate = projection.rotate();
var center = projection.invert(geo.midPt);
set('projection.rotation.lon', -rotate[0]);
set('center.lon', center[0]);
set('center.lat', center[1]);
}
zoom.on('zoomstart', handleZoomstart).on('zoom', handleZoom).on('zoomend', handleZoomend);
return zoom;
}
// zoom for clipped projections
// inspired by https://www.jasondavies.com/maps/d3.geo.zoom.js
function zoomClipped(geo, projection) {
var view = {
r: projection.rotate(),
k: projection.scale()
};
var zoom = initZoom(geo, projection);
var event = d3eventDispatch(zoom, 'zoomstart', 'zoom', 'zoomend');
var zooming = 0;
var zoomOn = zoom.on;
var zoomPoint;
zoom.on('zoomstart', function () {
d3.select(this).style(zoomstartStyle);
var mouse0 = d3.mouse(this);
var rotate0 = projection.rotate();
var lastRotate = rotate0;
var translate0 = projection.translate();
var q = quaternionFromEuler(rotate0);
zoomPoint = position(projection, mouse0);
zoomOn.call(zoom, 'zoom', function () {
var mouse1 = d3.mouse(this);
projection.scale(view.k = d3.event.scale);
if (!zoomPoint) {
// if no zoomPoint, the mouse wasn't over the actual geography yet
// maybe this point is the start... we'll find out next time!
mouse0 = mouse1;
zoomPoint = position(projection, mouse0);
} else if (position(projection, mouse1)) {
// check if the point is on the map
// if not, don't do anything new but scale
// if it is, then we can assume between will exist below
// so we don't need the 'bank' function, whatever that is.
// go back to original projection temporarily
// except for scale... that's kind of independent?
projection.rotate(rotate0).translate(translate0);
// calculate the new params
var point1 = position(projection, mouse1);
var between = rotateBetween(zoomPoint, point1);
var newEuler = eulerFromQuaternion(multiply(q, between));
var rotateAngles = view.r = unRoll(newEuler, zoomPoint, lastRotate);
if (!isFinite(rotateAngles[0]) || !isFinite(rotateAngles[1]) || !isFinite(rotateAngles[2])) {
rotateAngles = lastRotate;
}
// update the projection
projection.rotate(rotateAngles);
lastRotate = rotateAngles;
}
zoomed(event.of(this, arguments));
});
zoomstarted(event.of(this, arguments));
}).on('zoomend', function () {
d3.select(this).style(zoomendStyle);
zoomOn.call(zoom, 'zoom', null);
zoomended(event.of(this, arguments));
sync(geo, projection, syncCb);
}).on('zoom.redraw', function () {
geo.render(true);
var _rotate = projection.rotate();
geo.graphDiv.emit('plotly_relayouting', {
'geo.projection.scale': projection.scale() / geo.fitScale,
'geo.projection.rotation.lon': -_rotate[0],
'geo.projection.rotation.lat': -_rotate[1]
});
});
function zoomstarted(dispatch) {
if (!zooming++) dispatch({
type: 'zoomstart'
});
}
function zoomed(dispatch) {
dispatch({
type: 'zoom'
});
}
function zoomended(dispatch) {
if (! --zooming) dispatch({
type: 'zoomend'
});
}
function syncCb(set) {
var _rotate = projection.rotate();
set('projection.rotation.lon', -_rotate[0]);
set('projection.rotation.lat', -_rotate[1]);
}
return d3.rebind(zoom, event, 'on');
}
// -- helper functions for zoomClipped
function position(projection, point) {
var spherical = projection.invert(point);
return spherical && isFinite(spherical[0]) && isFinite(spherical[1]) && cartesian(spherical);
}
function quaternionFromEuler(euler) {
var lambda = 0.5 * euler[0] * radians;
var phi = 0.5 * euler[1] * radians;
var gamma = 0.5 * euler[2] * radians;
var sinLambda = Math.sin(lambda);
var cosLambda = Math.cos(lambda);
var sinPhi = Math.sin(phi);
var cosPhi = Math.cos(phi);
var sinGamma = Math.sin(gamma);
var cosGamma = Math.cos(gamma);
return [cosLambda * cosPhi * cosGamma + sinLambda * sinPhi * sinGamma, sinLambda * cosPhi * cosGamma - cosLambda * sinPhi * sinGamma, cosLambda * sinPhi * cosGamma + sinLambda * cosPhi * sinGamma, cosLambda * cosPhi * sinGamma - sinLambda * sinPhi * cosGamma];
}
function multiply(a, b) {
var a0 = a[0];
var a1 = a[1];
var a2 = a[2];
var a3 = a[3];
var b0 = b[0];
var b1 = b[1];
var b2 = b[2];
var b3 = b[3];
return [a0 * b0 - a1 * b1 - a2 * b2 - a3 * b3, a0 * b1 + a1 * b0 + a2 * b3 - a3 * b2, a0 * b2 - a1 * b3 + a2 * b0 + a3 * b1, a0 * b3 + a1 * b2 - a2 * b1 + a3 * b0];
}
function rotateBetween(a, b) {
if (!a || !b) return;
var axis = cross(a, b);
var norm = Math.sqrt(dot(axis, axis));
var halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, dot(a, b))));
var k = Math.sin(halfgamma) / norm;
return norm && [Math.cos(halfgamma), axis[2] * k, -axis[1] * k, axis[0] * k];
}
// input:
// rotateAngles: a calculated set of Euler angles
// pt: a point (cartesian in 3-space) to keep fixed
// roll0: an initial roll, to be preserved
// output:
// a set of Euler angles that preserve the projection of pt
// but set roll (output[2]) equal to roll0
// note that this doesn't depend on the particular projection,
// just on the rotation angles
function unRoll(rotateAngles, pt, lastRotate) {
// calculate the fixed point transformed by these Euler angles
// but with the desired roll undone
var ptRotated = rotateCartesian(pt, 2, rotateAngles[0]);
ptRotated = rotateCartesian(ptRotated, 1, rotateAngles[1]);
ptRotated = rotateCartesian(ptRotated, 0, rotateAngles[2] - lastRotate[2]);
var x = pt[0];
var y = pt[1];
var z = pt[2];
var f = ptRotated[0];
var g = ptRotated[1];
var h = ptRotated[2];
// the following essentially solves:
// ptRotated = rotateCartesian(rotateCartesian(pt, 2, newYaw), 1, newPitch)
// for newYaw and newPitch, as best it can
var theta = Math.atan2(y, x) * degrees;
var a = Math.sqrt(x * x + y * y);
var b;
var newYaw1;
if (Math.abs(g) > a) {
newYaw1 = (g > 0 ? 90 : -90) - theta;
b = 0;
} else {
newYaw1 = Math.asin(g / a) * degrees - theta;
b = Math.sqrt(a * a - g * g);
}
var newYaw2 = 180 - newYaw1 - 2 * theta;
var newPitch1 = (Math.atan2(h, f) - Math.atan2(z, b)) * degrees;
var newPitch2 = (Math.atan2(h, f) - Math.atan2(z, -b)) * degrees;
// which is closest to lastRotate[0,1]: newYaw/Pitch or newYaw2/Pitch2?
var dist1 = angleDistance(lastRotate[0], lastRotate[1], newYaw1, newPitch1);
var dist2 = angleDistance(lastRotate[0], lastRotate[1], newYaw2, newPitch2);
if (dist1 <= dist2) return [newYaw1, newPitch1, lastRotate[2]];else return [newYaw2, newPitch2, lastRotate[2]];
}
function angleDistance(yaw0, pitch0, yaw1, pitch1) {
var dYaw = angleMod(yaw1 - yaw0);
var dPitch = angleMod(pitch1 - pitch0);
return Math.sqrt(dYaw * dYaw + dPitch * dPitch);
}
// reduce an angle in degrees to [-180,180]
function angleMod(angle) {
return (angle % 360 + 540) % 360 - 180;
}
// rotate a cartesian vector
// axis is 0 (x), 1 (y), or 2 (z)
// angle is in degrees
function rotateCartesian(vector, axis, angle) {
var angleRads = angle * radians;
var vectorOut = vector.slice();
var ax1 = axis === 0 ? 1 : 0;
var ax2 = axis === 2 ? 1 : 2;
var cosa = Math.cos(angleRads);
var sina = Math.sin(angleRads);
vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;
vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;
return vectorOut;
}
function eulerFromQuaternion(q) {
return [Math.atan2(2 * (q[0] * q[1] + q[2] * q[3]), 1 - 2 * (q[1] * q[1] + q[2] * q[2])) * degrees, Math.asin(Math.max(-1, Math.min(1, 2 * (q[0] * q[2] - q[3] * q[1])))) * degrees, Math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] * q[2] + q[3] * q[3])) * degrees];
}
function cartesian(spherical) {
var lambda = spherical[0] * radians;
var phi = spherical[1] * radians;
var cosPhi = Math.cos(phi);
return [cosPhi * Math.cos(lambda), cosPhi * Math.sin(lambda), Math.sin(phi)];
}
function dot(a, b) {
var s = 0;
for (var i = 0, n = a.length; i < n; ++i) s += a[i] * b[i];
return s;
}
function cross(a, b) {
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
}
// Like d3.dispatch, but for custom events abstracting native UI events. These
// events have a target component (such as a brush), a target element (such as
// the svg:g element containing the brush) and the standard arguments `d` (the
// target element's data) and `i` (the selection index of the target element).
function d3eventDispatch(target) {
var i = 0;
var n = arguments.length;
var argumentz = [];
while (++i < n) argumentz.push(arguments[i]);
var dispatch = d3.dispatch.apply(null, argumentz);
// Creates a dispatch context for the specified `thiz` (typically, the target
// DOM element that received the source event) and `argumentz` (typically, the
// data `d` and index `i` of the target element). The returned function can be
// used to dispatch an event to any registered listeners; the function takes a
// single argument as input, being the event to dispatch. The event must have
// a "type" attribute which corresponds to a type registered in the
// constructor. This context will automatically populate the "sourceEvent" and
// "target" attributes of the event, as well as setting the `d3.event` global
// for the duration of the notification.
dispatch.of = function (thiz, argumentz) {
return function (e1) {
var e0;
try {
e0 = e1.sourceEvent = d3.event;
e1.target = target;
d3.event = e1;
dispatch[e1.type].apply(thiz, argumentz);
} finally {
d3.event = e0;
}
};
};
return dispatch;
}
/***/ }),
/***/ 84888:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var SUBPLOT_PATTERN = (__webpack_require__(33816).SUBPLOT_PATTERN);
/**
* Get calcdata trace(s) associated with a given subplot
*
* @param {array} calcData: as in gd.calcdata
* @param {string} type: subplot type
* @param {string} subplotId: subplot id to look for
*
* @return {array} array of calcdata traces
*/
exports.KY = function (calcData, type, subplotId) {
var basePlotModule = Registry.subplotsRegistry[type];
if (!basePlotModule) return [];
var attr = basePlotModule.attr;
var subplotCalcData = [];
for (var i = 0; i < calcData.length; i++) {
var calcTrace = calcData[i];
var trace = calcTrace[0].trace;
if (trace[attr] === subplotId) subplotCalcData.push(calcTrace);
}
return subplotCalcData;
};
/**
* Get calcdata trace(s) that can be plotted with a given module
* NOTE: this isn't necessarily just exactly matching trace type,
* if multiple trace types use the same plotting routine, they will be
* collected here.
* In order to not plot the same thing multiple times, we return two arrays,
* the calcdata we *will* plot with this module, and the ones we *won't*
*
* @param {array} calcdata: as in gd.calcdata
* @param {object|string|fn} arg1:
* the plotting module, or its name, or its plot method
* @param {int} arg2: (optional) zorder to filter on
* @return {array[array]} [foundCalcdata, remainingCalcdata]
*/
exports._M = function (calcdata, arg1, arg2) {
var moduleCalcData = [];
var remainingCalcData = [];
var plotMethod;
if (typeof arg1 === 'string') {
plotMethod = Registry.getModule(arg1).plot;
} else if (typeof arg1 === 'function') {
plotMethod = arg1;
} else {
plotMethod = arg1.plot;
}
if (!plotMethod) {
return [moduleCalcData, calcdata];
}
var zorder = arg2;
for (var i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var trace = cd[0].trace;
var filterByZ = trace.zorder !== undefined;
// N.B.
// - 'legendonly' traces do not make it past here
// - skip over 'visible' traces that got trimmed completely during calc transforms
if (trace.visible !== true || trace._length === 0) continue;
// group calcdata trace not by 'module' (as the name of this function
// would suggest), but by 'module plot method' so that if some traces
// share the same module plot method (e.g. bar and histogram), we
// only call it one!
if (trace._module && trace._module.plot === plotMethod && (!filterByZ || trace.zorder === zorder)) {
moduleCalcData.push(cd);
} else {
remainingCalcData.push(cd);
}
}
return [moduleCalcData, remainingCalcData];
};
/**
* Get the data trace(s) associated with a given subplot.
*
* @param {array} data plotly full data array.
* @param {string} type subplot type to look for.
* @param {string} subplotId subplot id to look for.
*
* @return {array} list of trace objects.
*
*/
exports.op = function getSubplotData(data, type, subplotId) {
if (!Registry.subplotsRegistry[type]) return [];
var attr = Registry.subplotsRegistry[type].attr;
var subplotData = [];
var trace, subplotX, subplotY;
if (type === 'gl2d') {
var spmatch = subplotId.match(SUBPLOT_PATTERN);
subplotX = 'x' + spmatch[1];
subplotY = 'y' + spmatch[2];
}
for (var i = 0; i < data.length; i++) {
trace = data[i];
if (type === 'gl2d' && Registry.traceIs(trace, 'gl2d')) {
if (trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) {
subplotData.push(trace);
}
} else {
if (trace[attr] === subplotId) subplotData.push(trace);
}
}
return subplotData;
};
/***/ }),
/***/ 2428:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var mouseChange = __webpack_require__(62644);
var mouseWheel = __webpack_require__(97264);
var mouseOffset = __webpack_require__(29128);
var cartesianConstants = __webpack_require__(33816);
var hasPassive = __webpack_require__(89184);
module.exports = createCamera;
function Camera2D(element, plot) {
this.element = element;
this.plot = plot;
this.mouseListener = null;
this.wheelListener = null;
this.lastInputTime = Date.now();
this.lastPos = [0, 0];
this.boxEnabled = false;
this.boxInited = false;
this.boxStart = [0, 0];
this.boxEnd = [0, 0];
this.dragStart = [0, 0];
}
function createCamera(scene) {
var element = scene.mouseContainer;
var plot = scene.glplot;
var result = new Camera2D(element, plot);
function unSetAutoRange() {
scene.xaxis.autorange = false;
scene.yaxis.autorange = false;
}
function getSubplotConstraint() {
// note: this assumes we only have one x and one y axis on this subplot
// when this constraint is lifted this block won't make sense
var constraints = scene.graphDiv._fullLayout._axisConstraintGroups;
var xaId = scene.xaxis._id;
var yaId = scene.yaxis._id;
for (var i = 0; i < constraints.length; i++) {
if (constraints[i][xaId] !== -1) {
if (constraints[i][yaId] !== -1) return true;
break;
}
}
return false;
}
result.mouseListener = mouseChange(element, handleInteraction);
// enable simple touch interactions
element.addEventListener('touchstart', function (ev) {
var xy = mouseOffset(ev.changedTouches[0], element);
handleInteraction(0, xy[0], xy[1]);
handleInteraction(1, xy[0], xy[1]);
ev.preventDefault();
}, hasPassive ? {
passive: false
} : false);
element.addEventListener('touchmove', function (ev) {
ev.preventDefault();
var xy = mouseOffset(ev.changedTouches[0], element);
handleInteraction(1, xy[0], xy[1]);
ev.preventDefault();
}, hasPassive ? {
passive: false
} : false);
element.addEventListener('touchend', function (ev) {
handleInteraction(0, result.lastPos[0], result.lastPos[1]);
ev.preventDefault();
}, hasPassive ? {
passive: false
} : false);
function handleInteraction(buttons, x, y) {
var dataBox = scene.calcDataBox();
var viewBox = plot.viewBox;
var lastX = result.lastPos[0];
var lastY = result.lastPos[1];
var MINDRAG = cartesianConstants.MINDRAG * plot.pixelRatio;
var MINZOOM = cartesianConstants.MINZOOM * plot.pixelRatio;
var dx, dy;
x *= plot.pixelRatio;
y *= plot.pixelRatio;
// mouseChange gives y about top; convert to about bottom
y = viewBox[3] - viewBox[1] - y;
function updateRange(i0, start, end) {
var range0 = Math.min(start, end);
var range1 = Math.max(start, end);
if (range0 !== range1) {
dataBox[i0] = range0;
dataBox[i0 + 2] = range1;
result.dataBox = dataBox;
scene.setRanges(dataBox);
} else {
scene.selectBox.selectBox = [0, 0, 1, 1];
scene.glplot.setDirty();
}
}
switch (scene.fullLayout.dragmode) {
case 'zoom':
if (buttons) {
var dataX = x / (viewBox[2] - viewBox[0]) * (dataBox[2] - dataBox[0]) + dataBox[0];
var dataY = y / (viewBox[3] - viewBox[1]) * (dataBox[3] - dataBox[1]) + dataBox[1];
if (!result.boxInited) {
result.boxStart[0] = dataX;
result.boxStart[1] = dataY;
result.dragStart[0] = x;
result.dragStart[1] = y;
}
result.boxEnd[0] = dataX;
result.boxEnd[1] = dataY;
// we need to mark the box as initialized right away
// so that we can tell the start and end points apart
result.boxInited = true;
// but don't actually enable the box until the cursor moves
if (!result.boxEnabled && (result.boxStart[0] !== result.boxEnd[0] || result.boxStart[1] !== result.boxEnd[1])) {
result.boxEnabled = true;
}
// constrain aspect ratio if the axes require it
var smallDx = Math.abs(result.dragStart[0] - x) < MINZOOM;
var smallDy = Math.abs(result.dragStart[1] - y) < MINZOOM;
if (getSubplotConstraint() && !(smallDx && smallDy)) {
dx = result.boxEnd[0] - result.boxStart[0];
dy = result.boxEnd[1] - result.boxStart[1];
var dydx = (dataBox[3] - dataBox[1]) / (dataBox[2] - dataBox[0]);
if (Math.abs(dx * dydx) > Math.abs(dy)) {
result.boxEnd[1] = result.boxStart[1] + Math.abs(dx) * dydx * (dy >= 0 ? 1 : -1);
// gl-select-box clips to the plot area bounds,
// which breaks the axis constraint, so don't allow
// this box to go out of bounds
if (result.boxEnd[1] < dataBox[1]) {
result.boxEnd[1] = dataBox[1];
result.boxEnd[0] = result.boxStart[0] + (dataBox[1] - result.boxStart[1]) / Math.abs(dydx);
} else if (result.boxEnd[1] > dataBox[3]) {
result.boxEnd[1] = dataBox[3];
result.boxEnd[0] = result.boxStart[0] + (dataBox[3] - result.boxStart[1]) / Math.abs(dydx);
}
} else {
result.boxEnd[0] = result.boxStart[0] + Math.abs(dy) / dydx * (dx >= 0 ? 1 : -1);
if (result.boxEnd[0] < dataBox[0]) {
result.boxEnd[0] = dataBox[0];
result.boxEnd[1] = result.boxStart[1] + (dataBox[0] - result.boxStart[0]) * Math.abs(dydx);
} else if (result.boxEnd[0] > dataBox[2]) {
result.boxEnd[0] = dataBox[2];
result.boxEnd[1] = result.boxStart[1] + (dataBox[2] - result.boxStart[0]) * Math.abs(dydx);
}
}
} else {
// otherwise clamp small changes to the origin so we get 1D zoom
if (smallDx) result.boxEnd[0] = result.boxStart[0];
if (smallDy) result.boxEnd[1] = result.boxStart[1];
}
} else if (result.boxEnabled) {
dx = result.boxStart[0] !== result.boxEnd[0];
dy = result.boxStart[1] !== result.boxEnd[1];
if (dx || dy) {
if (dx) {
updateRange(0, result.boxStart[0], result.boxEnd[0]);
scene.xaxis.autorange = false;
}
if (dy) {
updateRange(1, result.boxStart[1], result.boxEnd[1]);
scene.yaxis.autorange = false;
}
scene.relayoutCallback();
} else {
scene.glplot.setDirty();
}
result.boxEnabled = false;
result.boxInited = false;
} else if (result.boxInited) {
// if box was inited but button released then - reset the box
result.boxInited = false;
}
break;
case 'pan':
result.boxEnabled = false;
result.boxInited = false;
if (buttons) {
if (!result.panning) {
result.dragStart[0] = x;
result.dragStart[1] = y;
}
if (Math.abs(result.dragStart[0] - x) < MINDRAG) x = result.dragStart[0];
if (Math.abs(result.dragStart[1] - y) < MINDRAG) y = result.dragStart[1];
dx = (lastX - x) * (dataBox[2] - dataBox[0]) / (plot.viewBox[2] - plot.viewBox[0]);
dy = (lastY - y) * (dataBox[3] - dataBox[1]) / (plot.viewBox[3] - plot.viewBox[1]);
dataBox[0] += dx;
dataBox[2] += dx;
dataBox[1] += dy;
dataBox[3] += dy;
scene.setRanges(dataBox);
result.panning = true;
result.lastInputTime = Date.now();
unSetAutoRange();
scene.cameraChanged();
scene.handleAnnotations();
} else if (result.panning) {
result.panning = false;
scene.relayoutCallback();
}
break;
}
result.lastPos[0] = x;
result.lastPos[1] = y;
}
result.wheelListener = mouseWheel(element, function (dx, dy) {
if (!scene.scrollZoom) return false;
var dataBox = scene.calcDataBox();
var viewBox = plot.viewBox;
var lastX = result.lastPos[0];
var lastY = result.lastPos[1];
var scale = Math.exp(5.0 * dy / (viewBox[3] - viewBox[1]));
var cx = lastX / (viewBox[2] - viewBox[0]) * (dataBox[2] - dataBox[0]) + dataBox[0];
var cy = lastY / (viewBox[3] - viewBox[1]) * (dataBox[3] - dataBox[1]) + dataBox[1];
dataBox[0] = (dataBox[0] - cx) * scale + cx;
dataBox[2] = (dataBox[2] - cx) * scale + cx;
dataBox[1] = (dataBox[1] - cy) * scale + cy;
dataBox[3] = (dataBox[3] - cy) * scale + cy;
scene.setRanges(dataBox);
result.lastInputTime = Date.now();
unSetAutoRange();
scene.cameraChanged();
scene.handleAnnotations();
scene.relayoutCallback();
return true;
}, true);
return result;
}
/***/ }),
/***/ 92568:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var str2RGBArray = __webpack_require__(43080);
function Axes2DOptions(scene) {
this.scene = scene;
this.gl = scene.gl;
this.pixelRatio = scene.pixelRatio;
this.screenBox = [0, 0, 1, 1];
this.viewBox = [0, 0, 1, 1];
this.dataBox = [-1, -1, 1, 1];
this.borderLineEnable = [false, false, false, false];
this.borderLineWidth = [1, 1, 1, 1];
this.borderLineColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.ticks = [[], []];
this.tickEnable = [true, true, false, false];
this.tickPad = [15, 15, 15, 15];
this.tickAngle = [0, 0, 0, 0];
this.tickColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.tickMarkLength = [0, 0, 0, 0];
this.tickMarkWidth = [0, 0, 0, 0];
this.tickMarkColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.labels = ['x', 'y'];
this.labelEnable = [true, true, false, false];
this.labelAngle = [0, Math.PI / 2, 0, 3.0 * Math.PI / 2];
this.labelPad = [15, 15, 15, 15];
this.labelSize = [12, 12];
this.labelFont = ['sans-serif', 'sans-serif'];
this.labelColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.title = '';
this.titleEnable = true;
this.titleCenter = [0, 0, 0, 0];
this.titleAngle = 0;
this.titleColor = [0, 0, 0, 1];
this.titleFont = 'sans-serif';
this.titleSize = 18;
this.gridLineEnable = [true, true];
this.gridLineColor = [[0, 0, 0, 0.5], [0, 0, 0, 0.5]];
this.gridLineWidth = [1, 1];
this.zeroLineEnable = [true, true];
this.zeroLineWidth = [1, 1];
this.zeroLineColor = [[0, 0, 0, 1], [0, 0, 0, 1]];
this.borderColor = [0, 0, 0, 0];
this.backgroundColor = [0, 0, 0, 0];
this.static = this.scene.staticPlot;
}
var proto = Axes2DOptions.prototype;
var AXES = ['xaxis', 'yaxis'];
proto.merge = function (options) {
// titles are rendered in SVG
this.titleEnable = false;
this.backgroundColor = str2RGBArray(options.plot_bgcolor);
var axisName, ax, axTitle, axMirror;
var hasAxisInDfltPos, hasAxisInAltrPos, hasSharedAxis, mirrorLines, mirrorTicks;
var i, j;
for (i = 0; i < 2; ++i) {
axisName = AXES[i];
var axisLetter = axisName.charAt(0);
// get options relevant to this subplot,
// '_name' is e.g. xaxis, xaxis2, yaxis, yaxis4 ...
ax = options[this.scene[axisName]._name];
axTitle = ax.title.text === this.scene.fullLayout._dfltTitle[axisLetter] ? '' : ax.title.text;
for (j = 0; j <= 2; j += 2) {
this.labelEnable[i + j] = false;
this.labels[i + j] = axTitle;
this.labelColor[i + j] = str2RGBArray(ax.title.font.color);
this.labelFont[i + j] = ax.title.font.family;
this.labelSize[i + j] = ax.title.font.size;
this.labelPad[i + j] = this.getLabelPad(axisName, ax);
this.tickEnable[i + j] = false;
this.tickColor[i + j] = str2RGBArray((ax.tickfont || {}).color);
this.tickAngle[i + j] = ax.tickangle === 'auto' ? 0 : Math.PI * -ax.tickangle / 180;
this.tickPad[i + j] = this.getTickPad(ax);
this.tickMarkLength[i + j] = 0;
this.tickMarkWidth[i + j] = ax.tickwidth || 0;
this.tickMarkColor[i + j] = str2RGBArray(ax.tickcolor);
this.borderLineEnable[i + j] = false;
this.borderLineColor[i + j] = str2RGBArray(ax.linecolor);
this.borderLineWidth[i + j] = ax.linewidth || 0;
}
hasSharedAxis = this.hasSharedAxis(ax);
hasAxisInDfltPos = this.hasAxisInDfltPos(axisName, ax) && !hasSharedAxis;
hasAxisInAltrPos = this.hasAxisInAltrPos(axisName, ax) && !hasSharedAxis;
axMirror = ax.mirror || false;
mirrorLines = hasSharedAxis ? String(axMirror).indexOf('all') !== -1 :
// 'all' or 'allticks'
!!axMirror; // all but false
mirrorTicks = hasSharedAxis ? axMirror === 'allticks' : String(axMirror).indexOf('ticks') !== -1; // 'ticks' or 'allticks'
// Axis titles and tick labels can only appear of one side of the scene
// and are never show on subplots that share existing axes.
if (hasAxisInDfltPos) this.labelEnable[i] = true;else if (hasAxisInAltrPos) this.labelEnable[i + 2] = true;
if (hasAxisInDfltPos) this.tickEnable[i] = ax.showticklabels;else if (hasAxisInAltrPos) this.tickEnable[i + 2] = ax.showticklabels;
// Grid lines and ticks can appear on both sides of the scene
// and can appear on subplot that share existing axes via `ax.mirror`.
if (hasAxisInDfltPos || mirrorLines) this.borderLineEnable[i] = ax.showline;
if (hasAxisInAltrPos || mirrorLines) this.borderLineEnable[i + 2] = ax.showline;
if (hasAxisInDfltPos || mirrorTicks) this.tickMarkLength[i] = this.getTickMarkLength(ax);
if (hasAxisInAltrPos || mirrorTicks) this.tickMarkLength[i + 2] = this.getTickMarkLength(ax);
this.gridLineEnable[i] = ax.showgrid;
this.gridLineColor[i] = str2RGBArray(ax.gridcolor);
this.gridLineWidth[i] = ax.gridwidth;
this.zeroLineEnable[i] = ax.zeroline;
this.zeroLineColor[i] = str2RGBArray(ax.zerolinecolor);
this.zeroLineWidth[i] = ax.zerolinewidth;
}
};
// is an axis shared with an already-drawn subplot ?
proto.hasSharedAxis = function (ax) {
var scene = this.scene;
var subplotIds = scene.fullLayout._subplots.gl2d;
var list = Axes.findSubplotsWithAxis(subplotIds, ax);
// if index === 0, then the subplot is already drawn as subplots
// are drawn in order.
return list.indexOf(scene.id) !== 0;
};
// has an axis in default position (i.e. bottom/left) ?
proto.hasAxisInDfltPos = function (axisName, ax) {
var axSide = ax.side;
if (axisName === 'xaxis') return axSide === 'bottom';else if (axisName === 'yaxis') return axSide === 'left';
};
// has an axis in alternate position (i.e. top/right) ?
proto.hasAxisInAltrPos = function (axisName, ax) {
var axSide = ax.side;
if (axisName === 'xaxis') return axSide === 'top';else if (axisName === 'yaxis') return axSide === 'right';
};
proto.getLabelPad = function (axisName, ax) {
var offsetBase = 1.5;
var fontSize = ax.title.font.size;
var showticklabels = ax.showticklabels;
if (axisName === 'xaxis') {
return ax.side === 'top' ? -10 + fontSize * (offsetBase + (showticklabels ? 1 : 0)) : -10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0));
} else if (axisName === 'yaxis') {
return ax.side === 'right' ? 10 + fontSize * (offsetBase + (showticklabels ? 1 : 0.5)) : 10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0));
}
};
proto.getTickPad = function (ax) {
return ax.ticks === 'outside' ? 10 + ax.ticklen : 15;
};
proto.getTickMarkLength = function (ax) {
if (!ax.ticks) return 0;
var ticklen = ax.ticklen;
return ax.ticks === 'inside' ? -ticklen : ticklen;
};
function createAxes2D(scene) {
return new Axes2DOptions(scene);
}
module.exports = createAxes2D;
/***/ }),
/***/ 39952:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var overrideAll = (__webpack_require__(67824).overrideAll);
var Scene2D = __webpack_require__(17188);
var layoutGlobalAttrs = __webpack_require__(64859);
var xmlnsNamespaces = __webpack_require__(9616);
var constants = __webpack_require__(33816);
var Cartesian = __webpack_require__(57952);
var fxAttrs = __webpack_require__(65460);
var getSubplotData = (__webpack_require__(84888)/* .getSubplotData */ .op);
exports.name = 'gl2d';
exports.attr = ['xaxis', 'yaxis'];
exports.idRoot = ['x', 'y'];
exports.idRegex = constants.idRegex;
exports.attrRegex = constants.attrRegex;
exports.attributes = __webpack_require__(26720);
exports.supplyLayoutDefaults = function (layoutIn, layoutOut, fullData) {
if (!layoutOut._has('cartesian')) {
Cartesian.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
}
};
// gl2d uses svg axis attributes verbatim, but overrides editType
// this could potentially be just `layoutAttributes` but it would
// still need special handling somewhere to give it precedence over
// the svg version when both are in use on one plot
exports.layoutAttrOverrides = overrideAll(Cartesian.layoutAttributes, 'plot', 'from-root');
// similar overrides for base plot attributes (and those added by components)
exports.baseLayoutAttrOverrides = overrideAll({
plot_bgcolor: layoutGlobalAttrs.plot_bgcolor,
hoverlabel: fxAttrs.hoverlabel
// dragmode needs calc but only when transitioning TO lasso or select
// so for now it's left inside _relayout
// dragmode: fxAttrs.dragmode
}, 'plot', 'nested');
exports.plot = function plot(gd) {
var fullLayout = gd._fullLayout;
var fullData = gd._fullData;
var subplotIds = fullLayout._subplots.gl2d;
for (var i = 0; i < subplotIds.length; i++) {
var subplotId = subplotIds[i];
var subplotObj = fullLayout._plots[subplotId];
var fullSubplotData = getSubplotData(fullData, 'gl2d', subplotId);
// ref. to corresp. Scene instance
var scene = subplotObj._scene2d;
// If Scene is not instantiated, create one!
if (scene === undefined) {
scene = new Scene2D({
id: subplotId,
graphDiv: gd,
container: gd.querySelector('.gl-container'),
staticPlot: gd._context.staticPlot,
plotGlPixelRatio: gd._context.plotGlPixelRatio
}, fullLayout);
// set ref to Scene instance
subplotObj._scene2d = scene;
}
scene.plot(fullSubplotData, gd.calcdata, fullLayout, gd.layout);
}
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldSceneKeys = oldFullLayout._subplots.gl2d || [];
for (var i = 0; i < oldSceneKeys.length; i++) {
var id = oldSceneKeys[i];
var oldSubplot = oldFullLayout._plots[id];
// old subplot wasn't gl2d; nothing to do
if (!oldSubplot._scene2d) continue;
// if no traces are present, delete gl2d subplot
var subplotData = getSubplotData(newFullData, 'gl2d', id);
if (subplotData.length === 0) {
oldSubplot._scene2d.destroy();
delete oldFullLayout._plots[id];
}
}
// since we use cartesian interactions, do cartesian clean
Cartesian.clean.apply(this, arguments);
};
exports.drawFramework = function (gd) {
if (!gd._context.staticPlot) {
Cartesian.drawFramework(gd);
}
};
exports.toSVG = function (gd) {
var fullLayout = gd._fullLayout;
var subplotIds = fullLayout._subplots.gl2d;
for (var i = 0; i < subplotIds.length; i++) {
var subplot = fullLayout._plots[subplotIds[i]];
var scene = subplot._scene2d;
var imageData = scene.toImage('png');
var image = fullLayout._glimages.append('svg:image');
image.attr({
xmlns: xmlnsNamespaces.svg,
'xlink:href': imageData,
x: 0,
y: 0,
width: '100%',
height: '100%',
preserveAspectRatio: 'none'
});
scene.destroy();
}
};
exports.updateFx = function (gd) {
var fullLayout = gd._fullLayout;
var subplotIds = fullLayout._subplots.gl2d;
for (var i = 0; i < subplotIds.length; i++) {
var subplotObj = fullLayout._plots[subplotIds[i]]._scene2d;
subplotObj.updateFx(fullLayout.dragmode);
}
};
/***/ }),
/***/ 17188:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Axes = __webpack_require__(54460);
var Fx = __webpack_require__(93024);
var createPlot2D = (__webpack_require__(67792).gl_plot2d);
var createSpikes = (__webpack_require__(67792).gl_spikes2d);
var createSelectBox = (__webpack_require__(67792).gl_select_box);
var getContext = __webpack_require__(5408);
var createOptions = __webpack_require__(92568);
var createCamera = __webpack_require__(2428);
var showNoWebGlMsg = __webpack_require__(16576);
var axisConstraints = __webpack_require__(71888);
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = (__webpack_require__(19280).doAutoRange);
var dragHelpers = __webpack_require__(72760);
var drawMode = dragHelpers.drawMode;
var selectMode = dragHelpers.selectMode;
var AXES = ['xaxis', 'yaxis'];
var STATIC_CANVAS, STATIC_CONTEXT;
var SUBPLOT_PATTERN = (__webpack_require__(33816).SUBPLOT_PATTERN);
function Scene2D(options, fullLayout) {
this.container = options.container;
this.graphDiv = options.graphDiv;
this.pixelRatio = options.plotGlPixelRatio || window.devicePixelRatio;
this.id = options.id;
this.staticPlot = !!options.staticPlot;
this.scrollZoom = this.graphDiv._context._scrollZoom.cartesian;
this.fullData = null;
this.updateRefs(fullLayout);
this.makeFramework();
if (this.stopped) return;
// update options
this.glplotOptions = createOptions(this);
this.glplotOptions.merge(fullLayout);
// create the plot
this.glplot = createPlot2D(this.glplotOptions);
// create camera
this.camera = createCamera(this);
// trace set
this.traces = {};
// create axes spikes
this.spikes = createSpikes(this.glplot);
this.selectBox = createSelectBox(this.glplot, {
innerFill: false,
outerFill: true
});
// last button state
this.lastButtonState = 0;
// last pick result
this.pickResult = null;
// is the mouse over the plot?
// it's OK if this says true when it's not, so long as
// when we get a mouseout we set it to false before handling
this.isMouseOver = true;
// flag to stop render loop
this.stopped = false;
// redraw the plot
this.redraw = this.draw.bind(this);
this.redraw();
}
module.exports = Scene2D;
var proto = Scene2D.prototype;
proto.makeFramework = function () {
// create canvas and gl context
if (this.staticPlot) {
if (!STATIC_CONTEXT) {
STATIC_CANVAS = document.createElement('canvas');
STATIC_CONTEXT = getContext({
canvas: STATIC_CANVAS,
preserveDrawingBuffer: false,
premultipliedAlpha: true,
antialias: true
});
if (!STATIC_CONTEXT) {
throw new Error('Error creating static canvas/context for image server');
}
}
this.canvas = STATIC_CANVAS;
this.gl = STATIC_CONTEXT;
} else {
var liveCanvas = this.container.querySelector('.gl-canvas-focus');
var gl = getContext({
canvas: liveCanvas,
preserveDrawingBuffer: true,
premultipliedAlpha: true
});
if (!gl) {
showNoWebGlMsg(this);
this.stopped = true;
return;
}
this.canvas = liveCanvas;
this.gl = gl;
}
// position the canvas
var canvas = this.canvas;
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.style.position = 'absolute';
canvas.style.top = '0px';
canvas.style.left = '0px';
canvas.style['pointer-events'] = 'none';
this.updateSize(canvas);
// create SVG container for hover text
var svgContainer = this.svgContainer = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgContainer.style.position = 'absolute';
svgContainer.style.top = svgContainer.style.left = '0px';
svgContainer.style.width = svgContainer.style.height = '100%';
svgContainer.style['z-index'] = 20;
svgContainer.style['pointer-events'] = 'none';
// create div to catch the mouse event
var mouseContainer = this.mouseContainer = document.createElement('div');
mouseContainer.style.position = 'absolute';
mouseContainer.style['pointer-events'] = 'auto';
this.pickCanvas = this.container.querySelector('.gl-canvas-pick');
// append canvas, hover svg and mouse div to container
var container = this.container;
container.appendChild(svgContainer);
container.appendChild(mouseContainer);
var self = this;
mouseContainer.addEventListener('mouseout', function () {
self.isMouseOver = false;
self.unhover();
});
mouseContainer.addEventListener('mouseover', function () {
self.isMouseOver = true;
});
};
proto.toImage = function (format) {
if (!format) format = 'png';
this.stopped = true;
if (this.staticPlot) this.container.appendChild(STATIC_CANVAS);
// update canvas size
this.updateSize(this.canvas);
// grab context and yank out pixels
var gl = this.glplot.gl;
var w = gl.drawingBufferWidth;
var h = gl.drawingBufferHeight;
// force redraw
gl.clearColor(1, 1, 1, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
this.glplot.setDirty();
this.glplot.draw();
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
var pixels = new Uint8Array(w * h * 4);
gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
// flip pixels
for (var j = 0, k = h - 1; j < k; ++j, --k) {
for (var i = 0; i < w; ++i) {
for (var l = 0; l < 4; ++l) {
var tmp = pixels[4 * (w * j + i) + l];
pixels[4 * (w * j + i) + l] = pixels[4 * (w * k + i) + l];
pixels[4 * (w * k + i) + l] = tmp;
}
}
}
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var context = canvas.getContext('2d', {
willReadFrequently: true
});
var imageData = context.createImageData(w, h);
imageData.data.set(pixels);
context.putImageData(imageData, 0, 0);
var dataURL;
switch (format) {
case 'jpeg':
dataURL = canvas.toDataURL('image/jpeg');
break;
case 'webp':
dataURL = canvas.toDataURL('image/webp');
break;
default:
dataURL = canvas.toDataURL('image/png');
}
if (this.staticPlot) this.container.removeChild(STATIC_CANVAS);
return dataURL;
};
proto.updateSize = function (canvas) {
if (!canvas) canvas = this.canvas;
var pixelRatio = this.pixelRatio;
var fullLayout = this.fullLayout;
var width = fullLayout.width;
var height = fullLayout.height;
var pixelWidth = Math.ceil(pixelRatio * width) | 0;
var pixelHeight = Math.ceil(pixelRatio * height) | 0;
// check for resize
if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
canvas.width = pixelWidth;
canvas.height = pixelHeight;
}
return canvas;
};
proto.computeTickMarks = function () {
this.xaxis.setScale();
this.yaxis.setScale();
var nextTicks = [Axes.calcTicks(this.xaxis), Axes.calcTicks(this.yaxis)];
for (var j = 0; j < 2; ++j) {
for (var i = 0; i < nextTicks[j].length; ++i) {
// coercing tick value (may not be a string) to a string
nextTicks[j][i].text = nextTicks[j][i].text + '';
}
}
return nextTicks;
};
function compareTicks(a, b) {
for (var i = 0; i < 2; ++i) {
var aticks = a[i];
var bticks = b[i];
if (aticks.length !== bticks.length) return true;
for (var j = 0; j < aticks.length; ++j) {
if (aticks[j].x !== bticks[j].x) return true;
}
}
return false;
}
proto.updateRefs = function (newFullLayout) {
this.fullLayout = newFullLayout;
var spmatch = this.id.match(SUBPLOT_PATTERN);
var xaxisName = 'xaxis' + spmatch[1];
var yaxisName = 'yaxis' + spmatch[2];
this.xaxis = this.fullLayout[xaxisName];
this.yaxis = this.fullLayout[yaxisName];
};
proto.relayoutCallback = function () {
var graphDiv = this.graphDiv;
var xaxis = this.xaxis;
var yaxis = this.yaxis;
var layout = graphDiv.layout;
// make a meaningful value to be passed on to possible 'plotly_relayout' subscriber(s)
var update = {};
var xrange = update[xaxis._name + '.range'] = xaxis.range.slice();
var yrange = update[yaxis._name + '.range'] = yaxis.range.slice();
update[xaxis._name + '.autorange'] = xaxis.autorange;
update[yaxis._name + '.autorange'] = yaxis.autorange;
Registry.call('_storeDirectGUIEdit', graphDiv.layout, graphDiv._fullLayout._preGUI, update);
// update the input layout
var xaIn = layout[xaxis._name];
xaIn.range = xrange;
xaIn.autorange = xaxis.autorange;
var yaIn = layout[yaxis._name];
yaIn.range = yrange;
yaIn.autorange = yaxis.autorange;
// lastInputTime helps determine which one is the latest input (if async)
update.lastInputTime = this.camera.lastInputTime;
graphDiv.emit('plotly_relayout', update);
};
proto.cameraChanged = function () {
var camera = this.camera;
this.glplot.setDataBox(this.calcDataBox());
var nextTicks = this.computeTickMarks();
var curTicks = this.glplotOptions.ticks;
if (compareTicks(nextTicks, curTicks)) {
this.glplotOptions.ticks = nextTicks;
this.glplotOptions.dataBox = camera.dataBox;
this.glplot.update(this.glplotOptions);
this.handleAnnotations();
}
};
proto.handleAnnotations = function () {
var gd = this.graphDiv;
var annotations = this.fullLayout.annotations;
for (var i = 0; i < annotations.length; i++) {
var ann = annotations[i];
if (ann.xref === this.xaxis._id && ann.yref === this.yaxis._id) {
Registry.getComponentMethod('annotations', 'drawOne')(gd, i);
}
}
};
proto.destroy = function () {
if (!this.glplot) return;
var traces = this.traces;
if (traces) {
Object.keys(traces).map(function (key) {
traces[key].dispose();
delete traces[key];
});
}
this.glplot.dispose();
this.container.removeChild(this.svgContainer);
this.container.removeChild(this.mouseContainer);
this.fullData = null;
this.glplot = null;
this.stopped = true;
this.camera.mouseListener.enabled = false;
this.mouseContainer.removeEventListener('wheel', this.camera.wheelListener);
this.camera = null;
};
proto.plot = function (fullData, calcData, fullLayout) {
var glplot = this.glplot;
this.updateRefs(fullLayout);
this.xaxis.clearCalc();
this.yaxis.clearCalc();
this.updateTraces(fullData, calcData);
this.updateFx(fullLayout.dragmode);
var width = fullLayout.width;
var height = fullLayout.height;
this.updateSize(this.canvas);
var options = this.glplotOptions;
options.merge(fullLayout);
options.screenBox = [0, 0, width, height];
var mockGraphDiv = {
_fullLayout: {
_axisConstraintGroups: fullLayout._axisConstraintGroups,
xaxis: this.xaxis,
yaxis: this.yaxis,
_size: fullLayout._size
}
};
cleanAxisConstraints(mockGraphDiv, this.xaxis);
cleanAxisConstraints(mockGraphDiv, this.yaxis);
var size = fullLayout._size;
var domainX = this.xaxis.domain;
var domainY = this.yaxis.domain;
options.viewBox = [size.l + domainX[0] * size.w, size.b + domainY[0] * size.h, width - size.r - (1 - domainX[1]) * size.w, height - size.t - (1 - domainY[1]) * size.h];
this.mouseContainer.style.width = size.w * (domainX[1] - domainX[0]) + 'px';
this.mouseContainer.style.height = size.h * (domainY[1] - domainY[0]) + 'px';
this.mouseContainer.height = size.h * (domainY[1] - domainY[0]);
this.mouseContainer.style.left = size.l + domainX[0] * size.w + 'px';
this.mouseContainer.style.top = size.t + (1 - domainY[1]) * size.h + 'px';
var ax, i;
for (i = 0; i < 2; ++i) {
ax = this[AXES[i]];
ax._length = options.viewBox[i + 2] - options.viewBox[i];
doAutoRange(this.graphDiv, ax);
ax.setScale();
}
enforceAxisConstraints(mockGraphDiv);
options.ticks = this.computeTickMarks();
options.dataBox = this.calcDataBox();
options.merge(fullLayout);
glplot.update(options);
// force redraw so that promise is returned when rendering is completed
this.glplot.draw();
};
proto.calcDataBox = function () {
var xaxis = this.xaxis;
var yaxis = this.yaxis;
var xrange = xaxis.range;
var yrange = yaxis.range;
var xr2l = xaxis.r2l;
var yr2l = yaxis.r2l;
return [xr2l(xrange[0]), yr2l(yrange[0]), xr2l(xrange[1]), yr2l(yrange[1])];
};
proto.setRanges = function (dataBox) {
var xaxis = this.xaxis;
var yaxis = this.yaxis;
var xl2r = xaxis.l2r;
var yl2r = yaxis.l2r;
xaxis.range = [xl2r(dataBox[0]), xl2r(dataBox[2])];
yaxis.range = [yl2r(dataBox[1]), yl2r(dataBox[3])];
};
proto.updateTraces = function (fullData, calcData) {
var traceIds = Object.keys(this.traces);
var i, j, fullTrace;
this.fullData = fullData;
// remove empty traces
traceIdLoop: for (i = 0; i < traceIds.length; i++) {
var oldUid = traceIds[i];
var oldTrace = this.traces[oldUid];
for (j = 0; j < fullData.length; j++) {
fullTrace = fullData[j];
if (fullTrace.uid === oldUid && fullTrace.type === oldTrace.type) {
continue traceIdLoop;
}
}
oldTrace.dispose();
delete this.traces[oldUid];
}
// update / create trace objects
for (i = 0; i < fullData.length; i++) {
fullTrace = fullData[i];
var calcTrace = calcData[i];
var traceObj = this.traces[fullTrace.uid];
if (traceObj) traceObj.update(fullTrace, calcTrace);else {
traceObj = fullTrace._module.plot(this, fullTrace, calcTrace);
this.traces[fullTrace.uid] = traceObj;
}
}
// order object per traces
this.glplot.objects.sort(function (a, b) {
return a._trace.index - b._trace.index;
});
};
proto.updateFx = function (dragmode) {
// switch to svg interactions in lasso/select mode & shape drawing
if (selectMode(dragmode) || drawMode(dragmode)) {
this.pickCanvas.style['pointer-events'] = 'none';
this.mouseContainer.style['pointer-events'] = 'none';
} else {
this.pickCanvas.style['pointer-events'] = 'auto';
this.mouseContainer.style['pointer-events'] = 'auto';
}
// set proper cursor
if (dragmode === 'pan') {
this.mouseContainer.style.cursor = 'move';
} else if (dragmode === 'zoom') {
this.mouseContainer.style.cursor = 'crosshair';
} else {
this.mouseContainer.style.cursor = null;
}
};
proto.emitPointAction = function (nextSelection, eventType) {
var uid = nextSelection.trace.uid;
var ptNumber = nextSelection.pointIndex;
var trace;
for (var i = 0; i < this.fullData.length; i++) {
if (this.fullData[i].uid === uid) {
trace = this.fullData[i];
}
}
var pointData = {
x: nextSelection.traceCoord[0],
y: nextSelection.traceCoord[1],
curveNumber: trace.index,
pointNumber: ptNumber,
data: trace._input,
fullData: this.fullData,
xaxis: this.xaxis,
yaxis: this.yaxis
};
Fx.appendArrayPointValue(pointData, trace, ptNumber);
this.graphDiv.emit(eventType, {
points: [pointData]
});
};
proto.draw = function () {
if (this.stopped) return;
requestAnimationFrame(this.redraw);
var glplot = this.glplot;
var camera = this.camera;
var mouseListener = camera.mouseListener;
var mouseUp = this.lastButtonState === 1 && mouseListener.buttons === 0;
var fullLayout = this.fullLayout;
this.lastButtonState = mouseListener.buttons;
this.cameraChanged();
var x = mouseListener.x * glplot.pixelRatio;
var y = this.canvas.height - glplot.pixelRatio * mouseListener.y;
var result;
if (camera.boxEnabled && fullLayout.dragmode === 'zoom') {
this.selectBox.enabled = true;
var selectBox = this.selectBox.selectBox = [Math.min(camera.boxStart[0], camera.boxEnd[0]), Math.min(camera.boxStart[1], camera.boxEnd[1]), Math.max(camera.boxStart[0], camera.boxEnd[0]), Math.max(camera.boxStart[1], camera.boxEnd[1])];
// 1D zoom
for (var i = 0; i < 2; i++) {
if (camera.boxStart[i] === camera.boxEnd[i]) {
selectBox[i] = glplot.dataBox[i];
selectBox[i + 2] = glplot.dataBox[i + 2];
}
}
glplot.setDirty();
} else if (!camera.panning && this.isMouseOver) {
this.selectBox.enabled = false;
var size = fullLayout._size;
var domainX = this.xaxis.domain;
var domainY = this.yaxis.domain;
result = glplot.pick(x / glplot.pixelRatio + size.l + domainX[0] * size.w, y / glplot.pixelRatio - (size.t + (1 - domainY[1]) * size.h));
var nextSelection = result && result.object._trace.handlePick(result);
if (nextSelection && mouseUp) {
this.emitPointAction(nextSelection, 'plotly_click');
}
if (result && result.object._trace.hoverinfo !== 'skip' && fullLayout.hovermode) {
if (nextSelection && (!this.lastPickResult || this.lastPickResult.traceUid !== nextSelection.trace.uid || this.lastPickResult.dataCoord[0] !== nextSelection.dataCoord[0] || this.lastPickResult.dataCoord[1] !== nextSelection.dataCoord[1])) {
var selection = nextSelection;
this.lastPickResult = {
traceUid: nextSelection.trace ? nextSelection.trace.uid : null,
dataCoord: nextSelection.dataCoord.slice()
};
this.spikes.update({
center: result.dataCoord
});
selection.screenCoord = [((glplot.viewBox[2] - glplot.viewBox[0]) * (result.dataCoord[0] - glplot.dataBox[0]) / (glplot.dataBox[2] - glplot.dataBox[0]) + glplot.viewBox[0]) / glplot.pixelRatio, (this.canvas.height - (glplot.viewBox[3] - glplot.viewBox[1]) * (result.dataCoord[1] - glplot.dataBox[1]) / (glplot.dataBox[3] - glplot.dataBox[1]) - glplot.viewBox[1]) / glplot.pixelRatio];
// this needs to happen before the next block that deletes traceCoord data
// also it's important to copy, otherwise data is lost by the time event data is read
this.emitPointAction(nextSelection, 'plotly_hover');
var trace = this.fullData[selection.trace.index] || {};
var ptNumber = selection.pointIndex;
var hoverinfo = Fx.castHoverinfo(trace, fullLayout, ptNumber);
if (hoverinfo && hoverinfo !== 'all') {
var parts = hoverinfo.split('+');
if (parts.indexOf('x') === -1) selection.traceCoord[0] = undefined;
if (parts.indexOf('y') === -1) selection.traceCoord[1] = undefined;
if (parts.indexOf('z') === -1) selection.traceCoord[2] = undefined;
if (parts.indexOf('text') === -1) selection.textLabel = undefined;
if (parts.indexOf('name') === -1) selection.name = undefined;
}
Fx.loneHover({
x: selection.screenCoord[0],
y: selection.screenCoord[1],
xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]),
yLabel: this.hoverFormatter('yaxis', selection.traceCoord[1]),
zLabel: selection.traceCoord[2],
text: selection.textLabel,
name: selection.name,
color: Fx.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color,
borderColor: Fx.castHoverOption(trace, ptNumber, 'bordercolor'),
fontFamily: Fx.castHoverOption(trace, ptNumber, 'font.family'),
fontSize: Fx.castHoverOption(trace, ptNumber, 'font.size'),
fontColor: Fx.castHoverOption(trace, ptNumber, 'font.color'),
nameLength: Fx.castHoverOption(trace, ptNumber, 'namelength'),
textAlign: Fx.castHoverOption(trace, ptNumber, 'align')
}, {
container: this.svgContainer,
gd: this.graphDiv
});
}
}
}
// Remove hover effects if we're not over a point OR
// if we're zooming or panning (in which case result is not set)
if (!result) {
this.unhover();
}
glplot.draw();
};
proto.unhover = function () {
if (this.lastPickResult) {
this.spikes.update({});
this.lastPickResult = null;
this.graphDiv.emit('plotly_unhover');
Fx.loneUnhover(this.svgContainer);
}
};
proto.hoverFormatter = function (axisName, val) {
if (val === undefined) return undefined;
var axis = this[axisName];
return Axes.tickText(axis, axis.c2l(val), 'hover').text;
};
/***/ }),
/***/ 12536:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var overrideAll = (__webpack_require__(67824).overrideAll);
var fxAttrs = __webpack_require__(65460);
var Scene = __webpack_require__(98432);
var getSubplotData = (__webpack_require__(84888)/* .getSubplotData */ .op);
var Lib = __webpack_require__(3400);
var xmlnsNamespaces = __webpack_require__(9616);
var GL3D = 'gl3d';
var SCENE = 'scene';
exports.name = GL3D;
exports.attr = SCENE;
exports.idRoot = SCENE;
exports.idRegex = exports.attrRegex = Lib.counterRegex('scene');
exports.attributes = __webpack_require__(6636);
exports.layoutAttributes = __webpack_require__(346);
exports.baseLayoutAttrOverrides = overrideAll({
hoverlabel: fxAttrs.hoverlabel
}, 'plot', 'nested');
exports.supplyLayoutDefaults = __webpack_require__(5208);
exports.plot = function plot(gd) {
var fullLayout = gd._fullLayout;
var fullData = gd._fullData;
var sceneIds = fullLayout._subplots[GL3D];
for (var i = 0; i < sceneIds.length; i++) {
var sceneId = sceneIds[i];
var fullSceneData = getSubplotData(fullData, GL3D, sceneId);
var sceneLayout = fullLayout[sceneId];
var camera = sceneLayout.camera;
var scene = sceneLayout._scene;
if (!scene) {
scene = new Scene({
id: sceneId,
graphDiv: gd,
container: gd.querySelector('.gl-container'),
staticPlot: gd._context.staticPlot,
plotGlPixelRatio: gd._context.plotGlPixelRatio,
camera: camera
}, fullLayout);
// set ref to Scene instance
sceneLayout._scene = scene;
}
// save 'initial' camera view settings for modebar button
if (!scene.viewInitial) {
scene.viewInitial = {
up: {
x: camera.up.x,
y: camera.up.y,
z: camera.up.z
},
eye: {
x: camera.eye.x,
y: camera.eye.y,
z: camera.eye.z
},
center: {
x: camera.center.x,
y: camera.center.y,
z: camera.center.z
}
};
}
scene.plot(fullSceneData, fullLayout, gd.layout);
}
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldSceneKeys = oldFullLayout._subplots[GL3D] || [];
for (var i = 0; i < oldSceneKeys.length; i++) {
var oldSceneKey = oldSceneKeys[i];
if (!newFullLayout[oldSceneKey] && !!oldFullLayout[oldSceneKey]._scene) {
oldFullLayout[oldSceneKey]._scene.destroy();
if (oldFullLayout._infolayer) {
oldFullLayout._infolayer.selectAll('.annotation-' + oldSceneKey).remove();
}
}
}
};
exports.toSVG = function (gd) {
var fullLayout = gd._fullLayout;
var sceneIds = fullLayout._subplots[GL3D];
var size = fullLayout._size;
for (var i = 0; i < sceneIds.length; i++) {
var sceneLayout = fullLayout[sceneIds[i]];
var domain = sceneLayout.domain;
var scene = sceneLayout._scene;
var imageData = scene.toImage('png');
var image = fullLayout._glimages.append('svg:image');
image.attr({
xmlns: xmlnsNamespaces.svg,
'xlink:href': imageData,
x: size.l + size.w * domain.x[0],
y: size.t + size.h * (1 - domain.y[1]),
width: size.w * (domain.x[1] - domain.x[0]),
height: size.h * (domain.y[1] - domain.y[0]),
preserveAspectRatio: 'none'
});
scene.destroy();
}
};
// clean scene ids, 'scene1' -> 'scene'
exports.cleanId = function cleanId(id) {
if (!id.match(/^scene[0-9]*$/)) return;
var sceneNum = id.substr(5);
if (sceneNum === '1') sceneNum = '';
return SCENE + sceneNum;
};
exports.updateFx = function (gd) {
var fullLayout = gd._fullLayout;
var subplotIds = fullLayout._subplots[GL3D];
for (var i = 0; i < subplotIds.length; i++) {
var subplotObj = fullLayout[subplotIds[i]]._scene;
subplotObj.updateFx(fullLayout.dragmode, fullLayout.hovermode);
}
};
/***/ }),
/***/ 6636:
/***/ (function(module) {
"use strict";
module.exports = {
scene: {
valType: 'subplotid',
dflt: 'scene',
editType: 'calc+clearAxisTypes'
}
};
/***/ }),
/***/ 86140:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var axesAttrs = __webpack_require__(94724);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
module.exports = overrideAll({
visible: axesAttrs.visible,
showspikes: {
valType: 'boolean',
dflt: true
},
spikesides: {
valType: 'boolean',
dflt: true
},
spikethickness: {
valType: 'number',
min: 0,
dflt: 2
},
spikecolor: {
valType: 'color',
dflt: Color.defaultLine
},
showbackground: {
valType: 'boolean',
dflt: false
},
backgroundcolor: {
valType: 'color',
dflt: 'rgba(204, 204, 204, 0.5)'
},
showaxeslabels: {
valType: 'boolean',
dflt: true
},
color: axesAttrs.color,
categoryorder: axesAttrs.categoryorder,
categoryarray: axesAttrs.categoryarray,
title: {
text: axesAttrs.title.text,
font: axesAttrs.title.font
},
type: extendFlat({}, axesAttrs.type, {
values: ['-', 'linear', 'log', 'date', 'category']
}),
autotypenumbers: axesAttrs.autotypenumbers,
autorange: axesAttrs.autorange,
autorangeoptions: {
minallowed: axesAttrs.autorangeoptions.minallowed,
maxallowed: axesAttrs.autorangeoptions.maxallowed,
clipmin: axesAttrs.autorangeoptions.clipmin,
clipmax: axesAttrs.autorangeoptions.clipmax,
include: axesAttrs.autorangeoptions.include,
editType: 'plot'
},
rangemode: axesAttrs.rangemode,
minallowed: axesAttrs.minallowed,
maxallowed: axesAttrs.maxallowed,
range: extendFlat({}, axesAttrs.range, {
items: [{
valType: 'any',
editType: 'plot',
impliedEdits: {
'^autorange': false
}
}, {
valType: 'any',
editType: 'plot',
impliedEdits: {
'^autorange': false
}
}],
anim: false
}),
// ticks
tickmode: axesAttrs.minor.tickmode,
nticks: axesAttrs.nticks,
tick0: axesAttrs.tick0,
dtick: axesAttrs.dtick,
tickvals: axesAttrs.tickvals,
ticktext: axesAttrs.ticktext,
ticks: axesAttrs.ticks,
mirror: axesAttrs.mirror,
ticklen: axesAttrs.ticklen,
tickwidth: axesAttrs.tickwidth,
tickcolor: axesAttrs.tickcolor,
showticklabels: axesAttrs.showticklabels,
labelalias: axesAttrs.labelalias,
tickfont: axesAttrs.tickfont,
tickangle: axesAttrs.tickangle,
tickprefix: axesAttrs.tickprefix,
showtickprefix: axesAttrs.showtickprefix,
ticksuffix: axesAttrs.ticksuffix,
showticksuffix: axesAttrs.showticksuffix,
showexponent: axesAttrs.showexponent,
exponentformat: axesAttrs.exponentformat,
minexponent: axesAttrs.minexponent,
separatethousands: axesAttrs.separatethousands,
tickformat: axesAttrs.tickformat,
tickformatstops: axesAttrs.tickformatstops,
hoverformat: axesAttrs.hoverformat,
// lines and grids
showline: axesAttrs.showline,
linecolor: axesAttrs.linecolor,
linewidth: axesAttrs.linewidth,
showgrid: axesAttrs.showgrid,
gridcolor: extendFlat({}, axesAttrs.gridcolor,
// shouldn't this be on-par with 2D?
{
dflt: 'rgb(204, 204, 204)'
}),
gridwidth: axesAttrs.gridwidth,
zeroline: axesAttrs.zeroline,
zerolinecolor: axesAttrs.zerolinecolor,
zerolinewidth: axesAttrs.zerolinewidth,
_deprecated: {
title: axesAttrs._deprecated.title,
titlefont: axesAttrs._deprecated.titlefont
}
}, 'plot', 'from-root');
/***/ }),
/***/ 64380:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorMix = (__webpack_require__(49760).mix);
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
var layoutAttributes = __webpack_require__(86140);
var handleTypeDefaults = __webpack_require__(14944);
var handleAxisDefaults = __webpack_require__(28336);
var axesNames = ['xaxis', 'yaxis', 'zaxis'];
// TODO: hard-coded lightness fraction based on gridline default colors
// that differ from other subplot types.
var gridLightness = 100 * (204 - 0x44) / (255 - 0x44);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) {
var containerIn, containerOut;
function coerce(attr, dflt) {
return Lib.coerce(containerIn, containerOut, layoutAttributes, attr, dflt);
}
for (var j = 0; j < axesNames.length; j++) {
var axName = axesNames[j];
containerIn = layoutIn[axName] || {};
containerOut = Template.newContainer(layoutOut, axName);
containerOut._id = axName[0] + options.scene;
containerOut._name = axName;
handleTypeDefaults(containerIn, containerOut, coerce, options);
handleAxisDefaults(containerIn, containerOut, coerce, {
font: options.font,
letter: axName[0],
data: options.data,
showGrid: true,
noAutotickangles: true,
noTicklabelindex: true,
noTickson: true,
noTicklabelmode: true,
noTicklabelshift: true,
noTicklabelstandoff: true,
noTicklabelstep: true,
noTicklabelposition: true,
noTicklabeloverflow: true,
noInsiderange: true,
bgColor: options.bgColor,
calendar: options.calendar
}, options.fullLayout);
coerce('gridcolor', colorMix(containerOut.color, options.bgColor, gridLightness).toRgbString());
coerce('title.text', axName[0]); // shouldn't this be on-par with 2D?
containerOut.setScale = Lib.noop;
if (coerce('showspikes')) {
coerce('spikesides');
coerce('spikethickness');
coerce('spikecolor', containerOut.color);
}
coerce('showaxeslabels');
if (coerce('showbackground')) coerce('backgroundcolor');
}
};
/***/ }),
/***/ 44728:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var str2RgbaArray = __webpack_require__(43080);
var Lib = __webpack_require__(3400);
var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];
function AxesOptions() {
this.bounds = [[-10, -10, -10], [10, 10, 10]];
this.ticks = [[], [], []];
this.tickEnable = [true, true, true];
this.tickFont = ['sans-serif', 'sans-serif', 'sans-serif'];
this.tickSize = [12, 12, 12];
this.tickFontWeight = ['normal', 'normal', 'normal', 'normal'];
this.tickFontStyle = ['normal', 'normal', 'normal', 'normal'];
this.tickFontVariant = ['normal', 'normal', 'normal', 'normal'];
this.tickAngle = [0, 0, 0];
this.tickColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.tickPad = [18, 18, 18];
this.labels = ['x', 'y', 'z'];
this.labelEnable = [true, true, true];
this.labelFont = ['Open Sans', 'Open Sans', 'Open Sans'];
this.labelSize = [20, 20, 20];
this.labelFontWeight = ['normal', 'normal', 'normal', 'normal'];
this.labelFontStyle = ['normal', 'normal', 'normal', 'normal'];
this.labelFontVariant = ['normal', 'normal', 'normal', 'normal'];
this.labelColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.labelPad = [30, 30, 30];
this.lineEnable = [true, true, true];
this.lineMirror = [false, false, false];
this.lineWidth = [1, 1, 1];
this.lineColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.lineTickEnable = [true, true, true];
this.lineTickMirror = [false, false, false];
this.lineTickLength = [10, 10, 10];
this.lineTickWidth = [1, 1, 1];
this.lineTickColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.gridEnable = [true, true, true];
this.gridWidth = [1, 1, 1];
this.gridColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.zeroEnable = [true, true, true];
this.zeroLineColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.zeroLineWidth = [2, 2, 2];
this.backgroundEnable = [true, true, true];
this.backgroundColor = [[0.8, 0.8, 0.8, 0.5], [0.8, 0.8, 0.8, 0.5], [0.8, 0.8, 0.8, 0.5]];
// some default values are stored for applying model transforms
this._defaultTickPad = this.tickPad.slice();
this._defaultLabelPad = this.labelPad.slice();
this._defaultLineTickLength = this.lineTickLength.slice();
}
var proto = AxesOptions.prototype;
proto.merge = function (fullLayout, sceneLayout) {
var opts = this;
for (var i = 0; i < 3; ++i) {
var axes = sceneLayout[AXES_NAMES[i]];
if (!axes.visible) {
opts.tickEnable[i] = false;
opts.labelEnable[i] = false;
opts.lineEnable[i] = false;
opts.lineTickEnable[i] = false;
opts.gridEnable[i] = false;
opts.zeroEnable[i] = false;
opts.backgroundEnable[i] = false;
continue;
}
// Axes labels
opts.labels[i] = fullLayout._meta ? Lib.templateString(axes.title.text, fullLayout._meta) : axes.title.text;
if ('font' in axes.title) {
if (axes.title.font.color) opts.labelColor[i] = str2RgbaArray(axes.title.font.color);
if (axes.title.font.family) opts.labelFont[i] = axes.title.font.family;
if (axes.title.font.size) opts.labelSize[i] = axes.title.font.size;
if (axes.title.font.weight) opts.labelFontWeight[i] = axes.title.font.weight;
if (axes.title.font.style) opts.labelFontStyle[i] = axes.title.font.style;
if (axes.title.font.variant) opts.labelFontVariant[i] = axes.title.font.variant;
}
// Lines
if ('showline' in axes) opts.lineEnable[i] = axes.showline;
if ('linecolor' in axes) opts.lineColor[i] = str2RgbaArray(axes.linecolor);
if ('linewidth' in axes) opts.lineWidth[i] = axes.linewidth;
if ('showgrid' in axes) opts.gridEnable[i] = axes.showgrid;
if ('gridcolor' in axes) opts.gridColor[i] = str2RgbaArray(axes.gridcolor);
if ('gridwidth' in axes) opts.gridWidth[i] = axes.gridwidth;
// Remove zeroline if axis type is log
// otherwise the zeroline is incorrectly drawn at 1 on log axes
if (axes.type === 'log') opts.zeroEnable[i] = false;else if ('zeroline' in axes) opts.zeroEnable[i] = axes.zeroline;
if ('zerolinecolor' in axes) opts.zeroLineColor[i] = str2RgbaArray(axes.zerolinecolor);
if ('zerolinewidth' in axes) opts.zeroLineWidth[i] = axes.zerolinewidth;
// tick lines
if ('ticks' in axes && !!axes.ticks) opts.lineTickEnable[i] = true;else opts.lineTickEnable[i] = false;
if ('ticklen' in axes) {
opts.lineTickLength[i] = opts._defaultLineTickLength[i] = axes.ticklen;
}
if ('tickcolor' in axes) opts.lineTickColor[i] = str2RgbaArray(axes.tickcolor);
if ('tickwidth' in axes) opts.lineTickWidth[i] = axes.tickwidth;
if ('tickangle' in axes) {
opts.tickAngle[i] = axes.tickangle === 'auto' ? -3600 :
// i.e. special number to set auto option
Math.PI * -axes.tickangle / 180;
}
// tick labels
if ('showticklabels' in axes) opts.tickEnable[i] = axes.showticklabels;
if ('tickfont' in axes) {
if (axes.tickfont.color) opts.tickColor[i] = str2RgbaArray(axes.tickfont.color);
if (axes.tickfont.family) opts.tickFont[i] = axes.tickfont.family;
if (axes.tickfont.size) opts.tickSize[i] = axes.tickfont.size;
if (axes.tickfont.weight) opts.tickFontWeight[i] = axes.tickfont.weight;
if (axes.tickfont.style) opts.tickFontStyle[i] = axes.tickfont.style;
if (axes.tickfont.variant) opts.tickFontVariant[i] = axes.tickfont.variant;
}
if ('mirror' in axes) {
if (['ticks', 'all', 'allticks'].indexOf(axes.mirror) !== -1) {
opts.lineTickMirror[i] = true;
opts.lineMirror[i] = true;
} else if (axes.mirror === true) {
opts.lineTickMirror[i] = false;
opts.lineMirror[i] = true;
} else {
opts.lineTickMirror[i] = false;
opts.lineMirror[i] = false;
}
} else opts.lineMirror[i] = false;
// grid background
if ('showbackground' in axes && axes.showbackground !== false) {
opts.backgroundEnable[i] = true;
opts.backgroundColor[i] = str2RgbaArray(axes.backgroundcolor);
} else opts.backgroundEnable[i] = false;
}
};
function createAxesOptions(fullLayout, sceneLayout) {
var result = new AxesOptions();
result.merge(fullLayout, sceneLayout);
return result;
}
module.exports = createAxesOptions;
/***/ }),
/***/ 5208:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var Registry = __webpack_require__(24040);
var handleSubplotDefaults = __webpack_require__(168);
var supplyGl3dAxisLayoutDefaults = __webpack_require__(64380);
var layoutAttributes = __webpack_require__(346);
var getSubplotData = (__webpack_require__(84888)/* .getSubplotData */ .op);
var GL3D = 'gl3d';
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
var hasNon3D = layoutOut._basePlotModules.length > 1;
// some layout-wide attribute are used in all scenes
// if 3D is the only visible plot type
function getDfltFromLayout(attr) {
if (hasNon3D) return;
var isValid = Lib.validate(layoutIn[attr], layoutAttributes[attr]);
if (isValid) return layoutIn[attr];
}
handleSubplotDefaults(layoutIn, layoutOut, fullData, {
type: GL3D,
attributes: layoutAttributes,
handleDefaults: handleGl3dDefaults,
fullLayout: layoutOut,
font: layoutOut.font,
fullData: fullData,
getDfltFromLayout: getDfltFromLayout,
autotypenumbersDflt: layoutOut.autotypenumbers,
paper_bgcolor: layoutOut.paper_bgcolor,
calendar: layoutOut.calendar
});
};
function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) {
/*
* Scene numbering proceeds as follows
* scene
* scene2
* scene3
*
* and d.scene will be undefined or some number or number string
*
* Also write back a blank scene object to user layout so that some
* attributes like aspectratio can be written back dynamically.
*/
var bgcolor = coerce('bgcolor');
var bgColorCombined = Color.combine(bgcolor, opts.paper_bgcolor);
var cameraKeys = ['up', 'center', 'eye'];
for (var j = 0; j < cameraKeys.length; j++) {
coerce('camera.' + cameraKeys[j] + '.x');
coerce('camera.' + cameraKeys[j] + '.y');
coerce('camera.' + cameraKeys[j] + '.z');
}
coerce('camera.projection.type');
/*
* coerce to positive number (min 0) but also do not accept 0 (>0 not >=0)
* note that 0's go false with the !! call
*/
var hasAspect = !!coerce('aspectratio.x') && !!coerce('aspectratio.y') && !!coerce('aspectratio.z');
var defaultAspectMode = hasAspect ? 'manual' : 'auto';
var aspectMode = coerce('aspectmode', defaultAspectMode);
/*
* We need aspectratio object in all the Layouts as it is dynamically set
* in the calculation steps, ie, we cant set the correct data now, it happens later.
* We must also account for the case the user sends bad ratio data with 'manual' set
* for the mode. In this case we must force change it here as the default coerce
* misses it above.
*/
if (!hasAspect) {
sceneLayoutIn.aspectratio = sceneLayoutOut.aspectratio = {
x: 1,
y: 1,
z: 1
};
if (aspectMode === 'manual') sceneLayoutOut.aspectmode = 'auto';
/*
* kind of like autorange - we need the calculated aspectmode back in
* the input layout or relayout can cause problems later
*/
sceneLayoutIn.aspectmode = sceneLayoutOut.aspectmode;
}
var fullGl3dData = getSubplotData(opts.fullData, GL3D, opts.id);
supplyGl3dAxisLayoutDefaults(sceneLayoutIn, sceneLayoutOut, {
font: opts.font,
scene: opts.id,
data: fullGl3dData,
bgColor: bgColorCombined,
calendar: opts.calendar,
autotypenumbersDflt: opts.autotypenumbersDflt,
fullLayout: opts.fullLayout
});
Registry.getComponentMethod('annotations3d', 'handleDefaults')(sceneLayoutIn, sceneLayoutOut, opts);
var dragmode = opts.getDfltFromLayout('dragmode');
if (dragmode !== false) {
if (!dragmode) {
dragmode = 'orbit';
if (sceneLayoutIn.camera && sceneLayoutIn.camera.up) {
var x = sceneLayoutIn.camera.up.x;
var y = sceneLayoutIn.camera.up.y;
var z = sceneLayoutIn.camera.up.z;
if (z !== 0) {
if (!x || !y || !z) {
dragmode = 'turntable';
} else if (z / Math.sqrt(x * x + y * y + z * z) > 0.999) {
dragmode = 'turntable';
}
}
} else {
dragmode = 'turntable';
}
}
}
coerce('dragmode', dragmode);
coerce('hovermode', opts.getDfltFromLayout('hovermode'));
}
/***/ }),
/***/ 346:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var gl3dAxisAttrs = __webpack_require__(86140);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
var counterRegex = (__webpack_require__(3400).counterRegex);
function makeCameraVector(x, y, z) {
return {
x: {
valType: 'number',
dflt: x,
editType: 'camera'
},
y: {
valType: 'number',
dflt: y,
editType: 'camera'
},
z: {
valType: 'number',
dflt: z,
editType: 'camera'
},
editType: 'camera'
};
}
module.exports = {
_arrayAttrRegexps: [counterRegex('scene', '.annotations', true)],
bgcolor: {
valType: 'color',
dflt: 'rgba(0,0,0,0)',
editType: 'plot'
},
camera: {
up: extendFlat(makeCameraVector(0, 0, 1), {}),
center: extendFlat(makeCameraVector(0, 0, 0), {}),
eye: extendFlat(makeCameraVector(1.25, 1.25, 1.25), {}),
projection: {
type: {
valType: 'enumerated',
values: ['perspective', 'orthographic'],
dflt: 'perspective',
editType: 'calc'
},
editType: 'calc'
},
editType: 'camera'
},
domain: domainAttrs({
name: 'scene',
editType: 'plot'
}),
aspectmode: {
valType: 'enumerated',
values: ['auto', 'cube', 'data', 'manual'],
dflt: 'auto',
editType: 'plot',
impliedEdits: {
'aspectratio.x': undefined,
'aspectratio.y': undefined,
'aspectratio.z': undefined
}
},
aspectratio: {
// must be positive (0's are coerced to 1)
x: {
valType: 'number',
min: 0,
editType: 'plot',
impliedEdits: {
'^aspectmode': 'manual'
}
},
y: {
valType: 'number',
min: 0,
editType: 'plot',
impliedEdits: {
'^aspectmode': 'manual'
}
},
z: {
valType: 'number',
min: 0,
editType: 'plot',
impliedEdits: {
'^aspectmode': 'manual'
}
},
editType: 'plot',
impliedEdits: {
aspectmode: 'manual'
}
},
xaxis: gl3dAxisAttrs,
yaxis: gl3dAxisAttrs,
zaxis: gl3dAxisAttrs,
dragmode: {
valType: 'enumerated',
values: ['orbit', 'turntable', 'zoom', 'pan', false],
editType: 'plot'
},
hovermode: {
valType: 'enumerated',
values: ['closest', false],
dflt: 'closest',
editType: 'modebar'
},
uirevision: {
valType: 'any',
editType: 'none'
},
editType: 'plot',
_deprecated: {
cameraposition: {
valType: 'info_array',
editType: 'camera'
}
}
};
/***/ }),
/***/ 9020:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var str2RGBArray = __webpack_require__(43080);
var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];
function SpikeOptions() {
this.enabled = [true, true, true];
this.colors = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
this.drawSides = [true, true, true];
this.lineWidth = [1, 1, 1];
}
var proto = SpikeOptions.prototype;
proto.merge = function (sceneLayout) {
for (var i = 0; i < 3; ++i) {
var axes = sceneLayout[AXES_NAMES[i]];
if (!axes.visible) {
this.enabled[i] = false;
this.drawSides[i] = false;
continue;
}
this.enabled[i] = axes.showspikes;
this.colors[i] = str2RGBArray(axes.spikecolor);
this.drawSides[i] = axes.spikesides;
this.lineWidth[i] = axes.spikethickness;
}
};
function createSpikeOptions(layout) {
var result = new SpikeOptions();
result.merge(layout);
return result;
}
module.exports = createSpikeOptions;
/***/ }),
/***/ 87152:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* eslint block-scoped-var: 0*/
/* eslint no-redeclare: 0*/
module.exports = computeTickMarks;
var Axes = __webpack_require__(54460);
var Lib = __webpack_require__(3400);
var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];
var centerPoint = [0, 0, 0];
function contourLevelsFromTicks(ticks) {
var result = new Array(3);
for (var i = 0; i < 3; ++i) {
var tlevel = ticks[i];
var clevel = new Array(tlevel.length);
for (var j = 0; j < tlevel.length; ++j) {
clevel[j] = tlevel[j].x;
}
result[i] = clevel;
}
return result;
}
function computeTickMarks(scene) {
var axesOptions = scene.axesOptions;
var glRange = scene.glplot.axesPixels;
var sceneLayout = scene.fullSceneLayout;
var ticks = [[], [], []];
for (var i = 0; i < 3; ++i) {
var axes = sceneLayout[AXES_NAMES[i]];
axes._length = (glRange[i].hi - glRange[i].lo) * glRange[i].pixelsPerDataUnit / scene.dataScale[i];
if (Math.abs(axes._length) === Infinity || isNaN(axes._length)) {
ticks[i] = [];
} else {
axes._input_range = axes.range.slice();
axes.range[0] = glRange[i].lo / scene.dataScale[i];
axes.range[1] = glRange[i].hi / scene.dataScale[i];
axes._m = 1.0 / (scene.dataScale[i] * glRange[i].pixelsPerDataUnit);
if (axes.range[0] === axes.range[1]) {
axes.range[0] -= 1;
axes.range[1] += 1;
}
// this is necessary to short-circuit the 'y' handling
// in autotick part of calcTicks... Treating all axes as 'y' in this case
// running the autoticks here, then setting
// autoticks to false to get around the 2D handling in calcTicks.
var tickModeCached = axes.tickmode;
if (axes.tickmode === 'auto') {
axes.tickmode = 'linear';
var nticks = axes.nticks || Lib.constrain(axes._length / 40, 4, 9);
Axes.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks);
}
var dataTicks = Axes.calcTicks(axes, {
msUTC: true
});
for (var j = 0; j < dataTicks.length; ++j) {
dataTicks[j].x = dataTicks[j].x * scene.dataScale[i];
if (axes.type === 'date') {
dataTicks[j].text = dataTicks[j].text.replace(/\ /g, ' ');
}
}
ticks[i] = dataTicks;
axes.tickmode = tickModeCached;
}
}
axesOptions.ticks = ticks;
// Calculate tick lengths dynamically
for (var i = 0; i < 3; ++i) {
centerPoint[i] = 0.5 * (scene.glplot.bounds[0][i] + scene.glplot.bounds[1][i]);
for (var j = 0; j < 2; ++j) {
axesOptions.bounds[j][i] = scene.glplot.bounds[j][i];
}
}
scene.contourLevels = contourLevelsFromTicks(ticks);
}
/***/ }),
/***/ 94424:
/***/ (function(module) {
"use strict";
function xformMatrix(m, v) {
var out = [0, 0, 0, 0];
var i, j;
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
out[j] += m[4 * i + j] * v[i];
}
}
return out;
}
function project(camera, v) {
var p = xformMatrix(camera.projection, xformMatrix(camera.view, xformMatrix(camera.model, [v[0], v[1], v[2], 1])));
return p;
}
module.exports = project;
/***/ }),
/***/ 98432:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var glPlot3d = (__webpack_require__(67792).gl_plot3d);
var createCamera = glPlot3d.createCamera;
var createPlot = glPlot3d.createScene;
var getContext = __webpack_require__(5408);
var passiveSupported = __webpack_require__(89184);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var preserveDrawingBuffer = Lib.preserveDrawingBuffer();
var Axes = __webpack_require__(54460);
var Fx = __webpack_require__(93024);
var str2RGBAarray = __webpack_require__(43080);
var showNoWebGlMsg = __webpack_require__(16576);
var project = __webpack_require__(94424);
var createAxesOptions = __webpack_require__(44728);
var createSpikeOptions = __webpack_require__(9020);
var computeTickMarks = __webpack_require__(87152);
var applyAutorangeOptions = (__webpack_require__(19280).applyAutorangeOptions);
var STATIC_CANVAS, STATIC_CONTEXT;
var tabletmode = false;
function Scene(options, fullLayout) {
// create sub container for plot
var sceneContainer = document.createElement('div');
var plotContainer = options.container;
// keep a ref to the graph div to fire hover+click events
this.graphDiv = options.graphDiv;
// create SVG container for hover text
var svgContainer = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgContainer.style.position = 'absolute';
svgContainer.style.top = svgContainer.style.left = '0px';
svgContainer.style.width = svgContainer.style.height = '100%';
svgContainer.style['z-index'] = 20;
svgContainer.style['pointer-events'] = 'none';
sceneContainer.appendChild(svgContainer);
this.svgContainer = svgContainer;
// Tag the container with the sceneID
sceneContainer.id = options.id;
sceneContainer.style.position = 'absolute';
sceneContainer.style.top = sceneContainer.style.left = '0px';
sceneContainer.style.width = sceneContainer.style.height = '100%';
plotContainer.appendChild(sceneContainer);
this.fullLayout = fullLayout;
this.id = options.id || 'scene';
this.fullSceneLayout = fullLayout[this.id];
// Saved from last call to plot()
this.plotArgs = [[], {}, {}];
/*
* Move this to calc step? Why does it work here?
*/
this.axesOptions = createAxesOptions(fullLayout, fullLayout[this.id]);
this.spikeOptions = createSpikeOptions(fullLayout[this.id]);
this.container = sceneContainer;
this.staticMode = !!options.staticPlot;
this.pixelRatio = this.pixelRatio || options.plotGlPixelRatio || 2;
// Coordinate rescaling
this.dataScale = [1, 1, 1];
this.contourLevels = [[], [], []];
this.convertAnnotations = Registry.getComponentMethod('annotations3d', 'convert');
this.drawAnnotations = Registry.getComponentMethod('annotations3d', 'draw');
this.initializeGLPlot();
}
var proto = Scene.prototype;
proto.prepareOptions = function () {
var scene = this;
var opts = {
canvas: scene.canvas,
gl: scene.gl,
glOptions: {
preserveDrawingBuffer: preserveDrawingBuffer,
premultipliedAlpha: true,
antialias: true
},
container: scene.container,
axes: scene.axesOptions,
spikes: scene.spikeOptions,
pickRadius: 10,
snapToData: true,
autoScale: true,
autoBounds: false,
cameraObject: scene.camera,
pixelRatio: scene.pixelRatio
};
// for static plots, we reuse the WebGL context
// as WebKit doesn't collect them reliably
if (scene.staticMode) {
if (!STATIC_CONTEXT) {
STATIC_CANVAS = document.createElement('canvas');
STATIC_CONTEXT = getContext({
canvas: STATIC_CANVAS,
preserveDrawingBuffer: true,
premultipliedAlpha: true,
antialias: true
});
if (!STATIC_CONTEXT) {
throw new Error('error creating static canvas/context for image server');
}
}
opts.gl = STATIC_CONTEXT;
opts.canvas = STATIC_CANVAS;
}
return opts;
};
var firstInit = true;
proto.tryCreatePlot = function () {
var scene = this;
var opts = scene.prepareOptions();
var success = true;
try {
scene.glplot = createPlot(opts);
} catch (e) {
if (scene.staticMode || !firstInit || preserveDrawingBuffer) {
success = false;
} else {
// try second time
// enable preserveDrawingBuffer setup
// in case is-mobile not detecting the right device
Lib.warn(['webgl setup failed possibly due to', 'false preserveDrawingBuffer config.', 'The mobile/tablet device may not be detected by is-mobile module.', 'Enabling preserveDrawingBuffer in second attempt to create webgl scene...'].join(' '));
try {
// invert preserveDrawingBuffer
preserveDrawingBuffer = opts.glOptions.preserveDrawingBuffer = true;
scene.glplot = createPlot(opts);
} catch (e) {
// revert changes to preserveDrawingBuffer
preserveDrawingBuffer = opts.glOptions.preserveDrawingBuffer = false;
success = false;
}
}
}
firstInit = false;
return success;
};
proto.initializeGLCamera = function () {
var scene = this;
var cameraData = scene.fullSceneLayout.camera;
var isOrtho = cameraData.projection.type === 'orthographic';
scene.camera = createCamera(scene.container, {
center: [cameraData.center.x, cameraData.center.y, cameraData.center.z],
eye: [cameraData.eye.x, cameraData.eye.y, cameraData.eye.z],
up: [cameraData.up.x, cameraData.up.y, cameraData.up.z],
_ortho: isOrtho,
zoomMin: 0.01,
zoomMax: 100,
mode: 'orbit'
});
};
proto.initializeGLPlot = function () {
var scene = this;
scene.initializeGLCamera();
var success = scene.tryCreatePlot();
/*
* createPlot will throw when webgl is not enabled in the client.
* Lets return an instance of the module with all functions noop'd.
* The destroy method - which will remove the container from the DOM
* is overridden with a function that removes the container only.
*/
if (!success) return showNoWebGlMsg(scene);
// List of scene objects
scene.traces = {};
scene.make4thDimension();
var gd = scene.graphDiv;
var layout = gd.layout;
var makeUpdate = function () {
var update = {};
if (scene.isCameraChanged(layout)) {
// camera updates
update[scene.id + '.camera'] = scene.getCamera();
}
if (scene.isAspectChanged(layout)) {
// scene updates
update[scene.id + '.aspectratio'] = scene.glplot.getAspectratio();
if (layout[scene.id].aspectmode !== 'manual') {
scene.fullSceneLayout.aspectmode = layout[scene.id].aspectmode = update[scene.id + '.aspectmode'] = 'manual';
}
}
return update;
};
var relayoutCallback = function (scene) {
if (scene.fullSceneLayout.dragmode === false) return;
var update = makeUpdate();
scene.saveLayout(layout);
scene.graphDiv.emit('plotly_relayout', update);
};
if (scene.glplot.canvas) {
scene.glplot.canvas.addEventListener('mouseup', function () {
relayoutCallback(scene);
});
scene.glplot.canvas.addEventListener('touchstart', function () {
tabletmode = true;
});
scene.glplot.canvas.addEventListener('wheel', function (e) {
if (gd._context._scrollZoom.gl3d) {
if (scene.camera._ortho) {
var s = e.deltaX > e.deltaY ? 1.1 : 1.0 / 1.1;
var o = scene.glplot.getAspectratio();
scene.glplot.setAspectratio({
x: s * o.x,
y: s * o.y,
z: s * o.z
});
}
relayoutCallback(scene);
}
}, passiveSupported ? {
passive: false
} : false);
scene.glplot.canvas.addEventListener('mousemove', function () {
if (scene.fullSceneLayout.dragmode === false) return;
if (scene.camera.mouseListener.buttons === 0) return;
var update = makeUpdate();
scene.graphDiv.emit('plotly_relayouting', update);
});
if (!scene.staticMode) {
scene.glplot.canvas.addEventListener('webglcontextlost', function (event) {
if (gd && gd.emit) {
gd.emit('plotly_webglcontextlost', {
event: event,
layer: scene.id
});
}
}, false);
}
}
scene.glplot.oncontextloss = function () {
scene.recoverContext();
};
scene.glplot.onrender = function () {
scene.render();
};
return true;
};
proto.render = function () {
var scene = this;
var gd = scene.graphDiv;
var trace;
// update size of svg container
var svgContainer = scene.svgContainer;
var clientRect = scene.container.getBoundingClientRect();
gd._fullLayout._calcInverseTransform(gd);
var scaleX = gd._fullLayout._invScaleX;
var scaleY = gd._fullLayout._invScaleY;
var width = clientRect.width * scaleX;
var height = clientRect.height * scaleY;
svgContainer.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
svgContainer.setAttributeNS(null, 'width', width);
svgContainer.setAttributeNS(null, 'height', height);
computeTickMarks(scene);
scene.glplot.axes.update(scene.axesOptions);
// check if pick has changed
var keys = Object.keys(scene.traces);
var lastPicked = null;
var selection = scene.glplot.selection;
for (var i = 0; i < keys.length; ++i) {
trace = scene.traces[keys[i]];
if (trace.data.hoverinfo !== 'skip' && trace.handlePick(selection)) {
lastPicked = trace;
}
if (trace.setContourLevels) trace.setContourLevels();
}
function formatter(axLetter, val, hoverformat) {
var ax = scene.fullSceneLayout[axLetter + 'axis'];
if (ax.type !== 'log') {
val = ax.d2l(val);
}
return Axes.hoverLabelText(ax, val, hoverformat);
}
if (lastPicked !== null) {
var pdata = project(scene.glplot.cameraParams, selection.dataCoordinate);
trace = lastPicked.data;
var traceNow = gd._fullData[trace.index];
var ptNumber = selection.index;
var labels = {
xLabel: formatter('x', selection.traceCoordinate[0], trace.xhoverformat),
yLabel: formatter('y', selection.traceCoordinate[1], trace.yhoverformat),
zLabel: formatter('z', selection.traceCoordinate[2], trace.zhoverformat)
};
var hoverinfo = Fx.castHoverinfo(traceNow, scene.fullLayout, ptNumber);
var hoverinfoParts = (hoverinfo || '').split('+');
var isHoverinfoAll = hoverinfo && hoverinfo === 'all';
if (!traceNow.hovertemplate && !isHoverinfoAll) {
if (hoverinfoParts.indexOf('x') === -1) labels.xLabel = undefined;
if (hoverinfoParts.indexOf('y') === -1) labels.yLabel = undefined;
if (hoverinfoParts.indexOf('z') === -1) labels.zLabel = undefined;
if (hoverinfoParts.indexOf('text') === -1) selection.textLabel = undefined;
if (hoverinfoParts.indexOf('name') === -1) lastPicked.name = undefined;
}
var tx;
var vectorTx = [];
if (trace.type === 'cone' || trace.type === 'streamtube') {
labels.uLabel = formatter('x', selection.traceCoordinate[3], trace.uhoverformat);
if (isHoverinfoAll || hoverinfoParts.indexOf('u') !== -1) {
vectorTx.push('u: ' + labels.uLabel);
}
labels.vLabel = formatter('y', selection.traceCoordinate[4], trace.vhoverformat);
if (isHoverinfoAll || hoverinfoParts.indexOf('v') !== -1) {
vectorTx.push('v: ' + labels.vLabel);
}
labels.wLabel = formatter('z', selection.traceCoordinate[5], trace.whoverformat);
if (isHoverinfoAll || hoverinfoParts.indexOf('w') !== -1) {
vectorTx.push('w: ' + labels.wLabel);
}
labels.normLabel = selection.traceCoordinate[6].toPrecision(3);
if (isHoverinfoAll || hoverinfoParts.indexOf('norm') !== -1) {
vectorTx.push('norm: ' + labels.normLabel);
}
if (trace.type === 'streamtube') {
labels.divergenceLabel = selection.traceCoordinate[7].toPrecision(3);
if (isHoverinfoAll || hoverinfoParts.indexOf('divergence') !== -1) {
vectorTx.push('divergence: ' + labels.divergenceLabel);
}
}
if (selection.textLabel) {
vectorTx.push(selection.textLabel);
}
tx = vectorTx.join(' ');
} else if (trace.type === 'isosurface' || trace.type === 'volume') {
labels.valueLabel = Axes.hoverLabelText(scene._mockAxis, scene._mockAxis.d2l(selection.traceCoordinate[3]), trace.valuehoverformat);
vectorTx.push('value: ' + labels.valueLabel);
if (selection.textLabel) {
vectorTx.push(selection.textLabel);
}
tx = vectorTx.join(' ');
} else {
tx = selection.textLabel;
}
var pointData = {
x: selection.traceCoordinate[0],
y: selection.traceCoordinate[1],
z: selection.traceCoordinate[2],
data: traceNow._input,
fullData: traceNow,
curveNumber: traceNow.index,
pointNumber: ptNumber
};
Fx.appendArrayPointValue(pointData, traceNow, ptNumber);
if (trace._module.eventData) {
pointData = traceNow._module.eventData(pointData, selection, traceNow, {}, ptNumber);
}
var eventData = {
points: [pointData]
};
if (scene.fullSceneLayout.hovermode) {
var bbox = [];
Fx.loneHover({
trace: traceNow,
x: (0.5 + 0.5 * pdata[0] / pdata[3]) * width,
y: (0.5 - 0.5 * pdata[1] / pdata[3]) * height,
xLabel: labels.xLabel,
yLabel: labels.yLabel,
zLabel: labels.zLabel,
text: tx,
name: lastPicked.name,
color: Fx.castHoverOption(traceNow, ptNumber, 'bgcolor') || lastPicked.color,
borderColor: Fx.castHoverOption(traceNow, ptNumber, 'bordercolor'),
fontFamily: Fx.castHoverOption(traceNow, ptNumber, 'font.family'),
fontSize: Fx.castHoverOption(traceNow, ptNumber, 'font.size'),
fontColor: Fx.castHoverOption(traceNow, ptNumber, 'font.color'),
nameLength: Fx.castHoverOption(traceNow, ptNumber, 'namelength'),
textAlign: Fx.castHoverOption(traceNow, ptNumber, 'align'),
hovertemplate: Lib.castOption(traceNow, ptNumber, 'hovertemplate'),
hovertemplateLabels: Lib.extendFlat({}, pointData, labels),
eventData: [pointData]
}, {
container: svgContainer,
gd: gd,
inOut_bbox: bbox
});
pointData.bbox = bbox[0];
}
if (selection.distance < 5 && (selection.buttons || tabletmode)) {
gd.emit('plotly_click', eventData);
} else {
gd.emit('plotly_hover', eventData);
}
this.oldEventData = eventData;
} else {
Fx.loneUnhover(svgContainer);
if (this.oldEventData) gd.emit('plotly_unhover', this.oldEventData);
this.oldEventData = undefined;
}
scene.drawAnnotations(scene);
};
proto.recoverContext = function () {
var scene = this;
scene.glplot.dispose();
var tryRecover = function () {
if (scene.glplot.gl.isContextLost()) {
requestAnimationFrame(tryRecover);
return;
}
if (!scene.initializeGLPlot()) {
Lib.error('Catastrophic and unrecoverable WebGL error. Context lost.');
return;
}
scene.plot.apply(scene, scene.plotArgs);
};
requestAnimationFrame(tryRecover);
};
var axisProperties = ['xaxis', 'yaxis', 'zaxis'];
function computeTraceBounds(scene, trace, bounds) {
var fullSceneLayout = scene.fullSceneLayout;
for (var d = 0; d < 3; d++) {
var axisName = axisProperties[d];
var axLetter = axisName.charAt(0);
var ax = fullSceneLayout[axisName];
var coords = trace[axLetter];
var calendar = trace[axLetter + 'calendar'];
var len = trace['_' + axLetter + 'length'];
if (!Lib.isArrayOrTypedArray(coords)) {
bounds[0][d] = Math.min(bounds[0][d], 0);
bounds[1][d] = Math.max(bounds[1][d], len - 1);
} else {
var v;
for (var i = 0; i < (len || coords.length); i++) {
if (Lib.isArrayOrTypedArray(coords[i])) {
for (var j = 0; j < coords[i].length; ++j) {
v = ax.d2l(coords[i][j], 0, calendar);
if (!isNaN(v) && isFinite(v)) {
bounds[0][d] = Math.min(bounds[0][d], v);
bounds[1][d] = Math.max(bounds[1][d], v);
}
}
} else {
v = ax.d2l(coords[i], 0, calendar);
if (!isNaN(v) && isFinite(v)) {
bounds[0][d] = Math.min(bounds[0][d], v);
bounds[1][d] = Math.max(bounds[1][d], v);
}
}
}
}
}
}
function computeAnnotationBounds(scene, bounds) {
var fullSceneLayout = scene.fullSceneLayout;
var annotations = fullSceneLayout.annotations || [];
for (var d = 0; d < 3; d++) {
var axisName = axisProperties[d];
var axLetter = axisName.charAt(0);
var ax = fullSceneLayout[axisName];
for (var j = 0; j < annotations.length; j++) {
var ann = annotations[j];
if (ann.visible) {
var pos = ax.r2l(ann[axLetter]);
if (!isNaN(pos) && isFinite(pos)) {
bounds[0][d] = Math.min(bounds[0][d], pos);
bounds[1][d] = Math.max(bounds[1][d], pos);
}
}
}
}
}
proto.plot = function (sceneData, fullLayout, layout) {
var scene = this;
// Save parameters
scene.plotArgs = [sceneData, fullLayout, layout];
if (scene.glplot.contextLost) return;
var data, trace;
var i, j, axis, axisType;
var fullSceneLayout = fullLayout[scene.id];
var sceneLayout = layout[scene.id];
// Update layout
scene.fullLayout = fullLayout;
scene.fullSceneLayout = fullSceneLayout;
scene.axesOptions.merge(fullLayout, fullSceneLayout);
scene.spikeOptions.merge(fullSceneLayout);
// Update camera and camera mode
scene.setViewport(fullSceneLayout);
scene.updateFx(fullSceneLayout.dragmode, fullSceneLayout.hovermode);
scene.camera.enableWheel = scene.graphDiv._context._scrollZoom.gl3d;
// Update scene background
scene.glplot.setClearColor(str2RGBAarray(fullSceneLayout.bgcolor));
// Update axes functions BEFORE updating traces
scene.setConvert(axis);
// Convert scene data
if (!sceneData) sceneData = [];else if (!Array.isArray(sceneData)) sceneData = [sceneData];
// Compute trace bounding box
var dataBounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
for (i = 0; i < sceneData.length; ++i) {
data = sceneData[i];
if (data.visible !== true || data._length === 0) continue;
computeTraceBounds(this, data, dataBounds);
}
computeAnnotationBounds(this, dataBounds);
var dataScale = [1, 1, 1];
for (j = 0; j < 3; ++j) {
if (dataBounds[1][j] === dataBounds[0][j]) {
dataScale[j] = 1.0;
} else {
dataScale[j] = 1.0 / (dataBounds[1][j] - dataBounds[0][j]);
}
}
// Save scale
scene.dataScale = dataScale;
// after computeTraceBounds where ax._categories are filled in
scene.convertAnnotations(this);
// Update traces
for (i = 0; i < sceneData.length; ++i) {
data = sceneData[i];
if (data.visible !== true || data._length === 0) {
continue;
}
trace = scene.traces[data.uid];
if (trace) {
if (trace.data.type === data.type) {
trace.update(data);
} else {
trace.dispose();
trace = data._module.plot(this, data);
scene.traces[data.uid] = trace;
}
} else {
trace = data._module.plot(this, data);
scene.traces[data.uid] = trace;
}
trace.name = data.name;
}
// Remove empty traces
var traceIds = Object.keys(scene.traces);
traceIdLoop: for (i = 0; i < traceIds.length; ++i) {
for (j = 0; j < sceneData.length; ++j) {
if (sceneData[j].uid === traceIds[i] && sceneData[j].visible === true && sceneData[j]._length !== 0) {
continue traceIdLoop;
}
}
trace = scene.traces[traceIds[i]];
trace.dispose();
delete scene.traces[traceIds[i]];
}
// order object per trace index
scene.glplot.objects.sort(function (a, b) {
return a._trace.data.index - b._trace.data.index;
});
// Update ranges (needs to be called *after* objects are added due to updates)
var sceneBounds = [[0, 0, 0], [0, 0, 0]];
var axisDataRange = [];
var axisTypeRatios = {};
for (i = 0; i < 3; ++i) {
axis = fullSceneLayout[axisProperties[i]];
axisType = axis.type;
if (axisType in axisTypeRatios) {
axisTypeRatios[axisType].acc *= dataScale[i];
axisTypeRatios[axisType].count += 1;
} else {
axisTypeRatios[axisType] = {
acc: dataScale[i],
count: 1
};
}
var range;
if (axis.autorange) {
sceneBounds[0][i] = Infinity;
sceneBounds[1][i] = -Infinity;
var objects = scene.glplot.objects;
var annotations = scene.fullSceneLayout.annotations || [];
var axLetter = axis._name.charAt(0);
for (j = 0; j < objects.length; j++) {
var obj = objects[j];
var objBounds = obj.bounds;
var pad = obj._trace.data._pad || 0;
if (obj.constructor.name === 'ErrorBars' && axis._lowerLogErrorBound) {
sceneBounds[0][i] = Math.min(sceneBounds[0][i], axis._lowerLogErrorBound);
} else {
sceneBounds[0][i] = Math.min(sceneBounds[0][i], objBounds[0][i] / dataScale[i] - pad);
}
sceneBounds[1][i] = Math.max(sceneBounds[1][i], objBounds[1][i] / dataScale[i] + pad);
}
for (j = 0; j < annotations.length; j++) {
var ann = annotations[j];
// N.B. not taking into consideration the arrowhead
if (ann.visible) {
var pos = axis.r2l(ann[axLetter]);
sceneBounds[0][i] = Math.min(sceneBounds[0][i], pos);
sceneBounds[1][i] = Math.max(sceneBounds[1][i], pos);
}
}
if ('rangemode' in axis && axis.rangemode === 'tozero') {
sceneBounds[0][i] = Math.min(sceneBounds[0][i], 0);
sceneBounds[1][i] = Math.max(sceneBounds[1][i], 0);
}
if (sceneBounds[0][i] > sceneBounds[1][i]) {
sceneBounds[0][i] = -1;
sceneBounds[1][i] = 1;
} else {
var d = sceneBounds[1][i] - sceneBounds[0][i];
sceneBounds[0][i] -= d / 32.0;
sceneBounds[1][i] += d / 32.0;
}
range = [sceneBounds[0][i], sceneBounds[1][i]];
range = applyAutorangeOptions(range, axis);
sceneBounds[0][i] = range[0];
sceneBounds[1][i] = range[1];
if (axis.isReversed()) {
// swap bounds:
var tmp = sceneBounds[0][i];
sceneBounds[0][i] = sceneBounds[1][i];
sceneBounds[1][i] = tmp;
}
} else {
range = axis.range;
sceneBounds[0][i] = axis.r2l(range[0]);
sceneBounds[1][i] = axis.r2l(range[1]);
}
if (sceneBounds[0][i] === sceneBounds[1][i]) {
sceneBounds[0][i] -= 1;
sceneBounds[1][i] += 1;
}
axisDataRange[i] = sceneBounds[1][i] - sceneBounds[0][i];
axis.range = [sceneBounds[0][i], sceneBounds[1][i]];
axis.limitRange();
// Update plot bounds
scene.glplot.setBounds(i, {
min: axis.range[0] * dataScale[i],
max: axis.range[1] * dataScale[i]
});
}
/*
* Dynamically set the aspect ratio depending on the users aspect settings
*/
var aspectRatio;
var aspectmode = fullSceneLayout.aspectmode;
if (aspectmode === 'cube') {
aspectRatio = [1, 1, 1];
} else if (aspectmode === 'manual') {
var userRatio = fullSceneLayout.aspectratio;
aspectRatio = [userRatio.x, userRatio.y, userRatio.z];
} else if (aspectmode === 'auto' || aspectmode === 'data') {
var axesScaleRatio = [1, 1, 1];
// Compute axis scale per category
for (i = 0; i < 3; ++i) {
axis = fullSceneLayout[axisProperties[i]];
axisType = axis.type;
var axisRatio = axisTypeRatios[axisType];
axesScaleRatio[i] = Math.pow(axisRatio.acc, 1.0 / axisRatio.count) / dataScale[i];
}
if (aspectmode === 'data') {
aspectRatio = axesScaleRatio;
} else {
// i.e. 'auto' option
if (Math.max.apply(null, axesScaleRatio) / Math.min.apply(null, axesScaleRatio) <= 4) {
// USE DATA MODE WHEN AXIS RANGE DIMENSIONS ARE RELATIVELY EQUAL
aspectRatio = axesScaleRatio;
} else {
// USE EQUAL MODE WHEN AXIS RANGE DIMENSIONS ARE HIGHLY UNEQUAL
aspectRatio = [1, 1, 1];
}
}
} else {
throw new Error('scene.js aspectRatio was not one of the enumerated types');
}
/*
* Write aspect Ratio back to user data and fullLayout so that it is modifies as user
* manipulates the aspectmode settings and the fullLayout is up-to-date.
*/
fullSceneLayout.aspectratio.x = sceneLayout.aspectratio.x = aspectRatio[0];
fullSceneLayout.aspectratio.y = sceneLayout.aspectratio.y = aspectRatio[1];
fullSceneLayout.aspectratio.z = sceneLayout.aspectratio.z = aspectRatio[2];
/*
* Finally assign the computed aspecratio to the glplot module. This will have an effect
* on the next render cycle.
*/
scene.glplot.setAspectratio(fullSceneLayout.aspectratio);
// save 'initial' aspectratio & aspectmode view settings for modebar buttons
if (!scene.viewInitial.aspectratio) {
scene.viewInitial.aspectratio = {
x: fullSceneLayout.aspectratio.x,
y: fullSceneLayout.aspectratio.y,
z: fullSceneLayout.aspectratio.z
};
}
if (!scene.viewInitial.aspectmode) {
scene.viewInitial.aspectmode = fullSceneLayout.aspectmode;
}
// Update frame position for multi plots
var domain = fullSceneLayout.domain || null;
var size = fullLayout._size || null;
if (domain && size) {
var containerStyle = scene.container.style;
containerStyle.position = 'absolute';
containerStyle.left = size.l + domain.x[0] * size.w + 'px';
containerStyle.top = size.t + (1 - domain.y[1]) * size.h + 'px';
containerStyle.width = size.w * (domain.x[1] - domain.x[0]) + 'px';
containerStyle.height = size.h * (domain.y[1] - domain.y[0]) + 'px';
}
// force redraw so that promise is returned when rendering is completed
scene.glplot.redraw();
};
proto.destroy = function () {
var scene = this;
if (!scene.glplot) return;
scene.camera.mouseListener.enabled = false;
scene.container.removeEventListener('wheel', scene.camera.wheelListener);
scene.camera = null;
scene.glplot.dispose();
scene.container.parentNode.removeChild(scene.container);
scene.glplot = null;
};
// getCameraArrays :: plotly_coords -> gl-plot3d_coords
// inverse of getLayoutCamera
function getCameraArrays(camera) {
return [[camera.eye.x, camera.eye.y, camera.eye.z], [camera.center.x, camera.center.y, camera.center.z], [camera.up.x, camera.up.y, camera.up.z]];
}
// getLayoutCamera :: gl-plot3d_coords -> plotly_coords
// inverse of getCameraArrays
function getLayoutCamera(camera) {
return {
up: {
x: camera.up[0],
y: camera.up[1],
z: camera.up[2]
},
center: {
x: camera.center[0],
y: camera.center[1],
z: camera.center[2]
},
eye: {
x: camera.eye[0],
y: camera.eye[1],
z: camera.eye[2]
},
projection: {
type: camera._ortho === true ? 'orthographic' : 'perspective'
}
};
}
// get camera position in plotly coords from 'gl-plot3d' coords
proto.getCamera = function () {
var scene = this;
scene.camera.view.recalcMatrix(scene.camera.view.lastT());
return getLayoutCamera(scene.camera);
};
// set gl-plot3d camera position and scene aspects with a set of plotly coords
proto.setViewport = function (sceneLayout) {
var scene = this;
var cameraData = sceneLayout.camera;
scene.camera.lookAt.apply(this, getCameraArrays(cameraData));
scene.glplot.setAspectratio(sceneLayout.aspectratio);
var newOrtho = cameraData.projection.type === 'orthographic';
var oldOrtho = scene.camera._ortho;
if (newOrtho !== oldOrtho) {
scene.glplot.redraw(); // TODO: figure out why we need to redraw here?
scene.glplot.clearRGBA();
scene.glplot.dispose();
scene.initializeGLPlot();
}
};
proto.isCameraChanged = function (layout) {
var scene = this;
var cameraData = scene.getCamera();
var cameraNestedProp = Lib.nestedProperty(layout, scene.id + '.camera');
var cameraDataLastSave = cameraNestedProp.get();
function same(x, y, i, j) {
var vectors = ['up', 'center', 'eye'];
var components = ['x', 'y', 'z'];
return y[vectors[i]] && x[vectors[i]][components[j]] === y[vectors[i]][components[j]];
}
var changed = false;
if (cameraDataLastSave === undefined) {
changed = true;
} else {
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (!same(cameraData, cameraDataLastSave, i, j)) {
changed = true;
break;
}
}
}
if (!cameraDataLastSave.projection || cameraData.projection && cameraData.projection.type !== cameraDataLastSave.projection.type) {
changed = true;
}
}
return changed;
};
proto.isAspectChanged = function (layout) {
var scene = this;
var aspectData = scene.glplot.getAspectratio();
var aspectNestedProp = Lib.nestedProperty(layout, scene.id + '.aspectratio');
var aspectDataLastSave = aspectNestedProp.get();
return aspectDataLastSave === undefined || aspectDataLastSave.x !== aspectData.x || aspectDataLastSave.y !== aspectData.y || aspectDataLastSave.z !== aspectData.z;
};
// save camera to user layout (i.e. gd.layout)
proto.saveLayout = function (layout) {
var scene = this;
var fullLayout = scene.fullLayout;
var cameraData;
var cameraNestedProp;
var cameraDataLastSave;
var aspectData;
var aspectNestedProp;
var aspectDataLastSave;
var cameraChanged = scene.isCameraChanged(layout);
var aspectChanged = scene.isAspectChanged(layout);
var hasChanged = cameraChanged || aspectChanged;
if (hasChanged) {
var preGUI = {};
if (cameraChanged) {
cameraData = scene.getCamera();
cameraNestedProp = Lib.nestedProperty(layout, scene.id + '.camera');
cameraDataLastSave = cameraNestedProp.get();
preGUI[scene.id + '.camera'] = cameraDataLastSave;
}
if (aspectChanged) {
aspectData = scene.glplot.getAspectratio();
aspectNestedProp = Lib.nestedProperty(layout, scene.id + '.aspectratio');
aspectDataLastSave = aspectNestedProp.get();
preGUI[scene.id + '.aspectratio'] = aspectDataLastSave;
}
Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, preGUI);
if (cameraChanged) {
cameraNestedProp.set(cameraData);
var cameraFullNP = Lib.nestedProperty(fullLayout, scene.id + '.camera');
cameraFullNP.set(cameraData);
}
if (aspectChanged) {
aspectNestedProp.set(aspectData);
var aspectFullNP = Lib.nestedProperty(fullLayout, scene.id + '.aspectratio');
aspectFullNP.set(aspectData);
scene.glplot.redraw();
}
}
return hasChanged;
};
proto.updateFx = function (dragmode, hovermode) {
var scene = this;
var camera = scene.camera;
if (camera) {
// rotate and orbital are synonymous
if (dragmode === 'orbit') {
camera.mode = 'orbit';
camera.keyBindingMode = 'rotate';
} else if (dragmode === 'turntable') {
camera.up = [0, 0, 1];
camera.mode = 'turntable';
camera.keyBindingMode = 'rotate';
// The setter for camera.mode animates the transition to z-up,
// but only if we *don't* explicitly set z-up earlier via the
// relayout. So push `up` back to layout & fullLayout manually now.
var gd = scene.graphDiv;
var fullLayout = gd._fullLayout;
var fullCamera = scene.fullSceneLayout.camera;
var x = fullCamera.up.x;
var y = fullCamera.up.y;
var z = fullCamera.up.z;
// only push `up` back to (full)layout if it's going to change
if (z / Math.sqrt(x * x + y * y + z * z) < 0.999) {
var attr = scene.id + '.camera.up';
var zUp = {
x: 0,
y: 0,
z: 1
};
var edits = {};
edits[attr] = zUp;
var layout = gd.layout;
Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, edits);
fullCamera.up = zUp;
Lib.nestedProperty(layout, attr).set(zUp);
}
} else {
// none rotation modes [pan or zoom]
camera.keyBindingMode = dragmode;
}
}
// to put dragmode and hovermode on the same grounds from relayout
scene.fullSceneLayout.hovermode = hovermode;
};
function flipPixels(pixels, w, h) {
for (var i = 0, q = h - 1; i < q; ++i, --q) {
for (var j = 0; j < w; ++j) {
for (var k = 0; k < 4; ++k) {
var a = 4 * (w * i + j) + k;
var b = 4 * (w * q + j) + k;
var tmp = pixels[a];
pixels[a] = pixels[b];
pixels[b] = tmp;
}
}
}
}
function correctRGB(pixels, w, h) {
for (var i = 0; i < h; ++i) {
for (var j = 0; j < w; ++j) {
var k = 4 * (w * i + j);
var a = pixels[k + 3]; // alpha
if (a > 0) {
var q = 255 / a;
for (var l = 0; l < 3; ++l) {
// RGB
pixels[k + l] = Math.min(q * pixels[k + l], 255);
}
}
}
}
}
proto.toImage = function (format) {
var scene = this;
if (!format) format = 'png';
if (scene.staticMode) scene.container.appendChild(STATIC_CANVAS);
// Force redraw
scene.glplot.redraw();
// Grab context and yank out pixels
var gl = scene.glplot.gl;
var w = gl.drawingBufferWidth;
var h = gl.drawingBufferHeight;
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
var pixels = new Uint8Array(w * h * 4);
gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
flipPixels(pixels, w, h);
correctRGB(pixels, w, h);
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var context = canvas.getContext('2d', {
willReadFrequently: true
});
var imageData = context.createImageData(w, h);
imageData.data.set(pixels);
context.putImageData(imageData, 0, 0);
var dataURL;
switch (format) {
case 'jpeg':
dataURL = canvas.toDataURL('image/jpeg');
break;
case 'webp':
dataURL = canvas.toDataURL('image/webp');
break;
default:
dataURL = canvas.toDataURL('image/png');
}
if (scene.staticMode) scene.container.removeChild(STATIC_CANVAS);
return dataURL;
};
proto.setConvert = function () {
var scene = this;
for (var i = 0; i < 3; i++) {
var ax = scene.fullSceneLayout[axisProperties[i]];
Axes.setConvert(ax, scene.fullLayout);
ax.setScale = Lib.noop;
}
};
proto.make4thDimension = function () {
var scene = this;
var gd = scene.graphDiv;
var fullLayout = gd._fullLayout;
// mock axis for hover formatting
scene._mockAxis = {
type: 'linear',
showexponent: 'all',
exponentformat: 'B'
};
Axes.setConvert(scene._mockAxis, fullLayout);
};
module.exports = Scene;
/***/ }),
/***/ 52094:
/***/ (function(module) {
"use strict";
module.exports = function zip3(x, y, z, len) {
len = len || x.length;
var result = new Array(len);
for (var i = 0; i < len; i++) {
result[i] = [x[i], y[i], z[i]];
}
return result;
};
/***/ }),
/***/ 64859:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var animationAttrs = __webpack_require__(85656);
var colorAttrs = __webpack_require__(22548);
var drawNewShapeAttrs = __webpack_require__(92872);
var drawNewSelectionAttrs = __webpack_require__(34200);
var padAttrs = __webpack_require__(66741);
var extendFlat = (__webpack_require__(92880).extendFlat);
var globalFont = fontAttrs({
editType: 'calc'
});
globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
globalFont.size.dflt = 12;
globalFont.color.dflt = colorAttrs.defaultLine;
module.exports = {
font: globalFont,
title: {
text: {
valType: 'string',
editType: 'layoutstyle'
},
font: fontAttrs({
editType: 'layoutstyle'
}),
subtitle: {
text: {
valType: 'string',
editType: 'layoutstyle'
},
font: fontAttrs({
editType: 'layoutstyle'
}),
editType: 'layoutstyle'
},
xref: {
valType: 'enumerated',
dflt: 'container',
values: ['container', 'paper'],
editType: 'layoutstyle'
},
yref: {
valType: 'enumerated',
dflt: 'container',
values: ['container', 'paper'],
editType: 'layoutstyle'
},
x: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.5,
editType: 'layoutstyle'
},
y: {
valType: 'number',
min: 0,
max: 1,
dflt: 'auto',
editType: 'layoutstyle'
},
xanchor: {
valType: 'enumerated',
dflt: 'auto',
values: ['auto', 'left', 'center', 'right'],
editType: 'layoutstyle'
},
yanchor: {
valType: 'enumerated',
dflt: 'auto',
values: ['auto', 'top', 'middle', 'bottom'],
editType: 'layoutstyle'
},
pad: extendFlat(padAttrs({
editType: 'layoutstyle'
}), {}),
automargin: {
valType: 'boolean',
dflt: false,
editType: 'plot'
},
editType: 'layoutstyle'
},
uniformtext: {
mode: {
valType: 'enumerated',
values: [false, 'hide', 'show'],
dflt: false,
editType: 'plot'
},
minsize: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'plot'
},
editType: 'plot'
},
autosize: {
valType: 'boolean',
dflt: false,
// autosize, width, and height get special editType treatment in _relayout
// so we can handle noop resizes more efficiently
editType: 'none'
},
width: {
valType: 'number',
min: 10,
dflt: 700,
editType: 'plot'
},
height: {
valType: 'number',
min: 10,
dflt: 450,
editType: 'plot'
},
minreducedwidth: {
valType: 'number',
min: 2,
dflt: 64,
editType: 'plot'
},
minreducedheight: {
valType: 'number',
min: 2,
dflt: 64,
editType: 'plot'
},
margin: {
l: {
valType: 'number',
min: 0,
dflt: 80,
editType: 'plot'
},
r: {
valType: 'number',
min: 0,
dflt: 80,
editType: 'plot'
},
t: {
valType: 'number',
min: 0,
dflt: 100,
editType: 'plot'
},
b: {
valType: 'number',
min: 0,
dflt: 80,
editType: 'plot'
},
pad: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'plot'
},
autoexpand: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
editType: 'plot'
},
computed: {
valType: 'any',
editType: 'none'
},
paper_bgcolor: {
valType: 'color',
dflt: colorAttrs.background,
editType: 'plot'
},
plot_bgcolor: {
// defined here, but set in cartesian.supplyLayoutDefaults
// because it needs to know if there are (2D) axes or not
valType: 'color',
dflt: colorAttrs.background,
editType: 'layoutstyle'
},
autotypenumbers: {
valType: 'enumerated',
values: ['convert types', 'strict'],
dflt: 'convert types',
editType: 'calc'
},
separators: {
valType: 'string',
editType: 'plot'
},
hidesources: {
valType: 'boolean',
dflt: false,
editType: 'plot'
},
showlegend: {
// handled in legend.supplyLayoutDefaults
// but included here because it's not in the legend object
valType: 'boolean',
editType: 'legend'
},
colorway: {
valType: 'colorlist',
dflt: colorAttrs.defaults,
editType: 'calc'
},
datarevision: {
valType: 'any',
editType: 'calc'
},
uirevision: {
valType: 'any',
editType: 'none'
},
editrevision: {
valType: 'any',
editType: 'none'
},
selectionrevision: {
valType: 'any',
editType: 'none'
},
template: {
valType: 'any',
editType: 'calc'
},
newshape: drawNewShapeAttrs.newshape,
activeshape: drawNewShapeAttrs.activeshape,
newselection: drawNewSelectionAttrs.newselection,
activeselection: drawNewSelectionAttrs.activeselection,
meta: {
valType: 'any',
arrayOk: true,
editType: 'plot'
},
transition: extendFlat({}, animationAttrs.transition, {
editType: 'none'
}),
_deprecated: {
title: {
valType: 'string',
editType: 'layoutstyle'
},
titlefont: fontAttrs({
editType: 'layoutstyle'
})
}
};
/***/ }),
/***/ 47552:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var sortObjectKeys = __webpack_require__(95376);
var requiredVersion = '1.13.4';
var OSM = '© OpenStreetMap contributors';
var carto = ['© Carto ', OSM].join(' ');
var stamenTerrainOrToner = ['Map tiles by Stamen Design ', 'under CC BY 3.0 ', '|', 'Data by OpenStreetMap contributors', 'under ODbL '].join(' ');
var stamenWaterColor = ['Map tiles by Stamen Design ', 'under CC BY 3.0 ', '|', 'Data by OpenStreetMap contributors', 'under CC BY SA '].join(' ');
var stylesNonMapbox = {
'open-street-map': {
id: 'osm',
version: 8,
sources: {
'plotly-osm-tiles': {
type: 'raster',
attribution: OSM,
tiles: ['https://a.tile.openstreetmap.org/{z}/{x}/{y}.png', 'https://b.tile.openstreetmap.org/{z}/{x}/{y}.png'],
tileSize: 256
}
},
layers: [{
id: 'plotly-osm-tiles',
type: 'raster',
source: 'plotly-osm-tiles',
minzoom: 0,
maxzoom: 22
}],
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf'
},
'white-bg': {
id: 'white-bg',
version: 8,
sources: {},
layers: [{
id: 'white-bg',
type: 'background',
paint: {
'background-color': '#FFFFFF'
},
minzoom: 0,
maxzoom: 22
}],
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf'
},
'carto-positron': {
id: 'carto-positron',
version: 8,
sources: {
'plotly-carto-positron': {
type: 'raster',
attribution: carto,
tiles: ['https://cartodb-basemaps-c.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png'],
tileSize: 256
}
},
layers: [{
id: 'plotly-carto-positron',
type: 'raster',
source: 'plotly-carto-positron',
minzoom: 0,
maxzoom: 22
}],
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf'
},
'carto-darkmatter': {
id: 'carto-darkmatter',
version: 8,
sources: {
'plotly-carto-darkmatter': {
type: 'raster',
attribution: carto,
tiles: ['https://cartodb-basemaps-c.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png'],
tileSize: 256
}
},
layers: [{
id: 'plotly-carto-darkmatter',
type: 'raster',
source: 'plotly-carto-darkmatter',
minzoom: 0,
maxzoom: 22
}],
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf'
},
'stamen-terrain': {
id: 'stamen-terrain',
version: 8,
sources: {
'plotly-stamen-terrain': {
type: 'raster',
attribution: stamenTerrainOrToner,
tiles: ['https://tiles.stadiamaps.com/tiles/stamen_terrain/{z}/{x}/{y}.png?api_key='],
tileSize: 256
}
},
layers: [{
id: 'plotly-stamen-terrain',
type: 'raster',
source: 'plotly-stamen-terrain',
minzoom: 0,
maxzoom: 22
}],
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf'
},
'stamen-toner': {
id: 'stamen-toner',
version: 8,
sources: {
'plotly-stamen-toner': {
type: 'raster',
attribution: stamenTerrainOrToner,
tiles: ['https://tiles.stadiamaps.com/tiles/stamen_toner/{z}/{x}/{y}.png?api_key='],
tileSize: 256
}
},
layers: [{
id: 'plotly-stamen-toner',
type: 'raster',
source: 'plotly-stamen-toner',
minzoom: 0,
maxzoom: 22
}],
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf'
},
'stamen-watercolor': {
id: 'stamen-watercolor',
version: 8,
sources: {
'plotly-stamen-watercolor': {
type: 'raster',
attribution: stamenWaterColor,
tiles: ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg?api_key='],
tileSize: 256
}
},
layers: [{
id: 'plotly-stamen-watercolor',
type: 'raster',
source: 'plotly-stamen-watercolor',
minzoom: 0,
maxzoom: 22
}],
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf'
}
};
var styleValuesNonMapbox = sortObjectKeys(stylesNonMapbox);
module.exports = {
requiredVersion: requiredVersion,
styleUrlPrefix: 'mapbox://styles/mapbox/',
styleUrlSuffix: 'v9',
styleValuesMapbox: ['basic', 'streets', 'outdoors', 'light', 'dark', 'satellite', 'satellite-streets'],
styleValueDflt: 'basic',
stylesNonMapbox: stylesNonMapbox,
styleValuesNonMapbox: styleValuesNonMapbox,
traceLayerPrefix: 'plotly-trace-layer-',
layoutLayerPrefix: 'plotly-layout-layer-',
wrongVersionErrorMsg: ['Your custom plotly.js bundle is not using the correct mapbox-gl version', 'Please install @plotly/mapbox-gl@' + requiredVersion + '.'].join('\n'),
noAccessTokenErrorMsg: ['Missing Mapbox access token.', 'Mapbox trace type require a Mapbox access token to be registered.', 'For example:', ' Plotly.newPlot(gd, data, layout, { mapboxAccessToken: \'my-access-token\' });', 'More info here: https://www.mapbox.com/help/define-access-token/'].join('\n'),
missingStyleErrorMsg: ['No valid mapbox style found, please set `mapbox.style` to one of:', styleValuesNonMapbox.join(', '), 'or register a Mapbox access token to use a Mapbox-served style.'].join('\n'),
multipleTokensErrorMsg: ['Set multiple mapbox access token across different mapbox subplot,', 'using first token found as mapbox-gl does not allow multiple' + 'access tokens on the same page.'].join('\n'),
mapOnErrorMsg: 'Mapbox error.',
// Mapbox logo for static export
mapboxLogo: {
path0: 'm 10.5,1.24 c -5.11,0 -9.25,4.15 -9.25,9.25 0,5.1 4.15,9.25 9.25,9.25 5.1,0 9.25,-4.15 9.25,-9.25 0,-5.11 -4.14,-9.25 -9.25,-9.25 z m 4.39,11.53 c -1.93,1.93 -4.78,2.31 -6.7,2.31 -0.7,0 -1.41,-0.05 -2.1,-0.16 0,0 -1.02,-5.64 2.14,-8.81 0.83,-0.83 1.95,-1.28 3.13,-1.28 1.27,0 2.49,0.51 3.39,1.42 1.84,1.84 1.89,4.75 0.14,6.52 z',
path1: 'M 10.5,-0.01 C 4.7,-0.01 0,4.7 0,10.49 c 0,5.79 4.7,10.5 10.5,10.5 5.8,0 10.5,-4.7 10.5,-10.5 C 20.99,4.7 16.3,-0.01 10.5,-0.01 Z m 0,19.75 c -5.11,0 -9.25,-4.15 -9.25,-9.25 0,-5.1 4.14,-9.26 9.25,-9.26 5.11,0 9.25,4.15 9.25,9.25 0,5.13 -4.14,9.26 -9.25,9.26 z',
path2: 'M 14.74,6.25 C 12.9,4.41 9.98,4.35 8.23,6.1 5.07,9.27 6.09,14.91 6.09,14.91 c 0,0 5.64,1.02 8.81,-2.14 C 16.64,11 16.59,8.09 14.74,6.25 Z m -2.27,4.09 -0.91,1.87 -0.9,-1.87 -1.86,-0.91 1.86,-0.9 0.9,-1.87 0.91,1.87 1.86,0.9 z',
polygon: '11.56,12.21 10.66,10.34 8.8,9.43 10.66,8.53 11.56,6.66 12.47,8.53 14.33,9.43 12.47,10.34'
},
// a subset of node_modules/mapbox-gl/dist/mapbox-gl.css
styleRules: {
map: 'overflow:hidden;position:relative;',
'missing-css': 'display:none;',
canary: 'background-color:salmon;',
// Reusing CSS directives from: https://api.tiles.mapbox.com/mapbox-gl-js/v1.1.1/mapbox-gl.css
'ctrl-bottom-left': 'position: absolute; pointer-events: none; z-index: 2; bottom: 0; left: 0;',
'ctrl-bottom-right': 'position: absolute; pointer-events: none; z-index: 2; right: 0; bottom: 0;',
ctrl: 'clear: both; pointer-events: auto; transform: translate(0, 0);',
// Compact ctrl
'ctrl-attrib.mapboxgl-compact .mapboxgl-ctrl-attrib-inner': 'display: none;',
'ctrl-attrib.mapboxgl-compact:hover .mapboxgl-ctrl-attrib-inner': 'display: block; margin-top:2px',
'ctrl-attrib.mapboxgl-compact:hover': 'padding: 2px 24px 2px 4px; visibility: visible; margin-top: 6px;',
'ctrl-attrib.mapboxgl-compact::after': 'content: ""; cursor: pointer; position: absolute; background-image: url(\'data:image/svg+xml;charset=utf-8,%3Csvg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"%3E %3Cpath fill="%23333333" fill-rule="evenodd" d="M4,10a6,6 0 1,0 12,0a6,6 0 1,0 -12,0 M9,7a1,1 0 1,0 2,0a1,1 0 1,0 -2,0 M9,10a1,1 0 1,1 2,0l0,3a1,1 0 1,1 -2,0"/%3E %3C/svg%3E\'); background-color: rgba(255, 255, 255, 0.5); width: 24px; height: 24px; box-sizing: border-box; border-radius: 12px;',
'ctrl-attrib.mapboxgl-compact': 'min-height: 20px; padding: 0; margin: 10px; position: relative; background-color: #fff; border-radius: 3px 12px 12px 3px;',
'ctrl-bottom-right > .mapboxgl-ctrl-attrib.mapboxgl-compact::after': 'bottom: 0; right: 0',
'ctrl-bottom-left > .mapboxgl-ctrl-attrib.mapboxgl-compact::after': 'bottom: 0; left: 0',
'ctrl-bottom-left .mapboxgl-ctrl': 'margin: 0 0 10px 10px; float: left;',
'ctrl-bottom-right .mapboxgl-ctrl': 'margin: 0 10px 10px 0; float: right;',
'ctrl-attrib': 'color: rgba(0, 0, 0, 0.75); text-decoration: none; font-size: 12px',
'ctrl-attrib a': 'color: rgba(0, 0, 0, 0.75); text-decoration: none; font-size: 12px',
'ctrl-attrib a:hover': 'color: inherit; text-decoration: underline;',
'ctrl-attrib .mapbox-improve-map': 'font-weight: bold; margin-left: 2px;',
'attrib-empty': 'display: none;',
// Compact Mapbox logo without text
'ctrl-logo': 'display:block; width: 21px; height: 21px; background-image: url(\'data:image/svg+xml;charset=utf-8,%3C?xml version="1.0" encoding="utf-8"?%3E %3Csvg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 21 21" style="enable-background:new 0 0 21 21;" xml:space="preserve"%3E%3Cg transform="translate(0,0.01)"%3E%3Cpath d="m 10.5,1.24 c -5.11,0 -9.25,4.15 -9.25,9.25 0,5.1 4.15,9.25 9.25,9.25 5.1,0 9.25,-4.15 9.25,-9.25 0,-5.11 -4.14,-9.25 -9.25,-9.25 z m 4.39,11.53 c -1.93,1.93 -4.78,2.31 -6.7,2.31 -0.7,0 -1.41,-0.05 -2.1,-0.16 0,0 -1.02,-5.64 2.14,-8.81 0.83,-0.83 1.95,-1.28 3.13,-1.28 1.27,0 2.49,0.51 3.39,1.42 1.84,1.84 1.89,4.75 0.14,6.52 z" style="opacity:0.9;fill:%23ffffff;enable-background:new" class="st0"/%3E%3Cpath d="M 10.5,-0.01 C 4.7,-0.01 0,4.7 0,10.49 c 0,5.79 4.7,10.5 10.5,10.5 5.8,0 10.5,-4.7 10.5,-10.5 C 20.99,4.7 16.3,-0.01 10.5,-0.01 Z m 0,19.75 c -5.11,0 -9.25,-4.15 -9.25,-9.25 0,-5.1 4.14,-9.26 9.25,-9.26 5.11,0 9.25,4.15 9.25,9.25 0,5.13 -4.14,9.26 -9.25,9.26 z" style="opacity:0.35;enable-background:new" class="st1"/%3E%3Cpath d="M 14.74,6.25 C 12.9,4.41 9.98,4.35 8.23,6.1 5.07,9.27 6.09,14.91 6.09,14.91 c 0,0 5.64,1.02 8.81,-2.14 C 16.64,11 16.59,8.09 14.74,6.25 Z m -2.27,4.09 -0.91,1.87 -0.9,-1.87 -1.86,-0.91 1.86,-0.9 0.9,-1.87 0.91,1.87 1.86,0.9 z" style="opacity:0.35;enable-background:new" class="st1"/%3E%3Cpolygon points="11.56,12.21 10.66,10.34 8.8,9.43 10.66,8.53 11.56,6.66 12.47,8.53 14.33,9.43 12.47,10.34 " style="opacity:0.9;fill:%23ffffff;enable-background:new" class="st0"/%3E%3C/g%3E%3C/svg%3E\')'
// Mapbox logo WITH text below (commented out for now)
// 'ctrl-logo': 'width: 85px; height: 21px; margin: 0 0 -3px -3px; display: block; background-repeat: no-repeat; cursor: pointer; background-image: url(\'data:image/svg+xml;charset=utf-8,%3C?xml version="1.0" encoding="utf-8"?%3E%3Csvg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 84.49 21" style="enable-background:new 0 0 84.49 21;" xml:space="preserve"%3E%3Cg%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M83.25,14.26c0,0.12-0.09,0.21-0.21,0.21h-1.61c-0.13,0-0.24-0.06-0.3-0.17l-1.44-2.39l-1.44,2.39 c-0.06,0.11-0.18,0.17-0.3,0.17h-1.61c-0.04,0-0.08-0.01-0.12-0.03c-0.09-0.06-0.13-0.19-0.06-0.28l0,0l2.43-3.68L76.2,6.84 c-0.02-0.03-0.03-0.07-0.03-0.12c0-0.12,0.09-0.21,0.21-0.21h1.61c0.13,0,0.24,0.06,0.3,0.17l1.41,2.36l1.4-2.35 c0.06-0.11,0.18-0.17,0.3-0.17H83c0.04,0,0.08,0.01,0.12,0.03c0.09,0.06,0.13,0.19,0.06,0.28l0,0l-2.37,3.63l2.43,3.67 C83.24,14.18,83.25,14.22,83.25,14.26z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M66.24,9.59c-0.39-1.88-1.96-3.28-3.84-3.28c-1.03,0-2.03,0.42-2.73,1.18V3.51c0-0.13-0.1-0.23-0.23-0.23h-1.4 c-0.13,0-0.23,0.11-0.23,0.23v10.72c0,0.13,0.1,0.23,0.23,0.23h1.4c0.13,0,0.23-0.11,0.23-0.23V13.5c0.71,0.75,1.7,1.18,2.73,1.18 c1.88,0,3.45-1.41,3.84-3.29C66.37,10.79,66.37,10.18,66.24,9.59L66.24,9.59z M62.08,13c-1.32,0-2.39-1.11-2.41-2.48v-0.06 c0.02-1.38,1.09-2.48,2.41-2.48s2.42,1.12,2.42,2.51S63.41,13,62.08,13z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M71.67,6.32c-1.98-0.01-3.72,1.35-4.16,3.29c-0.13,0.59-0.13,1.19,0,1.77c0.44,1.94,2.17,3.32,4.17,3.3 c2.35,0,4.26-1.87,4.26-4.19S74.04,6.32,71.67,6.32z M71.65,13.01c-1.33,0-2.42-1.12-2.42-2.51s1.08-2.52,2.42-2.52 c1.33,0,2.42,1.12,2.42,2.51S72.99,13,71.65,13.01L71.65,13.01z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M62.08,7.98c-1.32,0-2.39,1.11-2.41,2.48v0.06C59.68,11.9,60.75,13,62.08,13s2.42-1.12,2.42-2.51 S63.41,7.98,62.08,7.98z M62.08,11.76c-0.63,0-1.14-0.56-1.17-1.25v-0.04c0.01-0.69,0.54-1.25,1.17-1.25 c0.63,0,1.17,0.57,1.17,1.27C63.24,11.2,62.73,11.76,62.08,11.76z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M71.65,7.98c-1.33,0-2.42,1.12-2.42,2.51S70.32,13,71.65,13s2.42-1.12,2.42-2.51S72.99,7.98,71.65,7.98z M71.65,11.76c-0.64,0-1.17-0.57-1.17-1.27c0-0.7,0.53-1.26,1.17-1.26s1.17,0.57,1.17,1.27C72.82,11.21,72.29,11.76,71.65,11.76z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M45.74,6.53h-1.4c-0.13,0-0.23,0.11-0.23,0.23v0.73c-0.71-0.75-1.7-1.18-2.73-1.18 c-2.17,0-3.94,1.87-3.94,4.19s1.77,4.19,3.94,4.19c1.04,0,2.03-0.43,2.73-1.19v0.73c0,0.13,0.1,0.23,0.23,0.23h1.4 c0.13,0,0.23-0.11,0.23-0.23V6.74c0-0.12-0.09-0.22-0.22-0.22C45.75,6.53,45.75,6.53,45.74,6.53z M44.12,10.53 C44.11,11.9,43.03,13,41.71,13s-2.42-1.12-2.42-2.51s1.08-2.52,2.4-2.52c1.33,0,2.39,1.11,2.41,2.48L44.12,10.53z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M41.71,7.98c-1.33,0-2.42,1.12-2.42,2.51S40.37,13,41.71,13s2.39-1.11,2.41-2.48v-0.06 C44.1,9.09,43.03,7.98,41.71,7.98z M40.55,10.49c0-0.7,0.52-1.27,1.17-1.27c0.64,0,1.14,0.56,1.17,1.25v0.04 c-0.01,0.68-0.53,1.24-1.17,1.24C41.08,11.75,40.55,11.19,40.55,10.49z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M52.41,6.32c-1.03,0-2.03,0.42-2.73,1.18V6.75c0-0.13-0.1-0.23-0.23-0.23h-1.4c-0.13,0-0.23,0.11-0.23,0.23 v10.72c0,0.13,0.1,0.23,0.23,0.23h1.4c0.13,0,0.23-0.1,0.23-0.23V13.5c0.71,0.75,1.7,1.18,2.74,1.18c2.17,0,3.94-1.87,3.94-4.19 S54.58,6.32,52.41,6.32z M52.08,13.01c-1.32,0-2.39-1.11-2.42-2.48v-0.07c0.02-1.38,1.09-2.49,2.4-2.49c1.32,0,2.41,1.12,2.41,2.51 S53.4,13,52.08,13.01L52.08,13.01z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M52.08,7.98c-1.32,0-2.39,1.11-2.42,2.48v0.06c0.03,1.38,1.1,2.48,2.42,2.48s2.41-1.12,2.41-2.51 S53.4,7.98,52.08,7.98z M52.08,11.76c-0.63,0-1.14-0.56-1.17-1.25v-0.04c0.01-0.69,0.54-1.25,1.17-1.25c0.63,0,1.17,0.58,1.17,1.27 S52.72,11.76,52.08,11.76z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M36.08,14.24c0,0.13-0.1,0.23-0.23,0.23h-1.41c-0.13,0-0.23-0.11-0.23-0.23V9.68c0-0.98-0.74-1.71-1.62-1.71 c-0.8,0-1.46,0.7-1.59,1.62l0.01,4.66c0,0.13-0.11,0.23-0.23,0.23h-1.41c-0.13,0-0.23-0.11-0.23-0.23V9.68 c0-0.98-0.74-1.71-1.62-1.71c-0.85,0-1.54,0.79-1.6,1.8v4.48c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.11-0.23-0.23V6.74 c0.01-0.13,0.1-0.22,0.23-0.22h1.4c0.13,0,0.22,0.11,0.23,0.22V7.4c0.5-0.68,1.3-1.09,2.16-1.1h0.03c1.09,0,2.09,0.6,2.6,1.55 c0.45-0.95,1.4-1.55,2.44-1.56c1.62,0,2.93,1.25,2.9,2.78L36.08,14.24z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M84.34,13.59l-0.07-0.13l-1.96-2.99l1.94-2.95c0.44-0.67,0.26-1.56-0.41-2.02c-0.02,0-0.03,0-0.04-0.01 c-0.23-0.15-0.5-0.22-0.78-0.22h-1.61c-0.56,0-1.08,0.29-1.37,0.78L79.72,6.6l-0.34-0.56C79.09,5.56,78.57,5.27,78,5.27h-1.6 c-0.6,0-1.13,0.37-1.35,0.92c-2.19-1.66-5.28-1.47-7.26,0.45c-0.35,0.34-0.65,0.72-0.89,1.14c-0.9-1.62-2.58-2.72-4.5-2.72 c-0.5,0-1.01,0.07-1.48,0.23V3.51c0-0.82-0.66-1.48-1.47-1.48h-1.4c-0.81,0-1.47,0.66-1.47,1.47v3.75 c-0.95-1.36-2.5-2.18-4.17-2.19c-0.74,0-1.46,0.16-2.12,0.47c-0.24-0.17-0.54-0.26-0.84-0.26h-1.4c-0.45,0-0.87,0.21-1.15,0.56 c-0.02-0.03-0.04-0.05-0.07-0.08c-0.28-0.3-0.68-0.47-1.09-0.47h-1.39c-0.3,0-0.6,0.09-0.84,0.26c-0.67-0.3-1.39-0.46-2.12-0.46 c-1.83,0-3.43,1-4.37,2.5c-0.2-0.46-0.48-0.89-0.83-1.25c-0.8-0.81-1.89-1.25-3.02-1.25h-0.01c-0.89,0.01-1.75,0.33-2.46,0.88 c-0.74-0.57-1.64-0.88-2.57-0.88H28.1c-0.29,0-0.58,0.03-0.86,0.11c-0.28,0.06-0.56,0.16-0.82,0.28c-0.21-0.12-0.45-0.18-0.7-0.18 h-1.4c-0.82,0-1.47,0.66-1.47,1.47v7.5c0,0.82,0.66,1.47,1.47,1.47h1.4c0.82,0,1.48-0.66,1.48-1.48l0,0V9.79 c0.03-0.36,0.23-0.59,0.36-0.59c0.18,0,0.38,0.18,0.38,0.47v4.57c0,0.82,0.66,1.47,1.47,1.47h1.41c0.82,0,1.47-0.66,1.47-1.47 l-0.01-4.57c0.06-0.32,0.25-0.47,0.35-0.47c0.18,0,0.38,0.18,0.38,0.47v4.57c0,0.82,0.66,1.47,1.47,1.47h1.41 c0.82,0,1.47-0.66,1.47-1.47v-0.38c0.96,1.29,2.46,2.06,4.06,2.06c0.74,0,1.46-0.16,2.12-0.47c0.24,0.17,0.54,0.26,0.84,0.26h1.39 c0.3,0,0.6-0.09,0.84-0.26v2.01c0,0.82,0.66,1.47,1.47,1.47h1.4c0.82,0,1.47-0.66,1.47-1.47v-1.77c0.48,0.15,0.99,0.23,1.49,0.22 c1.7,0,3.22-0.87,4.17-2.2v0.52c0,0.82,0.66,1.47,1.47,1.47h1.4c0.3,0,0.6-0.09,0.84-0.26c0.66,0.31,1.39,0.47,2.12,0.47 c1.92,0,3.6-1.1,4.49-2.73c1.54,2.65,4.95,3.53,7.58,1.98c0.18-0.11,0.36-0.22,0.53-0.36c0.22,0.55,0.76,0.91,1.35,0.9H78 c0.56,0,1.08-0.29,1.37-0.78l0.37-0.61l0.37,0.61c0.29,0.48,0.81,0.78,1.38,0.78h1.6c0.81,0,1.46-0.66,1.45-1.46 C84.49,14.02,84.44,13.8,84.34,13.59L84.34,13.59z M35.86,14.47h-1.41c-0.13,0-0.23-0.11-0.23-0.23V9.68 c0-0.98-0.74-1.71-1.62-1.71c-0.8,0-1.46,0.7-1.59,1.62l0.01,4.66c0,0.13-0.1,0.23-0.23,0.23h-1.41c-0.13,0-0.23-0.11-0.23-0.23 V9.68c0-0.98-0.74-1.71-1.62-1.71c-0.85,0-1.54,0.79-1.6,1.8v4.48c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.11-0.23-0.23 V6.74c0.01-0.13,0.11-0.22,0.23-0.22h1.4c0.13,0,0.22,0.11,0.23,0.22V7.4c0.5-0.68,1.3-1.09,2.16-1.1h0.03 c1.09,0,2.09,0.6,2.6,1.55c0.45-0.95,1.4-1.55,2.44-1.56c1.62,0,2.93,1.25,2.9,2.78l0.01,5.16C36.09,14.36,35.98,14.46,35.86,14.47 L35.86,14.47z M45.97,14.24c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.11-0.23-0.23V13.5c-0.7,0.76-1.69,1.18-2.72,1.18 c-2.17,0-3.94-1.87-3.94-4.19s1.77-4.19,3.94-4.19c1.03,0,2.02,0.43,2.73,1.18V6.74c0-0.13,0.1-0.23,0.23-0.23h1.4 c0.12-0.01,0.22,0.08,0.23,0.21c0,0.01,0,0.01,0,0.02v7.51h-0.01V14.24z M52.41,14.67c-1.03,0-2.02-0.43-2.73-1.18v3.97 c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.1-0.23-0.23V6.75c0-0.13,0.1-0.22,0.23-0.22h1.4c0.13,0,0.23,0.11,0.23,0.23v0.73 c0.71-0.76,1.7-1.18,2.73-1.18c2.17,0,3.94,1.86,3.94,4.18S54.58,14.67,52.41,14.67z M66.24,11.39c-0.39,1.87-1.96,3.29-3.84,3.29 c-1.03,0-2.02-0.43-2.73-1.18v0.73c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.11-0.23-0.23V3.51c0-0.13,0.1-0.23,0.23-0.23 h1.4c0.13,0,0.23,0.11,0.23,0.23v3.97c0.71-0.75,1.7-1.18,2.73-1.17c1.88,0,3.45,1.4,3.84,3.28C66.37,10.19,66.37,10.8,66.24,11.39 L66.24,11.39L66.24,11.39z M71.67,14.68c-2,0.01-3.73-1.35-4.17-3.3c-0.13-0.59-0.13-1.19,0-1.77c0.44-1.94,2.17-3.31,4.17-3.3 c2.36,0,4.26,1.87,4.26,4.19S74.03,14.68,71.67,14.68L71.67,14.68z M83.04,14.47h-1.61c-0.13,0-0.24-0.06-0.3-0.17l-1.44-2.39 l-1.44,2.39c-0.06,0.11-0.18,0.17-0.3,0.17h-1.61c-0.04,0-0.08-0.01-0.12-0.03c-0.09-0.06-0.13-0.19-0.06-0.28l0,0l2.43-3.68 L76.2,6.84c-0.02-0.03-0.03-0.07-0.03-0.12c0-0.12,0.09-0.21,0.21-0.21h1.61c0.13,0,0.24,0.06,0.3,0.17l1.41,2.36l1.41-2.36 c0.06-0.11,0.18-0.17,0.3-0.17h1.61c0.04,0,0.08,0.01,0.12,0.03c0.09,0.06,0.13,0.19,0.06,0.28l0,0l-2.38,3.64l2.43,3.67 c0.02,0.03,0.03,0.07,0.03,0.12C83.25,14.38,83.16,14.47,83.04,14.47L83.04,14.47L83.04,14.47z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M10.5,1.24c-5.11,0-9.25,4.15-9.25,9.25s4.15,9.25,9.25,9.25s9.25-4.15,9.25-9.25 C19.75,5.38,15.61,1.24,10.5,1.24z M14.89,12.77c-1.93,1.93-4.78,2.31-6.7,2.31c-0.7,0-1.41-0.05-2.1-0.16c0,0-1.02-5.64,2.14-8.81 c0.83-0.83,1.95-1.28,3.13-1.28c1.27,0,2.49,0.51,3.39,1.42C16.59,8.09,16.64,11,14.89,12.77z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M10.5-0.01C4.7-0.01,0,4.7,0,10.49s4.7,10.5,10.5,10.5S21,16.29,21,10.49C20.99,4.7,16.3-0.01,10.5-0.01z M10.5,19.74c-5.11,0-9.25-4.15-9.25-9.25s4.14-9.26,9.25-9.26s9.25,4.15,9.25,9.25C19.75,15.61,15.61,19.74,10.5,19.74z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M14.74,6.25C12.9,4.41,9.98,4.35,8.23,6.1c-3.16,3.17-2.14,8.81-2.14,8.81s5.64,1.02,8.81-2.14 C16.64,11,16.59,8.09,14.74,6.25z M12.47,10.34l-0.91,1.87l-0.9-1.87L8.8,9.43l1.86-0.9l0.9-1.87l0.91,1.87l1.86,0.9L12.47,10.34z"/%3E %3Cpolygon class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" points="14.33,9.43 12.47,10.34 11.56,12.21 10.66,10.34 8.8,9.43 10.66,8.53 11.56,6.66 12.47,8.53 "/%3E%3C/g%3E%3C/svg%3E\');'
}
};
/***/ }),
/***/ 89032:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
/**
* Convert plotly.js 'textposition' to mapbox-gl 'anchor' and 'offset'
* (with the help of the icon size).
*
* @param {string} textpostion : plotly.js textposition value
* @param {number} iconSize : plotly.js icon size (e.g. marker.size for traces)
*
* @return {object}
* - anchor
* - offset
*/
module.exports = function convertTextOpts(textposition, iconSize) {
var parts = textposition.split(' ');
var vPos = parts[0];
var hPos = parts[1];
// ballpack values
var factor = Lib.isArrayOrTypedArray(iconSize) ? Lib.mean(iconSize) : iconSize;
var xInc = 0.5 + factor / 100;
var yInc = 1.5 + factor / 100;
var anchorVals = ['', ''];
var offset = [0, 0];
switch (vPos) {
case 'top':
anchorVals[0] = 'top';
offset[1] = -yInc;
break;
case 'bottom':
anchorVals[0] = 'bottom';
offset[1] = yInc;
break;
}
switch (hPos) {
case 'left':
anchorVals[1] = 'right';
offset[0] = -xInc;
break;
case 'right':
anchorVals[1] = 'left';
offset[0] = xInc;
break;
}
// Mapbox text-anchor must be one of:
// center, left, right, top, bottom,
// top-left, top-right, bottom-left, bottom-right
var anchor;
if (anchorVals[0] && anchorVals[1]) anchor = anchorVals.join('-');else if (anchorVals[0]) anchor = anchorVals[0];else if (anchorVals[1]) anchor = anchorVals[1];else anchor = 'center';
return {
anchor: anchor,
offset: offset
};
};
/***/ }),
/***/ 33688:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var mapboxgl = __webpack_require__(3480);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var strScale = Lib.strScale;
var getSubplotCalcData = (__webpack_require__(84888)/* .getSubplotCalcData */ .KY);
var xmlnsNamespaces = __webpack_require__(9616);
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var svgTextUtils = __webpack_require__(72736);
var Mapbox = __webpack_require__(14440);
var MAPBOX = 'mapbox';
var constants = exports.constants = __webpack_require__(47552);
exports.name = MAPBOX;
exports.attr = 'subplot';
exports.idRoot = MAPBOX;
exports.idRegex = exports.attrRegex = Lib.counterRegex(MAPBOX);
exports.attributes = {
subplot: {
valType: 'subplotid',
dflt: 'mapbox',
editType: 'calc'
}
};
exports.layoutAttributes = __webpack_require__(5232);
exports.supplyLayoutDefaults = __webpack_require__(5976);
exports.plot = function plot(gd) {
var fullLayout = gd._fullLayout;
var calcData = gd.calcdata;
var mapboxIds = fullLayout._subplots[MAPBOX];
if (mapboxgl.version !== constants.requiredVersion) {
throw new Error(constants.wrongVersionErrorMsg);
}
var accessToken = findAccessToken(gd, mapboxIds);
mapboxgl.accessToken = accessToken;
for (var i = 0; i < mapboxIds.length; i++) {
var id = mapboxIds[i];
var subplotCalcData = getSubplotCalcData(calcData, MAPBOX, id);
var opts = fullLayout[id];
var mapbox = opts._subplot;
if (!mapbox) {
mapbox = new Mapbox(gd, id);
fullLayout[id]._subplot = mapbox;
}
if (!mapbox.viewInitial) {
mapbox.viewInitial = {
center: Lib.extendFlat({}, opts.center),
zoom: opts.zoom,
bearing: opts.bearing,
pitch: opts.pitch
};
}
mapbox.plot(subplotCalcData, fullLayout, gd._promises);
}
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldMapboxKeys = oldFullLayout._subplots[MAPBOX] || [];
for (var i = 0; i < oldMapboxKeys.length; i++) {
var oldMapboxKey = oldMapboxKeys[i];
if (!newFullLayout[oldMapboxKey] && !!oldFullLayout[oldMapboxKey]._subplot) {
oldFullLayout[oldMapboxKey]._subplot.destroy();
}
}
};
exports.toSVG = function (gd) {
var fullLayout = gd._fullLayout;
var subplotIds = fullLayout._subplots[MAPBOX];
var size = fullLayout._size;
for (var i = 0; i < subplotIds.length; i++) {
var opts = fullLayout[subplotIds[i]];
var domain = opts.domain;
var mapbox = opts._subplot;
var imageData = mapbox.toImage('png');
var image = fullLayout._glimages.append('svg:image');
image.attr({
xmlns: xmlnsNamespaces.svg,
'xlink:href': imageData,
x: size.l + size.w * domain.x[0],
y: size.t + size.h * (1 - domain.y[1]),
width: size.w * (domain.x[1] - domain.x[0]),
height: size.h * (domain.y[1] - domain.y[0]),
preserveAspectRatio: 'none'
});
var subplotDiv = d3.select(opts._subplot.div);
// Append logo if visible
var hidden = subplotDiv.select('.mapboxgl-ctrl-logo').node().offsetParent === null;
if (!hidden) {
var logo = fullLayout._glimages.append('g');
logo.attr('transform', strTranslate(size.l + size.w * domain.x[0] + 10, size.t + size.h * (1 - domain.y[0]) - 31));
logo.append('path').attr('d', constants.mapboxLogo.path0).style({
opacity: 0.9,
fill: '#ffffff',
'enable-background': 'new'
});
logo.append('path').attr('d', constants.mapboxLogo.path1).style('opacity', 0.35).style('enable-background', 'new');
logo.append('path').attr('d', constants.mapboxLogo.path2).style('opacity', 0.35).style('enable-background', 'new');
logo.append('polygon').attr('points', constants.mapboxLogo.polygon).style({
opacity: 0.9,
fill: '#ffffff',
'enable-background': 'new'
});
}
// Add attributions
var attributions = subplotDiv.select('.mapboxgl-ctrl-attrib').text().replace('Improve this map', '');
var attributionGroup = fullLayout._glimages.append('g');
var attributionText = attributionGroup.append('text');
attributionText.text(attributions).classed('static-attribution', true).attr({
'font-size': 12,
'font-family': 'Arial',
color: 'rgba(0, 0, 0, 0.75)',
'text-anchor': 'end',
'data-unformatted': attributions
});
var bBox = Drawing.bBox(attributionText.node());
// Break into multiple lines twice larger than domain
var maxWidth = size.w * (domain.x[1] - domain.x[0]);
if (bBox.width > maxWidth / 2) {
var multilineAttributions = attributions.split('|').join(' ');
attributionText.text(multilineAttributions).attr('data-unformatted', multilineAttributions).call(svgTextUtils.convertToTspans, gd);
bBox = Drawing.bBox(attributionText.node());
}
attributionText.attr('transform', strTranslate(-3, -bBox.height + 8));
// Draw white rectangle behind text
attributionGroup.insert('rect', '.static-attribution').attr({
x: -bBox.width - 6,
y: -bBox.height - 3,
width: bBox.width + 6,
height: bBox.height + 3,
fill: 'rgba(255, 255, 255, 0.75)'
});
// Scale down if larger than domain
var scaleRatio = 1;
if (bBox.width + 6 > maxWidth) scaleRatio = maxWidth / (bBox.width + 6);
var offset = [size.l + size.w * domain.x[1], size.t + size.h * (1 - domain.y[0])];
attributionGroup.attr('transform', strTranslate(offset[0], offset[1]) + strScale(scaleRatio));
}
};
// N.B. mapbox-gl only allows one accessToken to be set per page:
// https://github.com/mapbox/mapbox-gl-js/issues/6331
function findAccessToken(gd, mapboxIds) {
var fullLayout = gd._fullLayout;
var context = gd._context;
// special case for Mapbox Atlas users
if (context.mapboxAccessToken === '') return '';
var tokensUseful = [];
var tokensListed = [];
var hasOneSetMapboxStyle = false;
var wontWork = false;
// Take the first token we find in a mapbox subplot.
// These default to the context value but may be overridden.
for (var i = 0; i < mapboxIds.length; i++) {
var opts = fullLayout[mapboxIds[i]];
var token = opts.accesstoken;
if (isStyleRequireAccessToken(opts.style)) {
if (token) {
Lib.pushUnique(tokensUseful, token);
} else {
if (isStyleRequireAccessToken(opts._input.style)) {
Lib.error('Uses Mapbox map style, but did not set an access token.');
hasOneSetMapboxStyle = true;
}
wontWork = true;
}
}
if (token) {
Lib.pushUnique(tokensListed, token);
}
}
if (wontWork) {
var msg = hasOneSetMapboxStyle ? constants.noAccessTokenErrorMsg : constants.missingStyleErrorMsg;
Lib.error(msg);
throw new Error(msg);
}
if (tokensUseful.length) {
if (tokensUseful.length > 1) {
Lib.warn(constants.multipleTokensErrorMsg);
}
return tokensUseful[0];
} else {
if (tokensListed.length) {
Lib.log(['Listed mapbox access token(s)', tokensListed.join(','), 'but did not use a Mapbox map style, ignoring token(s).'].join(' '));
}
return '';
}
}
function isStyleRequireAccessToken(s) {
return typeof s === 'string' && (constants.styleValuesMapbox.indexOf(s) !== -1 || s.indexOf('mapbox://') === 0 || s.indexOf('stamen') === 0);
}
exports.updateFx = function (gd) {
var fullLayout = gd._fullLayout;
var subplotIds = fullLayout._subplots[MAPBOX];
for (var i = 0; i < subplotIds.length; i++) {
var subplotObj = fullLayout[subplotIds[i]]._subplot;
subplotObj.updateFx(fullLayout);
}
};
/***/ }),
/***/ 22360:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var sanitizeHTML = (__webpack_require__(72736).sanitizeHTML);
var convertTextOpts = __webpack_require__(89032);
var constants = __webpack_require__(47552);
function MapboxLayer(subplot, index) {
this.subplot = subplot;
this.uid = subplot.uid + '-' + index;
this.index = index;
this.idSource = 'source-' + this.uid;
this.idLayer = constants.layoutLayerPrefix + this.uid;
// some state variable to check if a remove/add step is needed
this.sourceType = null;
this.source = null;
this.layerType = null;
this.below = null;
// is layer currently visible
this.visible = false;
}
var proto = MapboxLayer.prototype;
proto.update = function update(opts) {
if (!this.visible) {
// IMPORTANT: must create source before layer to not cause errors
this.updateSource(opts);
this.updateLayer(opts);
} else if (this.needsNewImage(opts)) {
this.updateImage(opts);
} else if (this.needsNewSource(opts)) {
// IMPORTANT: must delete layer before source to not cause errors
this.removeLayer();
this.updateSource(opts);
this.updateLayer(opts);
} else if (this.needsNewLayer(opts)) {
this.updateLayer(opts);
} else {
this.updateStyle(opts);
}
this.visible = isVisible(opts);
};
proto.needsNewImage = function (opts) {
var map = this.subplot.map;
return map.getSource(this.idSource) && this.sourceType === 'image' && opts.sourcetype === 'image' && (this.source !== opts.source || JSON.stringify(this.coordinates) !== JSON.stringify(opts.coordinates));
};
proto.needsNewSource = function (opts) {
// for some reason changing layer to 'fill' or 'symbol'
// w/o changing the source throws an exception in mapbox-gl 0.18 ;
// stay safe and make new source on type changes
return this.sourceType !== opts.sourcetype || JSON.stringify(this.source) !== JSON.stringify(opts.source) || this.layerType !== opts.type;
};
proto.needsNewLayer = function (opts) {
return this.layerType !== opts.type || this.below !== this.subplot.belowLookup['layout-' + this.index];
};
proto.lookupBelow = function () {
return this.subplot.belowLookup['layout-' + this.index];
};
proto.updateImage = function (opts) {
var map = this.subplot.map;
map.getSource(this.idSource).updateImage({
url: opts.source,
coordinates: opts.coordinates
});
// Since the `updateImage` control flow doesn't call updateLayer,
// We need to take care of moving the image layer to match the location
// where updateLayer would have placed it.
var _below = this.findFollowingMapboxLayerId(this.lookupBelow());
if (_below !== null) {
this.subplot.map.moveLayer(this.idLayer, _below);
}
};
proto.updateSource = function (opts) {
var map = this.subplot.map;
if (map.getSource(this.idSource)) map.removeSource(this.idSource);
this.sourceType = opts.sourcetype;
this.source = opts.source;
if (!isVisible(opts)) return;
var sourceOpts = convertSourceOpts(opts);
map.addSource(this.idSource, sourceOpts);
};
proto.findFollowingMapboxLayerId = function (below) {
if (below === 'traces') {
var mapLayers = this.subplot.getMapLayers();
// find id of first plotly trace layer
for (var i = 0; i < mapLayers.length; i++) {
var layerId = mapLayers[i].id;
if (typeof layerId === 'string' && layerId.indexOf(constants.traceLayerPrefix) === 0) {
below = layerId;
break;
}
}
}
return below;
};
proto.updateLayer = function (opts) {
var subplot = this.subplot;
var convertedOpts = convertOpts(opts);
var below = this.lookupBelow();
var _below = this.findFollowingMapboxLayerId(below);
this.removeLayer();
if (isVisible(opts)) {
subplot.addLayer({
id: this.idLayer,
source: this.idSource,
'source-layer': opts.sourcelayer || '',
type: opts.type,
minzoom: opts.minzoom,
maxzoom: opts.maxzoom,
layout: convertedOpts.layout,
paint: convertedOpts.paint
}, _below);
}
this.layerType = opts.type;
this.below = below;
};
proto.updateStyle = function (opts) {
if (isVisible(opts)) {
var convertedOpts = convertOpts(opts);
this.subplot.setOptions(this.idLayer, 'setLayoutProperty', convertedOpts.layout);
this.subplot.setOptions(this.idLayer, 'setPaintProperty', convertedOpts.paint);
}
};
proto.removeLayer = function () {
var map = this.subplot.map;
if (map.getLayer(this.idLayer)) {
map.removeLayer(this.idLayer);
}
};
proto.dispose = function () {
var map = this.subplot.map;
if (map.getLayer(this.idLayer)) map.removeLayer(this.idLayer);
if (map.getSource(this.idSource)) map.removeSource(this.idSource);
};
function isVisible(opts) {
if (!opts.visible) return false;
var source = opts.source;
if (Array.isArray(source) && source.length > 0) {
for (var i = 0; i < source.length; i++) {
if (typeof source[i] !== 'string' || source[i].length === 0) {
return false;
}
}
return true;
}
return Lib.isPlainObject(source) || typeof source === 'string' && source.length > 0;
}
function convertOpts(opts) {
var layout = {};
var paint = {};
switch (opts.type) {
case 'circle':
Lib.extendFlat(paint, {
'circle-radius': opts.circle.radius,
'circle-color': opts.color,
'circle-opacity': opts.opacity
});
break;
case 'line':
Lib.extendFlat(paint, {
'line-width': opts.line.width,
'line-color': opts.color,
'line-opacity': opts.opacity,
'line-dasharray': opts.line.dash
});
break;
case 'fill':
Lib.extendFlat(paint, {
'fill-color': opts.color,
'fill-outline-color': opts.fill.outlinecolor,
'fill-opacity': opts.opacity
// no way to pass specify outline width at the moment
});
break;
case 'symbol':
var symbol = opts.symbol;
var textOpts = convertTextOpts(symbol.textposition, symbol.iconsize);
Lib.extendFlat(layout, {
'icon-image': symbol.icon + '-15',
'icon-size': symbol.iconsize / 10,
'text-field': symbol.text,
'text-size': symbol.textfont.size,
'text-anchor': textOpts.anchor,
'text-offset': textOpts.offset,
'symbol-placement': symbol.placement
// TODO font family
// 'text-font': symbol.textfont.family.split(', '),
});
Lib.extendFlat(paint, {
'icon-color': opts.color,
'text-color': symbol.textfont.color,
'text-opacity': opts.opacity
});
break;
case 'raster':
Lib.extendFlat(paint, {
'raster-fade-duration': 0,
'raster-opacity': opts.opacity
});
break;
}
return {
layout: layout,
paint: paint
};
}
function convertSourceOpts(opts) {
var sourceType = opts.sourcetype;
var source = opts.source;
var sourceOpts = {
type: sourceType
};
var field;
if (sourceType === 'geojson') {
field = 'data';
} else if (sourceType === 'vector') {
field = typeof source === 'string' ? 'url' : 'tiles';
} else if (sourceType === 'raster') {
field = 'tiles';
sourceOpts.tileSize = 256;
} else if (sourceType === 'image') {
field = 'url';
sourceOpts.coordinates = opts.coordinates;
}
sourceOpts[field] = source;
if (opts.sourceattribution) {
sourceOpts.attribution = sanitizeHTML(opts.sourceattribution);
}
return sourceOpts;
}
module.exports = function createMapboxLayer(subplot, index, opts) {
var mapboxLayer = new MapboxLayer(subplot, index);
mapboxLayer.update(opts);
return mapboxLayer;
};
/***/ }),
/***/ 5232:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var defaultLine = (__webpack_require__(76308).defaultLine);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var fontAttrs = __webpack_require__(25376);
var textposition = (__webpack_require__(52904).textposition);
var overrideAll = (__webpack_require__(67824).overrideAll);
var templatedArray = (__webpack_require__(31780).templatedArray);
var constants = __webpack_require__(47552);
var fontAttr = fontAttrs({
noFontVariant: true,
noFontShadow: true,
noFontLineposition: true,
noFontTextcase: true
});
fontAttr.family.dflt = 'Open Sans Regular, Arial Unicode MS Regular';
var attrs = module.exports = overrideAll({
_arrayAttrRegexps: [Lib.counterRegex('mapbox', '.layers', true)],
domain: domainAttrs({
name: 'mapbox'
}),
accesstoken: {
valType: 'string',
noBlank: true,
strict: true
},
style: {
valType: 'any',
values: constants.styleValuesMapbox.concat(constants.styleValuesNonMapbox),
dflt: constants.styleValueDflt
},
center: {
lon: {
valType: 'number',
dflt: 0
},
lat: {
valType: 'number',
dflt: 0
}
},
zoom: {
valType: 'number',
dflt: 1
},
bearing: {
valType: 'number',
dflt: 0
},
pitch: {
valType: 'number',
dflt: 0
},
bounds: {
west: {
valType: 'number'
},
east: {
valType: 'number'
},
south: {
valType: 'number'
},
north: {
valType: 'number'
}
},
layers: templatedArray('layer', {
visible: {
valType: 'boolean',
dflt: true
},
sourcetype: {
valType: 'enumerated',
values: ['geojson', 'vector', 'raster', 'image'],
dflt: 'geojson'
},
source: {
valType: 'any'
},
sourcelayer: {
valType: 'string',
dflt: ''
},
sourceattribution: {
valType: 'string'
},
type: {
valType: 'enumerated',
values: ['circle', 'line', 'fill', 'symbol', 'raster'],
dflt: 'circle'
},
coordinates: {
valType: 'any'
},
// attributes shared between all types
below: {
valType: 'string'
},
color: {
valType: 'color',
dflt: defaultLine
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1
},
minzoom: {
valType: 'number',
min: 0,
max: 24,
dflt: 0
},
maxzoom: {
valType: 'number',
min: 0,
max: 24,
dflt: 24
},
// type-specific style attributes
circle: {
radius: {
valType: 'number',
dflt: 15
}
},
line: {
width: {
valType: 'number',
dflt: 2
},
dash: {
valType: 'data_array'
}
},
fill: {
outlinecolor: {
valType: 'color',
dflt: defaultLine
}
},
symbol: {
icon: {
valType: 'string',
dflt: 'marker'
},
iconsize: {
valType: 'number',
dflt: 10
},
text: {
valType: 'string',
dflt: ''
},
placement: {
valType: 'enumerated',
values: ['point', 'line', 'line-center'],
dflt: 'point'
},
textfont: fontAttr,
textposition: Lib.extendFlat({}, textposition, {
arrayOk: false
})
}
})
}, 'plot', 'from-root');
// set uirevision outside of overrideAll so it can be `editType: 'none'`
attrs.uirevision = {
valType: 'any',
editType: 'none'
};
/***/ }),
/***/ 5976:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleSubplotDefaults = __webpack_require__(168);
var handleArrayContainerDefaults = __webpack_require__(51272);
var layoutAttributes = __webpack_require__(5232);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
handleSubplotDefaults(layoutIn, layoutOut, fullData, {
type: 'mapbox',
attributes: layoutAttributes,
handleDefaults: handleDefaults,
partition: 'y',
accessToken: layoutOut._mapboxAccessToken
});
};
function handleDefaults(containerIn, containerOut, coerce, opts) {
coerce('accesstoken', opts.accessToken);
coerce('style');
coerce('center.lon');
coerce('center.lat');
coerce('zoom');
coerce('bearing');
coerce('pitch');
var west = coerce('bounds.west');
var east = coerce('bounds.east');
var south = coerce('bounds.south');
var north = coerce('bounds.north');
if (west === undefined || east === undefined || south === undefined || north === undefined) {
delete containerOut.bounds;
}
handleArrayContainerDefaults(containerIn, containerOut, {
name: 'layers',
handleItemDefaults: handleLayerDefaults
});
// copy ref to input container to update 'center' and 'zoom' on map move
containerOut._input = containerIn;
}
function handleLayerDefaults(layerIn, layerOut) {
function coerce(attr, dflt) {
return Lib.coerce(layerIn, layerOut, layoutAttributes.layers, attr, dflt);
}
var visible = coerce('visible');
if (visible) {
var sourceType = coerce('sourcetype');
var mustBeRasterLayer = sourceType === 'raster' || sourceType === 'image';
coerce('source');
coerce('sourceattribution');
if (sourceType === 'vector') {
coerce('sourcelayer');
}
if (sourceType === 'image') {
coerce('coordinates');
}
var typeDflt;
if (mustBeRasterLayer) typeDflt = 'raster';
var type = coerce('type', typeDflt);
if (mustBeRasterLayer && type !== 'raster') {
type = layerOut.type = 'raster';
Lib.log('Source types *raster* and *image* must drawn *raster* layer type.');
}
coerce('below');
coerce('color');
coerce('opacity');
coerce('minzoom');
coerce('maxzoom');
if (type === 'circle') {
coerce('circle.radius');
}
if (type === 'line') {
coerce('line.width');
coerce('line.dash');
}
if (type === 'fill') {
coerce('fill.outlinecolor');
}
if (type === 'symbol') {
coerce('symbol.icon');
coerce('symbol.iconsize');
coerce('symbol.text');
Lib.coerceFont(coerce, 'symbol.textfont', undefined, {
noFontVariant: true,
noFontShadow: true,
noFontLineposition: true,
noFontTextcase: true
});
coerce('symbol.textposition');
coerce('symbol.placement');
}
}
}
/***/ }),
/***/ 14440:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var mapboxgl = __webpack_require__(3480);
var Lib = __webpack_require__(3400);
var geoUtils = __webpack_require__(27144);
var Registry = __webpack_require__(24040);
var Axes = __webpack_require__(54460);
var dragElement = __webpack_require__(86476);
var Fx = __webpack_require__(93024);
var dragHelpers = __webpack_require__(72760);
var drawMode = dragHelpers.drawMode;
var selectMode = dragHelpers.selectMode;
var prepSelect = (__webpack_require__(22676).prepSelect);
var clearOutline = (__webpack_require__(22676).clearOutline);
var clearSelectionsCache = (__webpack_require__(22676).clearSelectionsCache);
var selectOnClick = (__webpack_require__(22676).selectOnClick);
var constants = __webpack_require__(47552);
var createMapboxLayer = __webpack_require__(22360);
function Mapbox(gd, id) {
this.id = id;
this.gd = gd;
var fullLayout = gd._fullLayout;
var context = gd._context;
this.container = fullLayout._glcontainer.node();
this.isStatic = context.staticPlot;
// unique id for this Mapbox instance
this.uid = fullLayout._uid + '-' + this.id;
// create framework on instantiation for a smoother first plot call
this.div = null;
this.xaxis = null;
this.yaxis = null;
this.createFramework(fullLayout);
// state variables used to infer how and what to update
this.map = null;
this.accessToken = null;
this.styleObj = null;
this.traceHash = {};
this.layerList = [];
this.belowLookup = {};
this.dragging = false;
this.wheeling = false;
}
var proto = Mapbox.prototype;
proto.plot = function (calcData, fullLayout, promises) {
var self = this;
var opts = fullLayout[self.id];
// remove map and create a new map if access token has change
if (self.map && opts.accesstoken !== self.accessToken) {
self.map.remove();
self.map = null;
self.styleObj = null;
self.traceHash = {};
self.layerList = [];
}
var promise;
if (!self.map) {
promise = new Promise(function (resolve, reject) {
self.createMap(calcData, fullLayout, resolve, reject);
});
} else {
promise = new Promise(function (resolve, reject) {
self.updateMap(calcData, fullLayout, resolve, reject);
});
}
promises.push(promise);
};
proto.createMap = function (calcData, fullLayout, resolve, reject) {
var self = this;
var opts = fullLayout[self.id];
// store style id and URL or object
var styleObj = self.styleObj = getStyleObj(opts.style, fullLayout);
// store access token associated with this map
self.accessToken = opts.accesstoken;
var bounds = opts.bounds;
var maxBounds = bounds ? [[bounds.west, bounds.south], [bounds.east, bounds.north]] : null;
// create the map!
var map = self.map = new mapboxgl.Map({
container: self.div,
style: styleObj.style,
center: convertCenter(opts.center),
zoom: opts.zoom,
bearing: opts.bearing,
pitch: opts.pitch,
maxBounds: maxBounds,
interactive: !self.isStatic,
preserveDrawingBuffer: self.isStatic,
doubleClickZoom: false,
boxZoom: false,
attributionControl: false
}).addControl(new mapboxgl.AttributionControl({
compact: true
}));
// make sure canvas does not inherit left and top css
map._canvas.style.left = '0px';
map._canvas.style.top = '0px';
self.rejectOnError(reject);
if (!self.isStatic) {
self.initFx(calcData, fullLayout);
}
var promises = [];
promises.push(new Promise(function (resolve) {
map.once('load', resolve);
}));
promises = promises.concat(geoUtils.fetchTraceGeoData(calcData));
Promise.all(promises).then(function () {
self.fillBelowLookup(calcData, fullLayout);
self.updateData(calcData);
self.updateLayout(fullLayout);
self.resolveOnRender(resolve);
}).catch(reject);
};
proto.updateMap = function (calcData, fullLayout, resolve, reject) {
var self = this;
var map = self.map;
var opts = fullLayout[this.id];
self.rejectOnError(reject);
var promises = [];
var styleObj = getStyleObj(opts.style, fullLayout);
if (JSON.stringify(self.styleObj) !== JSON.stringify(styleObj)) {
self.styleObj = styleObj;
map.setStyle(styleObj.style);
// need to rebuild trace layers on reload
// to avoid 'lost event' errors
self.traceHash = {};
promises.push(new Promise(function (resolve) {
map.once('styledata', resolve);
}));
}
promises = promises.concat(geoUtils.fetchTraceGeoData(calcData));
Promise.all(promises).then(function () {
self.fillBelowLookup(calcData, fullLayout);
self.updateData(calcData);
self.updateLayout(fullLayout);
self.resolveOnRender(resolve);
}).catch(reject);
};
proto.fillBelowLookup = function (calcData, fullLayout) {
var opts = fullLayout[this.id];
var layers = opts.layers;
var i, val;
var belowLookup = this.belowLookup = {};
var hasTraceAtTop = false;
for (i = 0; i < calcData.length; i++) {
var trace = calcData[i][0].trace;
var _module = trace._module;
if (typeof trace.below === 'string') {
val = trace.below;
} else if (_module.getBelow) {
// 'smart' default that depend the map's base layers
val = _module.getBelow(trace, this);
}
if (val === '') {
hasTraceAtTop = true;
}
belowLookup['trace-' + trace.uid] = val || '';
}
for (i = 0; i < layers.length; i++) {
var item = layers[i];
if (typeof item.below === 'string') {
val = item.below;
} else if (hasTraceAtTop) {
// if one or more trace(s) set `below:''` and
// layers[i].below is unset,
// place layer below traces
val = 'traces';
} else {
val = '';
}
belowLookup['layout-' + i] = val;
}
// N.B. If multiple layers have the 'below' value,
// we must clear the stashed 'below' field in order
// to make `traceHash[k].update()` and `layerList[i].update()`
// remove/add the all those layers to have preserve
// the correct layer ordering
var val2list = {};
var k, id;
for (k in belowLookup) {
val = belowLookup[k];
if (val2list[val]) {
val2list[val].push(k);
} else {
val2list[val] = [k];
}
}
for (val in val2list) {
var list = val2list[val];
if (list.length > 1) {
for (i = 0; i < list.length; i++) {
k = list[i];
if (k.indexOf('trace-') === 0) {
id = k.split('trace-')[1];
if (this.traceHash[id]) {
this.traceHash[id].below = null;
}
} else if (k.indexOf('layout-') === 0) {
id = k.split('layout-')[1];
if (this.layerList[id]) {
this.layerList[id].below = null;
}
}
}
}
}
};
var traceType2orderIndex = {
choroplethmapbox: 0,
densitymapbox: 1,
scattermapbox: 2
};
proto.updateData = function (calcData) {
var traceHash = this.traceHash;
var traceObj, trace, i, j;
// Need to sort here by trace type here,
// in case traces with different `type` have the same
// below value, but sorting we ensure that
// e.g. choroplethmapbox traces will be below scattermapbox traces
var calcDataSorted = calcData.slice().sort(function (a, b) {
return traceType2orderIndex[a[0].trace.type] - traceType2orderIndex[b[0].trace.type];
});
// update or create trace objects
for (i = 0; i < calcDataSorted.length; i++) {
var calcTrace = calcDataSorted[i];
trace = calcTrace[0].trace;
traceObj = traceHash[trace.uid];
var didUpdate = false;
if (traceObj) {
if (traceObj.type === trace.type) {
traceObj.update(calcTrace);
didUpdate = true;
} else {
traceObj.dispose();
}
}
if (!didUpdate && trace._module) {
traceHash[trace.uid] = trace._module.plot(this, calcTrace);
}
}
// remove empty trace objects
var ids = Object.keys(traceHash);
idLoop: for (i = 0; i < ids.length; i++) {
var id = ids[i];
for (j = 0; j < calcData.length; j++) {
trace = calcData[j][0].trace;
if (id === trace.uid) continue idLoop;
}
traceObj = traceHash[id];
traceObj.dispose();
delete traceHash[id];
}
};
proto.updateLayout = function (fullLayout) {
var map = this.map;
var opts = fullLayout[this.id];
if (!this.dragging && !this.wheeling) {
map.setCenter(convertCenter(opts.center));
map.setZoom(opts.zoom);
map.setBearing(opts.bearing);
map.setPitch(opts.pitch);
}
this.updateLayers(fullLayout);
this.updateFramework(fullLayout);
this.updateFx(fullLayout);
this.map.resize();
if (this.gd._context._scrollZoom.mapbox) {
map.scrollZoom.enable();
} else {
map.scrollZoom.disable();
}
};
proto.resolveOnRender = function (resolve) {
var map = this.map;
map.on('render', function onRender() {
if (map.loaded()) {
map.off('render', onRender);
// resolve at end of render loop
//
// Need a 10ms delay (0ms should suffice to skip a thread in the
// render loop) to workaround mapbox-gl bug introduced in v1.3.0
setTimeout(resolve, 10);
}
});
};
proto.rejectOnError = function (reject) {
var map = this.map;
function handler() {
reject(new Error(constants.mapOnErrorMsg));
}
map.once('error', handler);
map.once('style.error', handler);
map.once('source.error', handler);
map.once('tile.error', handler);
map.once('layer.error', handler);
};
proto.createFramework = function (fullLayout) {
var self = this;
var div = self.div = document.createElement('div');
div.id = self.uid;
div.style.position = 'absolute';
self.container.appendChild(div);
// create mock x/y axes for hover routine
self.xaxis = {
_id: 'x',
c2p: function (v) {
return self.project(v).x;
}
};
self.yaxis = {
_id: 'y',
c2p: function (v) {
return self.project(v).y;
}
};
self.updateFramework(fullLayout);
// mock axis for hover formatting
self.mockAxis = {
type: 'linear',
showexponent: 'all',
exponentformat: 'B'
};
Axes.setConvert(self.mockAxis, fullLayout);
};
proto.initFx = function (calcData, fullLayout) {
var self = this;
var gd = self.gd;
var map = self.map;
// keep track of pan / zoom in user layout and emit relayout event
map.on('moveend', function (evt) {
if (!self.map) return;
var fullLayoutNow = gd._fullLayout;
// 'moveend' gets triggered by map.setCenter, map.setZoom,
// map.setBearing and map.setPitch.
//
// Here, we make sure that state updates amd 'plotly_relayout'
// are triggered only when the 'moveend' originates from a
// mouse target (filtering out API calls) to not
// duplicate 'plotly_relayout' events.
if (evt.originalEvent || self.wheeling) {
var optsNow = fullLayoutNow[self.id];
Registry.call('_storeDirectGUIEdit', gd.layout, fullLayoutNow._preGUI, self.getViewEdits(optsNow));
var viewNow = self.getView();
optsNow._input.center = optsNow.center = viewNow.center;
optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
optsNow._input.pitch = optsNow.pitch = viewNow.pitch;
gd.emit('plotly_relayout', self.getViewEditsWithDerived(viewNow));
}
if (evt.originalEvent && evt.originalEvent.type === 'mouseup') {
self.dragging = false;
} else if (self.wheeling) {
self.wheeling = false;
}
if (fullLayoutNow._rehover) {
fullLayoutNow._rehover();
}
});
map.on('wheel', function () {
self.wheeling = true;
});
map.on('mousemove', function (evt) {
var bb = self.div.getBoundingClientRect();
var xy = [evt.originalEvent.offsetX, evt.originalEvent.offsetY];
evt.target.getBoundingClientRect = function () {
return bb;
};
self.xaxis.p2c = function () {
return map.unproject(xy).lng;
};
self.yaxis.p2c = function () {
return map.unproject(xy).lat;
};
gd._fullLayout._rehover = function () {
if (gd._fullLayout._hoversubplot === self.id && gd._fullLayout[self.id]) {
Fx.hover(gd, evt, self.id);
}
};
Fx.hover(gd, evt, self.id);
gd._fullLayout._hoversubplot = self.id;
});
function unhover() {
Fx.loneUnhover(fullLayout._hoverlayer);
}
map.on('dragstart', function () {
self.dragging = true;
unhover();
});
map.on('zoomstart', unhover);
map.on('mouseout', function () {
gd._fullLayout._hoversubplot = null;
});
function emitUpdate() {
var viewNow = self.getView();
gd.emit('plotly_relayouting', self.getViewEditsWithDerived(viewNow));
}
map.on('drag', emitUpdate);
map.on('zoom', emitUpdate);
map.on('dblclick', function () {
var optsNow = gd._fullLayout[self.id];
Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, self.getViewEdits(optsNow));
var viewInitial = self.viewInitial;
map.setCenter(convertCenter(viewInitial.center));
map.setZoom(viewInitial.zoom);
map.setBearing(viewInitial.bearing);
map.setPitch(viewInitial.pitch);
var viewNow = self.getView();
optsNow._input.center = optsNow.center = viewNow.center;
optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
optsNow._input.pitch = optsNow.pitch = viewNow.pitch;
gd.emit('plotly_doubleclick', null);
gd.emit('plotly_relayout', self.getViewEditsWithDerived(viewNow));
});
// define event handlers on map creation, to keep one ref per map,
// so that map.on / map.off in updateFx works as expected
self.clearOutline = function () {
clearSelectionsCache(self.dragOptions);
clearOutline(self.dragOptions.gd);
};
/**
* Returns a click handler function that is supposed
* to handle clicks in pan mode.
*/
self.onClickInPanFn = function (dragOptions) {
return function (evt) {
var clickMode = gd._fullLayout.clickmode;
if (clickMode.indexOf('select') > -1) {
selectOnClick(evt.originalEvent, gd, [self.xaxis], [self.yaxis], self.id, dragOptions);
}
if (clickMode.indexOf('event') > -1) {
// TODO: this does not support right-click. If we want to support it, we
// would likely need to change mapbox 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
// pie would use this too.
Fx.click(gd, evt.originalEvent);
}
};
};
};
proto.updateFx = function (fullLayout) {
var self = this;
var map = self.map;
var gd = self.gd;
if (self.isStatic) return;
function invert(pxpy) {
var obj = self.map.unproject(pxpy);
return [obj.lng, obj.lat];
}
var dragMode = fullLayout.dragmode;
var fillRangeItems;
fillRangeItems = function (eventData, poly) {
if (poly.isRect) {
var ranges = eventData.range = {};
ranges[self.id] = [invert([poly.xmin, poly.ymin]), invert([poly.xmax, poly.ymax])];
} else {
var dataPts = eventData.lassoPoints = {};
dataPts[self.id] = poly.map(invert);
}
};
// Note: dragOptions is needed to be declared for all dragmodes because
// it's the object that holds persistent selection state.
// Merge old dragOptions with new to keep possibly initialized
// persistent selection state.
var oldDragOptions = self.dragOptions;
self.dragOptions = Lib.extendDeep(oldDragOptions || {}, {
dragmode: fullLayout.dragmode,
element: self.div,
gd: gd,
plotinfo: {
id: self.id,
domain: fullLayout[self.id].domain,
xaxis: self.xaxis,
yaxis: self.yaxis,
fillRangeItems: fillRangeItems
},
xaxes: [self.xaxis],
yaxes: [self.yaxis],
subplot: self.id
});
// Unregister the old handler before potentially registering
// a new one. Otherwise multiple click handlers might
// be registered resulting in unwanted behavior.
map.off('click', self.onClickInPanHandler);
if (selectMode(dragMode) || drawMode(dragMode)) {
map.dragPan.disable();
map.on('zoomstart', self.clearOutline);
self.dragOptions.prepFn = function (e, startX, startY) {
prepSelect(e, startX, startY, self.dragOptions, dragMode);
};
dragElement.init(self.dragOptions);
} else {
map.dragPan.enable();
map.off('zoomstart', self.clearOutline);
self.div.onmousedown = null;
self.div.ontouchstart = null;
self.div.removeEventListener('touchstart', self.div._ontouchstart);
// TODO: this does not support right-click. If we want to support it, we
// would likely need to change mapbox 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
// pie would use this too.
self.onClickInPanHandler = self.onClickInPanFn(self.dragOptions);
map.on('click', self.onClickInPanHandler);
}
};
proto.updateFramework = function (fullLayout) {
var domain = fullLayout[this.id].domain;
var size = fullLayout._size;
var style = this.div.style;
style.width = size.w * (domain.x[1] - domain.x[0]) + 'px';
style.height = size.h * (domain.y[1] - domain.y[0]) + 'px';
style.left = size.l + domain.x[0] * size.w + 'px';
style.top = size.t + (1 - domain.y[1]) * size.h + 'px';
this.xaxis._offset = size.l + domain.x[0] * size.w;
this.xaxis._length = size.w * (domain.x[1] - domain.x[0]);
this.yaxis._offset = size.t + (1 - domain.y[1]) * size.h;
this.yaxis._length = size.h * (domain.y[1] - domain.y[0]);
};
proto.updateLayers = function (fullLayout) {
var opts = fullLayout[this.id];
var layers = opts.layers;
var layerList = this.layerList;
var i;
// if the layer arrays don't match,
// don't try to be smart,
// delete them all, and start all over.
if (layers.length !== layerList.length) {
for (i = 0; i < layerList.length; i++) {
layerList[i].dispose();
}
layerList = this.layerList = [];
for (i = 0; i < layers.length; i++) {
layerList.push(createMapboxLayer(this, i, layers[i]));
}
} else {
for (i = 0; i < layers.length; i++) {
layerList[i].update(layers[i]);
}
}
};
proto.destroy = function () {
if (this.map) {
this.map.remove();
this.map = null;
this.container.removeChild(this.div);
}
};
proto.toImage = function () {
this.map.stop();
return this.map.getCanvas().toDataURL();
};
// convenience wrapper to create set multiple layer
// 'layout' or 'paint options at once.
proto.setOptions = function (id, methodName, opts) {
for (var k in opts) {
this.map[methodName](id, k, opts[k]);
}
};
proto.getMapLayers = function () {
return this.map.getStyle().layers;
};
// convenience wrapper that first check in 'below' references
// a layer that exist and then add the layer to the map,
proto.addLayer = function (opts, below) {
var map = this.map;
if (typeof below === 'string') {
if (below === '') {
map.addLayer(opts, below);
return;
}
var mapLayers = this.getMapLayers();
for (var i = 0; i < mapLayers.length; i++) {
if (below === mapLayers[i].id) {
map.addLayer(opts, below);
return;
}
}
Lib.warn(['Trying to add layer with *below* value', below, 'referencing a layer that does not exist', 'or that does not yet exist.'].join(' '));
}
map.addLayer(opts);
};
// convenience method to project a [lon, lat] array to pixel coords
proto.project = function (v) {
return this.map.project(new mapboxgl.LngLat(v[0], v[1]));
};
// get map's current view values in plotly.js notation
proto.getView = function () {
var map = this.map;
var mapCenter = map.getCenter();
var lon = mapCenter.lng;
var lat = mapCenter.lat;
var center = {
lon: lon,
lat: lat
};
var canvas = map.getCanvas();
var w = parseInt(canvas.style.width);
var h = parseInt(canvas.style.height);
return {
center: center,
zoom: map.getZoom(),
bearing: map.getBearing(),
pitch: map.getPitch(),
_derived: {
coordinates: [map.unproject([0, 0]).toArray(), map.unproject([w, 0]).toArray(), map.unproject([w, h]).toArray(), map.unproject([0, h]).toArray()]
}
};
};
proto.getViewEdits = function (cont) {
var id = this.id;
var keys = ['center', 'zoom', 'bearing', 'pitch'];
var obj = {};
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
obj[id + '.' + k] = cont[k];
}
return obj;
};
proto.getViewEditsWithDerived = function (cont) {
var id = this.id;
var obj = this.getViewEdits(cont);
obj[id + '._derived'] = cont._derived;
return obj;
};
function getStyleObj(val, fullLayout) {
var styleObj = {};
if (Lib.isPlainObject(val)) {
styleObj.id = val.id;
styleObj.style = val;
} else if (typeof val === 'string') {
styleObj.id = val;
if (constants.styleValuesMapbox.indexOf(val) !== -1) {
styleObj.style = convertStyleVal(val);
} else if (constants.stylesNonMapbox[val]) {
styleObj.style = constants.stylesNonMapbox[val];
var spec = styleObj.style.sources['plotly-' + val];
var tiles = spec ? spec.tiles : undefined;
if (tiles && tiles[0] && tiles[0].slice(-9) === '?api_key=') {
// provide api_key for stamen styles
tiles[0] += fullLayout._mapboxAccessToken;
}
} else {
styleObj.style = val;
}
} else {
styleObj.id = constants.styleValueDflt;
styleObj.style = convertStyleVal(constants.styleValueDflt);
}
styleObj.transition = {
duration: 0,
delay: 0
};
return styleObj;
}
// if style is part of the 'official' mapbox values, add URL prefix and suffix
function convertStyleVal(val) {
return constants.styleUrlPrefix + val + '-' + constants.styleUrlSuffix;
}
function convertCenter(center) {
return [center.lon, center.lat];
}
module.exports = Mapbox;
/***/ }),
/***/ 66741:
/***/ (function(module) {
"use strict";
/**
* Creates a set of padding attributes.
*
* @param {object} opts
* @param {string} editType:
* the editType for all pieces of this padding definition
*
* @return {object} attributes object containing {t, r, b, l} as specified
*/
module.exports = function (opts) {
var editType = opts.editType;
return {
t: {
valType: 'number',
dflt: 0,
editType: editType
},
r: {
valType: 'number',
dflt: 0,
editType: editType
},
b: {
valType: 'number',
dflt: 0,
editType: editType
},
l: {
valType: 'number',
dflt: 0,
editType: editType
},
editType: editType
};
};
/***/ }),
/***/ 7316:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var timeFormatLocale = (__webpack_require__(94336)/* .timeFormatLocale */ .m_);
var formatLocale = (__webpack_require__(57624)/* .formatLocale */ .SO);
var isNumeric = __webpack_require__(38248);
var b64encode = __webpack_require__(83160);
var Registry = __webpack_require__(24040);
var PlotSchema = __webpack_require__(73060);
var Template = __webpack_require__(31780);
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var BADNUM = (__webpack_require__(39032).BADNUM);
var axisIDs = __webpack_require__(79811);
var clearOutline = (__webpack_require__(1936).clearOutline);
var scatterAttrs = __webpack_require__(55308);
var animationAttrs = __webpack_require__(85656);
var frameAttrs = __webpack_require__(16672);
var getModuleCalcData = (__webpack_require__(84888)/* .getModuleCalcData */ ._M);
var relinkPrivateKeys = Lib.relinkPrivateKeys;
var _ = Lib._;
var plots = module.exports = {};
// Expose registry methods on Plots for backward-compatibility
Lib.extendFlat(plots, Registry);
plots.attributes = __webpack_require__(45464);
plots.attributes.type.values = plots.allTypes;
plots.fontAttrs = __webpack_require__(25376);
plots.layoutAttributes = __webpack_require__(64859);
var transformsRegistry = plots.transformsRegistry;
var commandModule = __webpack_require__(62460);
plots.executeAPICommand = commandModule.executeAPICommand;
plots.computeAPICommandBindings = commandModule.computeAPICommandBindings;
plots.manageCommandObserver = commandModule.manageCommandObserver;
plots.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings;
// in some cases the browser doesn't seem to know how big
// the text is at first, so it needs to draw it,
// then wait a little, then draw it again
plots.redrawText = function (gd) {
gd = Lib.getGraphDiv(gd);
return new Promise(function (resolve) {
setTimeout(function () {
if (!gd._fullLayout) return;
Registry.getComponentMethod('annotations', 'draw')(gd);
Registry.getComponentMethod('legend', 'draw')(gd);
Registry.getComponentMethod('colorbar', 'draw')(gd);
resolve(plots.previousPromises(gd));
}, 300);
});
};
// resize plot about the container size
plots.resize = function (gd) {
gd = Lib.getGraphDiv(gd);
var resolveLastResize;
var p = new Promise(function (resolve, reject) {
if (!gd || Lib.isHidden(gd)) {
reject(new Error('Resize must be passed a displayed plot div element.'));
}
if (gd._redrawTimer) clearTimeout(gd._redrawTimer);
if (gd._resolveResize) resolveLastResize = gd._resolveResize;
gd._resolveResize = resolve;
gd._redrawTimer = setTimeout(function () {
// return if there is nothing to resize or is hidden
if (!gd.layout || gd.layout.width && gd.layout.height || Lib.isHidden(gd)) {
resolve(gd);
return;
}
delete gd.layout.width;
delete gd.layout.height;
// autosizing doesn't count as a change that needs saving
var oldchanged = gd.changed;
// nor should it be included in the undo queue
gd.autoplay = true;
Registry.call('relayout', gd, {
autosize: true
}).then(function () {
gd.changed = oldchanged;
// Only resolve if a new call hasn't been made!
if (gd._resolveResize === resolve) {
delete gd._resolveResize;
resolve(gd);
}
});
}, 100);
});
if (resolveLastResize) resolveLastResize(p);
return p;
};
// for use in Lib.syncOrAsync, check if there are any
// pending promises in this plot and wait for them
plots.previousPromises = function (gd) {
if ((gd._promises || []).length) {
return Promise.all(gd._promises).then(function () {
gd._promises = [];
});
}
};
/**
* Adds the 'Edit chart' link.
* Note that now _doPlot calls this so it can regenerate whenever it replots
*
* Add source links to your graph inside the 'showSources' config argument.
*/
plots.addLinks = function (gd) {
// Do not do anything if showLink and showSources are not set to true in config
if (!gd._context.showLink && !gd._context.showSources) return;
var fullLayout = gd._fullLayout;
var linkContainer = Lib.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function (s) {
s.style({
'font-family': '"Open Sans", Arial, sans-serif',
'font-size': '12px',
fill: Color.defaultLine,
'pointer-events': 'all'
}).each(function () {
var links = d3.select(this);
links.append('tspan').classed('js-link-to-tool', true);
links.append('tspan').classed('js-link-spacer', true);
links.append('tspan').classed('js-sourcelinks', true);
});
});
// The text node inside svg
var text = linkContainer.node();
var attrs = {
y: fullLayout._paper.attr('height') - 9
};
// If text's width is bigger than the layout
// Check that text is a child node or document.body
// because otherwise IE/Edge might throw an exception
// when calling getComputedTextLength().
// Apparently offsetParent is null for invisibles.
if (document.body.contains(text) && text.getComputedTextLength() >= fullLayout.width - 20) {
// Align the text at the left
attrs['text-anchor'] = 'start';
attrs.x = 5;
} else {
// Align the text at the right
attrs['text-anchor'] = 'end';
attrs.x = fullLayout._paper.attr('width') - 7;
}
linkContainer.attr(attrs);
var toolspan = linkContainer.select('.js-link-to-tool');
var spacespan = linkContainer.select('.js-link-spacer');
var sourcespan = linkContainer.select('.js-sourcelinks');
if (gd._context.showSources) gd._context.showSources(gd);
// 'view in plotly' link for embedded plots
if (gd._context.showLink) positionPlayWithData(gd, toolspan);
// separator if we have both sources and tool link
spacespan.text(toolspan.text() && sourcespan.text() ? ' - ' : '');
};
// note that now this function is only adding the brand in
// iframes and 3rd-party apps
function positionPlayWithData(gd, container) {
container.text('');
var link = container.append('a').attr({
'xlink:xlink:href': '#',
class: 'link--impt link--embedview',
'font-weight': 'bold'
}).text(gd._context.linkText + ' ' + String.fromCharCode(187));
if (gd._context.sendData) {
link.on('click', function () {
plots.sendDataToCloud(gd);
});
} else {
var path = window.location.pathname.split('/');
var query = window.location.search;
link.attr({
'xlink:xlink:show': 'new',
'xlink:xlink:href': '/' + path[2].split('.')[0] + '/' + path[1] + query
});
}
}
plots.sendDataToCloud = function (gd) {
var baseUrl = (window.PLOTLYENV || {}).BASE_URL || gd._context.plotlyServerURL;
if (!baseUrl) return;
gd.emit('plotly_beforeexport');
var hiddenformDiv = d3.select(gd).append('div').attr('id', 'hiddenform').style('display', 'none');
var hiddenform = hiddenformDiv.append('form').attr({
action: baseUrl + '/external',
method: 'post',
target: '_blank'
});
var hiddenformInput = hiddenform.append('input').attr({
type: 'text',
name: 'data'
});
hiddenformInput.node().value = plots.graphJson(gd, false, 'keepdata');
hiddenform.node().submit();
hiddenformDiv.remove();
gd.emit('plotly_afterexport');
return false;
};
var d3FormatKeys = ['days', 'shortDays', 'months', 'shortMonths', 'periods', 'dateTime', 'date', 'time', 'decimal', 'thousands', 'grouping', 'currency'];
var extraFormatKeys = ['year', 'month', 'dayMonth', 'dayMonthYear'];
/*
* Fill in default values
* @param {DOM element} gd
* @param {object} opts
* @param {boolean} opts.skipUpdateCalc: normally if the existing gd.calcdata looks
* compatible with the new gd._fullData we finish by linking the new _fullData traces
* to the old gd.calcdata, so it's correctly set if we're not going to recalc. But also,
* if there are calcTransforms on the trace, we first remap data arrays from the old full
* trace into the new one. Use skipUpdateCalc to defer this (needed by Plotly.react)
*
* gd.data, gd.layout:
* are precisely what the user specified (except as modified by cleanData/cleanLayout),
* these fields shouldn't be modified (except for filling in some auto values)
* nor used directly after the supply defaults step.
*
* gd._fullData, gd._fullLayout:
* are complete descriptions of how to draw the plot,
* use these fields in all required computations.
*
* gd._fullLayout._modules
* is a list of all the trace modules required to draw the plot.
*
* gd._fullLayout._visibleModules
* subset of _modules, a list of modules corresponding to visible:true traces.
*
* gd._fullLayout._basePlotModules
* is a list of all the plot modules required to draw the plot.
*
* gd._fullLayout._transformModules
* is a list of all the transform modules invoked.
*
*/
plots.supplyDefaults = function (gd, opts) {
var skipUpdateCalc = opts && opts.skipUpdateCalc;
var oldFullLayout = gd._fullLayout || {};
if (oldFullLayout._skipDefaults) {
delete oldFullLayout._skipDefaults;
return;
}
var newFullLayout = gd._fullLayout = {};
var newLayout = gd.layout || {};
var oldFullData = gd._fullData || [];
var newFullData = gd._fullData = [];
var newData = gd.data || [];
var oldCalcdata = gd.calcdata || [];
var context = gd._context || {};
var i;
// Create all the storage space for frames, but only if doesn't already exist
if (!gd._transitionData) plots.createTransitionData(gd);
// So we only need to do this once (and since we have gd here)
// get the translated placeholder titles.
// These ones get used as default values so need to be known at supplyDefaults
// others keep their blank defaults but render the placeholder as desired later
// TODO: make these work the same way, only inserting the placeholder text at draw time?
// The challenge is that this has slightly different behavior right now in editable mode:
// using the placeholder as default makes this text permanently (but lightly) visible,
// but explicit '' for these titles gives you a placeholder that's hidden until you mouse
// over it - so you're not distracted by it if you really don't want a title, but if you do
// and you're new to plotly you may not be able to find it.
// When editable=false the two behave the same, no title is drawn.
newFullLayout._dfltTitle = {
plot: _(gd, 'Click to enter Plot title'),
subtitle: _(gd, 'Click to enter Plot subtitle'),
x: _(gd, 'Click to enter X axis title'),
y: _(gd, 'Click to enter Y axis title'),
colorbar: _(gd, 'Click to enter Colorscale title'),
annotation: _(gd, 'new text')
};
newFullLayout._traceWord = _(gd, 'trace');
var formatObj = getFormatObj(gd, d3FormatKeys);
// stash the token from context so mapbox subplots can use it as default
newFullLayout._mapboxAccessToken = context.mapboxAccessToken;
// first fill in what we can of layout without looking at data
// because fullData needs a few things from layout
if (oldFullLayout._initialAutoSizeIsDone) {
// coerce the updated layout while preserving width and height
var oldWidth = oldFullLayout.width;
var oldHeight = oldFullLayout.height;
plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);
if (!newLayout.width) newFullLayout.width = oldWidth;
if (!newLayout.height) newFullLayout.height = oldHeight;
plots.sanitizeMargins(newFullLayout);
} else {
// coerce the updated layout and autosize if needed
plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);
var missingWidthOrHeight = !newLayout.width || !newLayout.height;
var autosize = newFullLayout.autosize;
var autosizable = context.autosizable;
var initialAutoSize = missingWidthOrHeight && (autosize || autosizable);
if (initialAutoSize) plots.plotAutoSize(gd, newLayout, newFullLayout);else if (missingWidthOrHeight) plots.sanitizeMargins(newFullLayout);
// for backwards-compatibility with Plotly v1.x.x
if (!autosize && missingWidthOrHeight) {
newLayout.width = newFullLayout.width;
newLayout.height = newFullLayout.height;
}
}
newFullLayout._d3locale = getFormatter(formatObj, newFullLayout.separators);
newFullLayout._extraFormat = getFormatObj(gd, extraFormatKeys);
newFullLayout._initialAutoSizeIsDone = true;
// keep track of how many traces are inputted
newFullLayout._dataLength = newData.length;
// clear the lists of trace and baseplot modules, and subplots
newFullLayout._modules = [];
newFullLayout._visibleModules = [];
newFullLayout._basePlotModules = [];
var subplots = newFullLayout._subplots = emptySubplotLists();
// initialize axis and subplot hash objects for splom-generated grids
var splomAxes = newFullLayout._splomAxes = {
x: {},
y: {}
};
var splomSubplots = newFullLayout._splomSubplots = {};
// initialize splom grid defaults
newFullLayout._splomGridDflt = {};
// for stacked area traces to share config across traces
newFullLayout._scatterStackOpts = {};
// for the first scatter trace on each subplot (so it knows tonext->tozero)
newFullLayout._firstScatter = {};
// for grouped bar/box/violin trace to share config across traces
newFullLayout._alignmentOpts = {};
// track color axes referenced in the data
newFullLayout._colorAxes = {};
// for traces to request a default rangeslider on their x axes
// eg set `_requestRangeslider.x2 = true` for xaxis2
newFullLayout._requestRangeslider = {};
// pull uids from old data to use as new defaults
newFullLayout._traceUids = getTraceUids(oldFullData, newData);
// then do the data
newFullLayout._globalTransforms = (gd._context || {}).globalTransforms;
plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout);
// redo grid size defaults with info about splom x/y axes,
// and fill in generated cartesian axes and subplots
var splomXa = Object.keys(splomAxes.x);
var splomYa = Object.keys(splomAxes.y);
if (splomXa.length > 1 && splomYa.length > 1) {
Registry.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout);
for (i = 0; i < splomXa.length; i++) {
Lib.pushUnique(subplots.xaxis, splomXa[i]);
}
for (i = 0; i < splomYa.length; i++) {
Lib.pushUnique(subplots.yaxis, splomYa[i]);
}
for (var k in splomSubplots) {
Lib.pushUnique(subplots.cartesian, k);
}
}
// attach helper method to check whether a plot type is present on graph
newFullLayout._has = plots._hasPlotType.bind(newFullLayout);
if (oldFullData.length === newFullData.length) {
for (i = 0; i < newFullData.length; i++) {
relinkPrivateKeys(newFullData[i], oldFullData[i]);
}
}
// finally, fill in the pieces of layout that may need to look at data
plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData);
// Special cases that introduce interactions between traces.
// This is after relinkPrivateKeys so we can use those in crossTraceDefaults
// and after layout module defaults, so we can use eg barmode
var _modules = newFullLayout._visibleModules;
var crossTraceDefaultsFuncs = [];
for (i = 0; i < _modules.length; i++) {
var funci = _modules[i].crossTraceDefaults;
// some trace types share crossTraceDefaults (ie histogram2d, histogram2dcontour)
if (funci) Lib.pushUnique(crossTraceDefaultsFuncs, funci);
}
for (i = 0; i < crossTraceDefaultsFuncs.length; i++) {
crossTraceDefaultsFuncs[i](newFullData, newFullLayout);
}
// turn on flag to optimize large splom-only graphs
// mostly by omitting SVG layers during Cartesian.drawFramework
newFullLayout._hasOnlyLargeSploms = newFullLayout._basePlotModules.length === 1 && newFullLayout._basePlotModules[0].name === 'splom' && splomXa.length > 15 && splomYa.length > 15 && newFullLayout.shapes.length === 0 && newFullLayout.images.length === 0;
// relink / initialize subplot axis objects
plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout);
// clean subplots and other artifacts from previous plot calls
plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout);
var hadGL2D = !!(oldFullLayout._has && oldFullLayout._has('gl2d'));
var hasGL2D = !!(newFullLayout._has && newFullLayout._has('gl2d'));
var hadCartesian = !!(oldFullLayout._has && oldFullLayout._has('cartesian'));
var hasCartesian = !!(newFullLayout._has && newFullLayout._has('cartesian'));
var hadBgLayer = hadCartesian || hadGL2D;
var hasBgLayer = hasCartesian || hasGL2D;
if (hadBgLayer && !hasBgLayer) {
// remove bgLayer
oldFullLayout._bgLayer.remove();
} else if (hasBgLayer && !hadBgLayer) {
// create bgLayer
newFullLayout._shouldCreateBgLayer = true;
}
// clear selection outline until we implement persistent selection,
// don't clear them though when drag handlers (e.g. listening to
// `plotly_selecting`) update the graph.
// we should try to come up with a better solution when implementing
// https://github.com/plotly/plotly.js/issues/1851
if (oldFullLayout._zoomlayer && !gd._dragging) {
clearOutline({
// mock old gd
_fullLayout: oldFullLayout
});
}
// fill in meta helpers
fillMetaTextHelpers(newFullData, newFullLayout);
// relink functions and _ attributes to promote consistency between plots
relinkPrivateKeys(newFullLayout, oldFullLayout);
// colorscale crossTraceDefaults needs newFullLayout with relinked keys
Registry.getComponentMethod('colorscale', 'crossTraceDefaults')(newFullData, newFullLayout);
// For persisting GUI-driven changes in layout
// _preGUI and _tracePreGUI were already copied over in relinkPrivateKeys
if (!newFullLayout._preGUI) newFullLayout._preGUI = {};
// track trace GUI changes by uid rather than by trace index
if (!newFullLayout._tracePreGUI) newFullLayout._tracePreGUI = {};
var tracePreGUI = newFullLayout._tracePreGUI;
var uids = {};
var uid;
for (uid in tracePreGUI) uids[uid] = 'old';
for (i = 0; i < newFullData.length; i++) {
uid = newFullData[i]._fullInput.uid;
if (!uids[uid]) tracePreGUI[uid] = {};
uids[uid] = 'new';
}
for (uid in uids) {
if (uids[uid] === 'old') delete tracePreGUI[uid];
}
// set up containers for margin calculations
initMargins(newFullLayout);
// collect and do some initial calculations for rangesliders
Registry.getComponentMethod('rangeslider', 'makeData')(newFullLayout);
// update object references in calcdata
if (!skipUpdateCalc && oldCalcdata.length === newFullData.length) {
plots.supplyDefaultsUpdateCalc(oldCalcdata, newFullData);
}
};
plots.supplyDefaultsUpdateCalc = function (oldCalcdata, newFullData) {
for (var i = 0; i < newFullData.length; i++) {
var newTrace = newFullData[i];
var cd0 = (oldCalcdata[i] || [])[0];
if (cd0 && cd0.trace) {
var oldTrace = cd0.trace;
if (oldTrace._hasCalcTransform) {
var arrayAttrs = oldTrace._arrayAttrs;
var j, astr, oldArrayVal;
for (j = 0; j < arrayAttrs.length; j++) {
astr = arrayAttrs[j];
oldArrayVal = Lib.nestedProperty(oldTrace, astr).get().slice();
Lib.nestedProperty(newTrace, astr).set(oldArrayVal);
}
}
cd0.trace = newTrace;
}
}
};
/**
* Create a list of uid strings satisfying (in this order of importance):
* 1. all unique, all strings
* 2. matches input uids if provided
* 3. matches previous data uids
*/
function getTraceUids(oldFullData, newData) {
var len = newData.length;
var oldFullInput = [];
var i, prevFullInput;
for (i = 0; i < oldFullData.length; i++) {
var thisFullInput = oldFullData[i]._fullInput;
if (thisFullInput !== prevFullInput) oldFullInput.push(thisFullInput);
prevFullInput = thisFullInput;
}
var oldLen = oldFullInput.length;
var out = new Array(len);
var seenUids = {};
function setUid(uid, i) {
out[i] = uid;
seenUids[uid] = 1;
}
function tryUid(uid, i) {
if (uid && typeof uid === 'string' && !seenUids[uid]) {
setUid(uid, i);
return true;
}
}
for (i = 0; i < len; i++) {
var newUid = newData[i].uid;
if (typeof newUid === 'number') newUid = String(newUid);
if (tryUid(newUid, i)) continue;
if (i < oldLen && tryUid(oldFullInput[i].uid, i)) continue;
setUid(Lib.randstr(seenUids), i);
}
return out;
}
/**
* Make a container for collecting subplots we need to display.
*
* Finds all subplot types we need to enumerate once and caches it,
* but makes a new output object each time.
* Single-trace subplots (which have no `id`) such as pie, table, etc
* do not need to be collected because we just draw all visible traces.
*/
function emptySubplotLists() {
var collectableSubplotTypes = Registry.collectableSubplotTypes;
var out = {};
var i, j;
if (!collectableSubplotTypes) {
collectableSubplotTypes = [];
var subplotsRegistry = Registry.subplotsRegistry;
for (var subplotType in subplotsRegistry) {
var subplotModule = subplotsRegistry[subplotType];
var subplotAttr = subplotModule.attr;
if (subplotAttr) {
collectableSubplotTypes.push(subplotType);
// special case, currently just for cartesian:
// we need to enumerate axes, not just subplots
if (Array.isArray(subplotAttr)) {
for (j = 0; j < subplotAttr.length; j++) {
Lib.pushUnique(collectableSubplotTypes, subplotAttr[j]);
}
}
}
}
}
for (i = 0; i < collectableSubplotTypes.length; i++) {
out[collectableSubplotTypes[i]] = [];
}
return out;
}
/**
* getFormatObj: use _context to get the format object from locale.
* Used to get d3.locale argument object and extraFormat argument object
*
* Regarding d3.locale argument :
* decimal and thousands can be overridden later by layout.separators
* grouping and currency are not presently used by our automatic number
* formatting system but can be used by custom formats.
*
* @returns {object} d3.locale format object
*/
function getFormatObj(gd, formatKeys) {
var locale = gd._context.locale;
if (!locale) locale = 'en-US';
var formatDone = false;
var formatObj = {};
function includeFormat(newFormat) {
var formatFinished = true;
for (var i = 0; i < formatKeys.length; i++) {
var formatKey = formatKeys[i];
if (!formatObj[formatKey]) {
if (newFormat[formatKey]) {
formatObj[formatKey] = newFormat[formatKey];
} else formatFinished = false;
}
}
if (formatFinished) formatDone = true;
}
// same as localize, look for format parts in each format spec in the chain
for (var i = 0; i < 2; i++) {
var locales = gd._context.locales;
for (var j = 0; j < 2; j++) {
var formatj = (locales[locale] || {}).format;
if (formatj) {
includeFormat(formatj);
if (formatDone) break;
}
locales = Registry.localeRegistry;
}
var baseLocale = locale.split('-')[0];
if (formatDone || baseLocale === locale) break;
locale = baseLocale;
}
// lastly pick out defaults from english (non-US, as DMY is so much more common)
if (!formatDone) includeFormat(Registry.localeRegistry.en.format);
return formatObj;
}
/**
* getFormatter: combine the final separators with the locale formatting object
* we pulled earlier to generate number and time formatters
* TODO: remove separators in v3, only use locale, so we don't need this step?
*
* @param {object} formatObj: d3.locale format object
* @param {string} separators: length-2 string to override decimal and thousands
* separators in number formatting
*
* @returns {object} {numberFormat, timeFormat} d3 formatter factory functions
* for numbers and time
*/
function getFormatter(formatObj, separators) {
formatObj.decimal = separators.charAt(0);
formatObj.thousands = separators.charAt(1);
return {
numberFormat: function (formatStr) {
try {
formatStr = formatLocale(formatObj).format(Lib.adjustFormat(formatStr));
} catch (e) {
Lib.warnBadFormat(formatStr);
return Lib.noFormat;
}
return formatStr;
},
timeFormat: timeFormatLocale(formatObj).utcFormat
};
}
function fillMetaTextHelpers(newFullData, newFullLayout) {
var _meta;
var meta4data = [];
if (newFullLayout.meta) {
_meta = newFullLayout._meta = {
meta: newFullLayout.meta,
layout: {
meta: newFullLayout.meta
}
};
}
for (var i = 0; i < newFullData.length; i++) {
var trace = newFullData[i];
if (trace.meta) {
meta4data[trace.index] = trace._meta = {
meta: trace.meta
};
} else if (newFullLayout.meta) {
trace._meta = {
meta: newFullLayout.meta
};
}
if (newFullLayout.meta) {
trace._meta.layout = {
meta: newFullLayout.meta
};
}
}
if (meta4data.length) {
if (!_meta) {
_meta = newFullLayout._meta = {};
}
_meta.data = meta4data;
}
}
// Create storage for all of the data related to frames and transitions:
plots.createTransitionData = function (gd) {
// Set up the default keyframe if it doesn't exist:
if (!gd._transitionData) {
gd._transitionData = {};
}
if (!gd._transitionData._frames) {
gd._transitionData._frames = [];
}
if (!gd._transitionData._frameHash) {
gd._transitionData._frameHash = {};
}
if (!gd._transitionData._counter) {
gd._transitionData._counter = 0;
}
if (!gd._transitionData._interruptCallbacks) {
gd._transitionData._interruptCallbacks = [];
}
};
// helper function to be bound to fullLayout to check
// whether a certain plot type is present on plot
// or trace has a category
plots._hasPlotType = function (category) {
var i;
// check base plot modules
var basePlotModules = this._basePlotModules || [];
for (i = 0; i < basePlotModules.length; i++) {
if (basePlotModules[i].name === category) return true;
}
// check trace modules (including non-visible:true)
var modules = this._modules || [];
for (i = 0; i < modules.length; i++) {
var name = modules[i].name;
if (name === category) return true;
// N.B. this is modules[i] along with 'categories' as a hash object
var _module = Registry.modules[name];
if (_module && _module.categories[category]) return true;
}
return false;
};
plots.cleanPlot = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var i, j;
var basePlotModules = oldFullLayout._basePlotModules || [];
for (i = 0; i < basePlotModules.length; i++) {
var _module = basePlotModules[i];
if (_module.clean) {
_module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
}
}
var hadGl = oldFullLayout._has && oldFullLayout._has('gl');
var hasGl = newFullLayout._has && newFullLayout._has('gl');
if (hadGl && !hasGl) {
if (oldFullLayout._glcontainer !== undefined) {
oldFullLayout._glcontainer.selectAll('.gl-canvas').remove();
oldFullLayout._glcontainer.selectAll('.no-webgl').remove();
oldFullLayout._glcanvas = null;
}
}
var hasInfoLayer = !!oldFullLayout._infolayer;
oldLoop: for (i = 0; i < oldFullData.length; i++) {
var oldTrace = oldFullData[i];
var oldUid = oldTrace.uid;
for (j = 0; j < newFullData.length; j++) {
var newTrace = newFullData[j];
if (oldUid === newTrace.uid) continue oldLoop;
}
// clean old colorbars
if (hasInfoLayer) {
oldFullLayout._infolayer.select('.cb' + oldUid).remove();
}
}
};
plots.linkSubplots = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var i, j;
var oldSubplots = oldFullLayout._plots || {};
var newSubplots = newFullLayout._plots = {};
var newSubplotList = newFullLayout._subplots;
var mockGd = {
_fullData: newFullData,
_fullLayout: newFullLayout
};
var ids = newSubplotList.cartesian.concat(newSubplotList.gl2d || []);
for (i = 0; i < ids.length; i++) {
var id = ids[i];
var oldSubplot = oldSubplots[id];
var xaxis = axisIDs.getFromId(mockGd, id, 'x');
var yaxis = axisIDs.getFromId(mockGd, id, 'y');
var plotinfo;
// link or create subplot object
if (oldSubplot) {
plotinfo = newSubplots[id] = oldSubplot;
} else {
plotinfo = newSubplots[id] = {};
plotinfo.id = id;
}
// add these axis ids to each others' subplot lists
xaxis._counterAxes.push(yaxis._id);
yaxis._counterAxes.push(xaxis._id);
xaxis._subplotsWith.push(id);
yaxis._subplotsWith.push(id);
// update x and y axis layout object refs
plotinfo.xaxis = xaxis;
plotinfo.yaxis = yaxis;
// By default, we clip at the subplot level,
// but if one trace on a given subplot has *cliponaxis* set to false,
// we need to clip at the trace module layer level;
// find this out here, once of for all.
plotinfo._hasClipOnAxisFalse = false;
for (j = 0; j < newFullData.length; j++) {
var trace = newFullData[j];
if (trace.xaxis === plotinfo.xaxis._id && trace.yaxis === plotinfo.yaxis._id && trace.cliponaxis === false) {
plotinfo._hasClipOnAxisFalse = true;
break;
}
}
}
// while we're at it, link overlaying axes to their main axes and
// anchored axes to the axes they're anchored to
var axList = axisIDs.list(mockGd, null, true);
var ax;
for (i = 0; i < axList.length; i++) {
ax = axList[i];
var mainAx = null;
if (ax.overlaying) {
mainAx = axisIDs.getFromId(mockGd, ax.overlaying);
// you cannot overlay an axis that's already overlaying another
if (mainAx && mainAx.overlaying) {
ax.overlaying = false;
mainAx = null;
}
}
ax._mainAxis = mainAx || ax;
/*
* For now force overlays to overlay completely... so they
* can drag together correctly and share backgrounds.
* Later perhaps we make separate axis domain and
* tick/line domain or something, so they can still share
* the (possibly larger) dragger and background but don't
* have to both be drawn over that whole domain
*/
if (mainAx) ax.domain = mainAx.domain.slice();
ax._anchorAxis = ax.anchor === 'free' ? null : axisIDs.getFromId(mockGd, ax.anchor);
}
// finally, we can find the main subplot for each axis
// (on which the ticks & labels are drawn)
for (i = 0; i < axList.length; i++) {
ax = axList[i];
ax._counterAxes.sort(axisIDs.idSort);
ax._subplotsWith.sort(Lib.subplotSort);
ax._mainSubplot = findMainSubplot(ax, newFullLayout);
// find "full" domain span of counter axes,
// this loop can be costly, so only compute it when required
if (ax._counterAxes.length && (ax.spikemode && ax.spikemode.indexOf('across') !== -1 || ax.automargin && ax.mirror && ax.anchor !== 'free' || Registry.getComponentMethod('rangeslider', 'isVisible')(ax))) {
var min = 1;
var max = 0;
for (j = 0; j < ax._counterAxes.length; j++) {
var ax2 = axisIDs.getFromId(mockGd, ax._counterAxes[j]);
min = Math.min(min, ax2.domain[0]);
max = Math.max(max, ax2.domain[1]);
}
if (min < max) {
ax._counterDomainMin = min;
ax._counterDomainMax = max;
}
}
}
};
function findMainSubplot(ax, fullLayout) {
var mockGd = {
_fullLayout: fullLayout
};
var isX = ax._id.charAt(0) === 'x';
var anchorAx = ax._mainAxis._anchorAxis;
var mainSubplotID = '';
var nextBestMainSubplotID = '';
var anchorID = '';
// First try the main ID with the anchor
if (anchorAx) {
anchorID = anchorAx._mainAxis._id;
mainSubplotID = isX ? ax._id + anchorID : anchorID + ax._id;
}
// Then look for a subplot with the counteraxis overlaying the anchor
// If that fails just use the first subplot including this axis
if (!mainSubplotID || !fullLayout._plots[mainSubplotID]) {
mainSubplotID = '';
var counterIDs = ax._counterAxes;
for (var j = 0; j < counterIDs.length; j++) {
var counterPart = counterIDs[j];
var id = isX ? ax._id + counterPart : counterPart + ax._id;
if (!nextBestMainSubplotID) nextBestMainSubplotID = id;
var counterAx = axisIDs.getFromId(mockGd, counterPart);
if (anchorID && counterAx.overlaying === anchorID) {
mainSubplotID = id;
break;
}
}
}
return mainSubplotID || nextBestMainSubplotID;
}
// This function clears any trace attributes with valType: color and
// no set dflt filed in the plot schema. This is needed because groupby (which
// is the only transform for which this currently applies) supplies parent
// trace defaults, then expanded trace defaults. The result is that `null`
// colors are default-supplied and inherited as a color instead of a null.
// The result is that expanded trace default colors have no effect, with
// the final result that groups are indistinguishable. This function clears
// those colors so that individual groupby groups get unique colors.
plots.clearExpandedTraceDefaultColors = function (trace) {
var colorAttrs, path, i;
// This uses weird closure state in order to satisfy the linter rule
// that we can't create functions in a loop.
function locateColorAttrs(attr, attrName, attrs, level) {
path[level] = attrName;
path.length = level + 1;
if (attr.valType === 'color' && attr.dflt === undefined) {
colorAttrs.push(path.join('.'));
}
}
path = [];
// Get the cached colorAttrs:
colorAttrs = trace._module._colorAttrs;
// Or else compute and cache the colorAttrs on the module:
if (!colorAttrs) {
trace._module._colorAttrs = colorAttrs = [];
PlotSchema.crawl(trace._module.attributes, locateColorAttrs);
}
for (i = 0; i < colorAttrs.length; i++) {
var origprop = Lib.nestedProperty(trace, '_input.' + colorAttrs[i]);
if (!origprop.get()) {
Lib.nestedProperty(trace, colorAttrs[i]).set(null);
}
}
};
plots.supplyDataDefaults = function (dataIn, dataOut, layout, fullLayout) {
var modules = fullLayout._modules;
var visibleModules = fullLayout._visibleModules;
var basePlotModules = fullLayout._basePlotModules;
var cnt = 0;
var colorCnt = 0;
var i, fullTrace, trace;
fullLayout._transformModules = [];
function pushModule(fullTrace) {
dataOut.push(fullTrace);
var _module = fullTrace._module;
if (!_module) return;
Lib.pushUnique(modules, _module);
if (fullTrace.visible === true) Lib.pushUnique(visibleModules, _module);
Lib.pushUnique(basePlotModules, fullTrace._module.basePlotModule);
cnt++;
// TODO: do we really want color not to increment for explicitly invisible traces?
// This logic is weird, but matches previous behavior: traces that you explicitly
// set to visible:false do not increment the color, but traces WE determine to be
// empty or invalid (and thus set to visible:false) DO increment color.
// I kind of think we should just let all traces increment color, visible or not.
// see mock: axes-autotype-empty vs. a test of restyling visible: false that
// I can't find right now...
if (fullTrace._input.visible !== false) colorCnt++;
}
var carpetIndex = {};
var carpetDependents = [];
var dataTemplate = (layout.template || {}).data || {};
var templater = Template.traceTemplater(dataTemplate);
for (i = 0; i < dataIn.length; i++) {
trace = dataIn[i];
// reuse uid we may have pulled out of oldFullData
// Note: templater supplies trace type
fullTrace = templater.newTrace(trace);
fullTrace.uid = fullLayout._traceUids[i];
plots.supplyTraceDefaults(trace, fullTrace, colorCnt, fullLayout, i);
fullTrace.index = i;
fullTrace._input = trace;
fullTrace._expandedIndex = cnt;
if (fullTrace.transforms && fullTrace.transforms.length) {
var sdInvisible = trace.visible !== false && fullTrace.visible === false;
var expandedTraces = applyTransforms(fullTrace, dataOut, layout, fullLayout);
for (var j = 0; j < expandedTraces.length; j++) {
var expandedTrace = expandedTraces[j];
// No further templating during transforms.
var fullExpandedTrace = {
_template: fullTrace._template,
type: fullTrace.type,
// set uid using parent uid and expanded index
// to promote consistency between update calls
uid: fullTrace.uid + j
};
// If the first supplyDefaults created `visible: false`,
// clear it before running supplyDefaults a second time,
// because sometimes there are items we still want to coerce
// inside trace modules before determining that the trace is
// again `visible: false`, for example partial visibilities
// in `splom` traces.
if (sdInvisible && expandedTrace.visible === false) {
delete expandedTrace.visible;
}
plots.supplyTraceDefaults(expandedTrace, fullExpandedTrace, cnt, fullLayout, i);
// relink private (i.e. underscore) keys expanded trace to full expanded trace so
// that transform supply-default methods can set _ keys for future use.
relinkPrivateKeys(fullExpandedTrace, expandedTrace);
// add info about parent data trace
fullExpandedTrace.index = i;
fullExpandedTrace._input = trace;
fullExpandedTrace._fullInput = fullTrace;
// add info about the expanded data
fullExpandedTrace._expandedIndex = cnt;
fullExpandedTrace._expandedInput = expandedTrace;
pushModule(fullExpandedTrace);
}
} else {
// add identify refs for consistency with transformed traces
fullTrace._fullInput = fullTrace;
fullTrace._expandedInput = fullTrace;
pushModule(fullTrace);
}
if (Registry.traceIs(fullTrace, 'carpetAxis')) {
carpetIndex[fullTrace.carpet] = fullTrace;
}
if (Registry.traceIs(fullTrace, 'carpetDependent')) {
carpetDependents.push(i);
}
}
for (i = 0; i < carpetDependents.length; i++) {
fullTrace = dataOut[carpetDependents[i]];
if (!fullTrace.visible) continue;
var carpetAxis = carpetIndex[fullTrace.carpet];
fullTrace._carpet = carpetAxis;
if (!carpetAxis || !carpetAxis.visible) {
fullTrace.visible = false;
continue;
}
fullTrace.xaxis = carpetAxis.xaxis;
fullTrace.yaxis = carpetAxis.yaxis;
}
};
plots.supplyAnimationDefaults = function (opts) {
opts = opts || {};
var i;
var optsOut = {};
function coerce(attr, dflt) {
return Lib.coerce(opts || {}, optsOut, animationAttrs, attr, dflt);
}
coerce('mode');
coerce('direction');
coerce('fromcurrent');
if (Array.isArray(opts.frame)) {
optsOut.frame = [];
for (i = 0; i < opts.frame.length; i++) {
optsOut.frame[i] = plots.supplyAnimationFrameDefaults(opts.frame[i] || {});
}
} else {
optsOut.frame = plots.supplyAnimationFrameDefaults(opts.frame || {});
}
if (Array.isArray(opts.transition)) {
optsOut.transition = [];
for (i = 0; i < opts.transition.length; i++) {
optsOut.transition[i] = plots.supplyAnimationTransitionDefaults(opts.transition[i] || {});
}
} else {
optsOut.transition = plots.supplyAnimationTransitionDefaults(opts.transition || {});
}
return optsOut;
};
plots.supplyAnimationFrameDefaults = function (opts) {
var optsOut = {};
function coerce(attr, dflt) {
return Lib.coerce(opts || {}, optsOut, animationAttrs.frame, attr, dflt);
}
coerce('duration');
coerce('redraw');
return optsOut;
};
plots.supplyAnimationTransitionDefaults = function (opts) {
var optsOut = {};
function coerce(attr, dflt) {
return Lib.coerce(opts || {}, optsOut, animationAttrs.transition, attr, dflt);
}
coerce('duration');
coerce('easing');
return optsOut;
};
plots.supplyFrameDefaults = function (frameIn) {
var frameOut = {};
function coerce(attr, dflt) {
return Lib.coerce(frameIn, frameOut, frameAttrs, attr, dflt);
}
coerce('group');
coerce('name');
coerce('traces');
coerce('baseframe');
coerce('data');
coerce('layout');
return frameOut;
};
plots.supplyTraceDefaults = function (traceIn, traceOut, colorIndex, layout, traceInIndex) {
var colorway = layout.colorway || Color.defaults;
var defaultColor = colorway[colorIndex % colorway.length];
var i;
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, plots.attributes, attr, dflt);
}
var visible = coerce('visible');
coerce('type');
coerce('name', layout._traceWord + ' ' + traceInIndex);
coerce('uirevision', layout.uirevision);
// we want even invisible traces to make their would-be subplots visible
// so coerce the subplot id(s) now no matter what
var _module = plots.getModule(traceOut);
traceOut._module = _module;
if (_module) {
var basePlotModule = _module.basePlotModule;
var subplotAttr = basePlotModule.attr;
var subplotAttrs = basePlotModule.attributes;
if (subplotAttr && subplotAttrs) {
var subplots = layout._subplots;
var subplotId = '';
if (visible || basePlotModule.name !== 'gl2d' // for now just drop empty gl2d subplots
// TODO - currently if we draw an empty gl2d subplot, it draws
// nothing then gets stuck and you can't get it back without newPlot
// sort this out in the regl refactor?
) {
if (Array.isArray(subplotAttr)) {
for (i = 0; i < subplotAttr.length; i++) {
var attri = subplotAttr[i];
var vali = Lib.coerce(traceIn, traceOut, subplotAttrs, attri);
if (subplots[attri]) Lib.pushUnique(subplots[attri], vali);
subplotId += vali;
}
} else {
subplotId = Lib.coerce(traceIn, traceOut, subplotAttrs, subplotAttr);
}
if (subplots[basePlotModule.name]) {
Lib.pushUnique(subplots[basePlotModule.name], subplotId);
}
}
}
}
if (visible) {
coerce('customdata');
coerce('ids');
coerce('meta');
if (Registry.traceIs(traceOut, 'showLegend')) {
Lib.coerce(traceIn, traceOut, _module.attributes.showlegend ? _module.attributes : plots.attributes, 'showlegend');
coerce('legend');
coerce('legendwidth');
coerce('legendgroup');
coerce('legendgrouptitle.text');
coerce('legendrank');
traceOut._dfltShowLegend = true;
} else {
traceOut._dfltShowLegend = false;
}
if (_module) {
_module.supplyDefaults(traceIn, traceOut, defaultColor, layout);
}
if (!Registry.traceIs(traceOut, 'noOpacity')) {
coerce('opacity');
}
if (Registry.traceIs(traceOut, 'notLegendIsolatable')) {
// This clears out the legendonly state for traces like carpet that
// cannot be isolated in the legend
traceOut.visible = !!traceOut.visible;
}
if (!Registry.traceIs(traceOut, 'noHover')) {
if (!traceOut.hovertemplate) Lib.coerceHoverinfo(traceIn, traceOut, layout);
// parcats support hover, but not hoverlabel stylings (yet)
if (traceOut.type !== 'parcats') {
Registry.getComponentMethod('fx', 'supplyDefaults')(traceIn, traceOut, defaultColor, layout);
}
}
if (_module && _module.selectPoints) {
var selectedpoints = coerce('selectedpoints');
if (Lib.isTypedArray(selectedpoints)) {
traceOut.selectedpoints = Array.from(selectedpoints);
}
}
plots.supplyTransformDefaults(traceIn, traceOut, layout);
}
return traceOut;
};
/**
* hasMakesDataTransform: does this trace have a transform that makes its own
* data, either by grabbing it from somewhere else or by creating it from input
* parameters? If so, we should still keep going with supplyDefaults
* even if the trace is invisible, which may just be because it has no data yet.
*/
function hasMakesDataTransform(trace) {
var transforms = trace.transforms;
if (Array.isArray(transforms) && transforms.length) {
for (var i = 0; i < transforms.length; i++) {
var ti = transforms[i];
var _module = ti._module || transformsRegistry[ti.type];
if (_module && _module.makesData) return true;
}
}
return false;
}
plots.hasMakesDataTransform = hasMakesDataTransform;
plots.supplyTransformDefaults = function (traceIn, traceOut, layout) {
// For now we only allow transforms on 1D traces, ie those that specify a _length.
// If we were to implement 2D transforms, we'd need to have each transform
// describe its own applicability and disable itself when it doesn't apply.
// Also allow transforms that make their own data, but not in globalTransforms
if (!(traceOut._length || hasMakesDataTransform(traceIn))) return;
var globalTransforms = layout._globalTransforms || [];
var transformModules = layout._transformModules || [];
if (!Array.isArray(traceIn.transforms) && globalTransforms.length === 0) return;
var containerIn = traceIn.transforms || [];
var transformList = globalTransforms.concat(containerIn);
var containerOut = traceOut.transforms = [];
for (var i = 0; i < transformList.length; i++) {
var transformIn = transformList[i];
var type = transformIn.type;
var _module = transformsRegistry[type];
var transformOut;
/*
* Supply defaults may run twice. First pass runs all supply defaults steps
* and adds the _module to any output transforms.
* If transforms exist another pass is run so that any generated traces also
* go through supply defaults. This has the effect of rerunning
* supplyTransformDefaults. If the transform does not have a `transform`
* function it could not have generated any new traces and the second stage
* is unnecessary. We detect this case with the following variables.
*/
var isFirstStage = !(transformIn._module && transformIn._module === _module);
var doLaterStages = _module && typeof _module.transform === 'function';
if (!_module) Lib.warn('Unrecognized transform type ' + type + '.');
if (_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) {
transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn);
transformOut.type = type;
transformOut._module = _module;
Lib.pushUnique(transformModules, _module);
} else {
transformOut = Lib.extendFlat({}, transformIn);
}
containerOut.push(transformOut);
}
};
function applyTransforms(fullTrace, fullData, layout, fullLayout) {
var container = fullTrace.transforms;
var dataOut = [fullTrace];
for (var i = 0; i < container.length; i++) {
var transform = container[i];
var _module = transformsRegistry[transform.type];
if (_module && _module.transform) {
dataOut = _module.transform(dataOut, {
transform: transform,
fullTrace: fullTrace,
fullData: fullData,
layout: layout,
fullLayout: fullLayout,
transformIndex: i
});
}
}
return dataOut;
}
plots.supplyLayoutGlobalDefaults = function (layoutIn, layoutOut, formatObj) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt);
}
var template = layoutIn.template;
if (Lib.isPlainObject(template)) {
layoutOut.template = template;
layoutOut._template = template.layout;
layoutOut._dataTemplate = template.data;
}
coerce('autotypenumbers');
var font = Lib.coerceFont(coerce, 'font');
var fontSize = font.size;
Lib.coerceFont(coerce, 'title.font', font, {
overrideDflt: {
size: Math.round(fontSize * 1.4)
}
});
coerce('title.text', layoutOut._dfltTitle.plot);
coerce('title.xref');
var titleYref = coerce('title.yref');
coerce('title.pad.t');
coerce('title.pad.r');
coerce('title.pad.b');
coerce('title.pad.l');
var titleAutomargin = coerce('title.automargin');
coerce('title.x');
coerce('title.xanchor');
coerce('title.y');
coerce('title.yanchor');
coerce('title.subtitle.text', layoutOut._dfltTitle.subtitle);
Lib.coerceFont(coerce, 'title.subtitle.font', font, {
overrideDflt: {
size: Math.round(layoutOut.title.font.size * 0.7)
}
});
if (titleAutomargin) {
// when automargin=true
// title.y is 1 or 0 if paper ref
// 'auto' is not supported for either title.y or title.yanchor
// TODO: mention this smart default in the title.y and title.yanchor descriptions
if (titleYref === 'paper') {
if (layoutOut.title.y !== 0) layoutOut.title.y = 1;
if (layoutOut.title.yanchor === 'auto') {
layoutOut.title.yanchor = layoutOut.title.y === 0 ? 'top' : 'bottom';
}
}
if (titleYref === 'container') {
if (layoutOut.title.y === 'auto') layoutOut.title.y = 1;
if (layoutOut.title.yanchor === 'auto') {
layoutOut.title.yanchor = layoutOut.title.y < 0.5 ? 'bottom' : 'top';
}
}
}
var uniformtextMode = coerce('uniformtext.mode');
if (uniformtextMode) {
coerce('uniformtext.minsize');
}
// Make sure that autosize is defaulted to *true*
// on layouts with no set width and height for backward compatibly,
// in particular https://plotly.com/javascript/responsive-fluid-layout/
//
// Before https://github.com/plotly/plotly.js/pull/635 ,
// layouts with no set width and height were set temporary set to 'initial'
// to pass through the autosize routine
//
// This behavior is subject to change in v3.
coerce('autosize', !(layoutIn.width && layoutIn.height));
coerce('width');
coerce('height');
coerce('minreducedwidth');
coerce('minreducedheight');
coerce('margin.l');
coerce('margin.r');
coerce('margin.t');
coerce('margin.b');
coerce('margin.pad');
coerce('margin.autoexpand');
if (layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut);
Registry.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut);
coerce('paper_bgcolor');
coerce('separators', formatObj.decimal + formatObj.thousands);
coerce('hidesources');
coerce('colorway');
coerce('datarevision');
var uirevision = coerce('uirevision');
coerce('editrevision', uirevision);
coerce('selectionrevision', uirevision);
Registry.getComponentMethod('modebar', 'supplyLayoutDefaults')(layoutIn, layoutOut);
Registry.getComponentMethod('shapes', 'supplyDrawNewShapeDefaults')(layoutIn, layoutOut, coerce);
Registry.getComponentMethod('selections', 'supplyDrawNewSelectionDefaults')(layoutIn, layoutOut, coerce);
coerce('meta');
// do not include defaults in fullLayout when users do not set transition
if (Lib.isPlainObject(layoutIn.transition)) {
coerce('transition.duration');
coerce('transition.easing');
coerce('transition.ordering');
}
Registry.getComponentMethod('calendars', 'handleDefaults')(layoutIn, layoutOut, 'calendar');
Registry.getComponentMethod('fx', 'supplyLayoutGlobalDefaults')(layoutIn, layoutOut, coerce);
Lib.coerce(layoutIn, layoutOut, scatterAttrs, 'scattermode');
};
function getComputedSize(attr) {
return typeof attr === 'string' && attr.substr(attr.length - 2) === 'px' && parseFloat(attr);
}
plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) {
var context = gd._context || {};
var frameMargins = context.frameMargins;
var newWidth;
var newHeight;
var isPlotDiv = Lib.isPlotDiv(gd);
if (isPlotDiv) gd.emit('plotly_autosize');
// embedded in an iframe - just take the full iframe size
// if we get to this point, with no aspect ratio restrictions
if (context.fillFrame) {
newWidth = window.innerWidth;
newHeight = window.innerHeight;
// somehow we get a few extra px height sometimes...
// just hide it
document.body.style.overflow = 'hidden';
} else {
// plotly.js - let the developers do what they want, either
// provide height and width for the container div,
// specify size in layout, or take the defaults,
// but don't enforce any ratio restrictions
var computedStyle = isPlotDiv ? window.getComputedStyle(gd) : {};
newWidth = getComputedSize(computedStyle.width) || getComputedSize(computedStyle.maxWidth) || fullLayout.width;
newHeight = getComputedSize(computedStyle.height) || getComputedSize(computedStyle.maxHeight) || fullLayout.height;
if (isNumeric(frameMargins) && frameMargins > 0) {
var factor = 1 - 2 * frameMargins;
newWidth = Math.round(factor * newWidth);
newHeight = Math.round(factor * newHeight);
}
}
var minWidth = plots.layoutAttributes.width.min;
var minHeight = plots.layoutAttributes.height.min;
if (newWidth < minWidth) newWidth = minWidth;
if (newHeight < minHeight) newHeight = minHeight;
var widthHasChanged = !layout.width && Math.abs(fullLayout.width - newWidth) > 1;
var heightHasChanged = !layout.height && Math.abs(fullLayout.height - newHeight) > 1;
if (heightHasChanged || widthHasChanged) {
if (widthHasChanged) fullLayout.width = newWidth;
if (heightHasChanged) fullLayout.height = newHeight;
}
// cache initial autosize value, used in relayout when
// width or height values are set to null
if (!gd._initialAutoSize) {
gd._initialAutoSize = {
width: newWidth,
height: newHeight
};
}
plots.sanitizeMargins(fullLayout);
};
plots.supplyLayoutModuleDefaults = function (layoutIn, layoutOut, fullData, transitionData) {
var componentsRegistry = Registry.componentsRegistry;
var basePlotModules = layoutOut._basePlotModules;
var component, i, _module;
var Cartesian = Registry.subplotsRegistry.cartesian;
// check if any components need to add more base plot modules
// that weren't captured by traces
for (component in componentsRegistry) {
_module = componentsRegistry[component];
if (_module.includeBasePlot) {
_module.includeBasePlot(layoutIn, layoutOut);
}
}
// make sure we *at least* have some cartesian axes
if (!basePlotModules.length) {
basePlotModules.push(Cartesian);
}
// ensure all cartesian axes have at least one subplot
if (layoutOut._has('cartesian')) {
Registry.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut);
Cartesian.finalizeSubplots(layoutIn, layoutOut);
}
// sort subplot lists
for (var subplotType in layoutOut._subplots) {
layoutOut._subplots[subplotType].sort(Lib.subplotSort);
}
// base plot module layout defaults
for (i = 0; i < basePlotModules.length; i++) {
_module = basePlotModules[i];
// e.g. pie does not have a layout-defaults step
if (_module.supplyLayoutDefaults) {
_module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
}
}
// trace module layout defaults
// use _modules rather than _visibleModules so that even
// legendonly traces can include settings - eg barmode, which affects
// legend.traceorder default value.
var modules = layoutOut._modules;
for (i = 0; i < modules.length; i++) {
_module = modules[i];
if (_module.supplyLayoutDefaults) {
_module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
}
}
// transform module layout defaults
var transformModules = layoutOut._transformModules;
for (i = 0; i < transformModules.length; i++) {
_module = transformModules[i];
if (_module.supplyLayoutDefaults) {
_module.supplyLayoutDefaults(layoutIn, layoutOut, fullData, transitionData);
}
}
for (component in componentsRegistry) {
_module = componentsRegistry[component];
if (_module.supplyLayoutDefaults) {
_module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
}
}
};
// Remove all plotly attributes from a div so it can be replotted fresh
// TODO: these really need to be encapsulated into a much smaller set...
plots.purge = function (gd) {
// note: we DO NOT remove _context because it doesn't change when we insert
// a new plot, and may have been set outside of our scope.
var fullLayout = gd._fullLayout || {};
if (fullLayout._glcontainer !== undefined) {
fullLayout._glcontainer.selectAll('.gl-canvas').remove();
fullLayout._glcontainer.remove();
fullLayout._glcanvas = null;
}
// remove modebar
if (fullLayout._modeBar) fullLayout._modeBar.destroy();
if (gd._transitionData) {
// Ensure any dangling callbacks are simply dropped if the plot is purged.
// This is more or less only actually important for testing.
if (gd._transitionData._interruptCallbacks) {
gd._transitionData._interruptCallbacks.length = 0;
}
if (gd._transitionData._animationRaf) {
window.cancelAnimationFrame(gd._transitionData._animationRaf);
}
}
// remove any planned throttles
Lib.clearThrottle();
// remove responsive handler
Lib.clearResponsive(gd);
// data and layout
delete gd.data;
delete gd.layout;
delete gd._fullData;
delete gd._fullLayout;
delete gd.calcdata;
delete gd.empty;
delete gd.fid;
delete gd.undoqueue; // action queue
delete gd.undonum;
delete gd.autoplay; // are we doing an action that doesn't go in undo queue?
delete gd.changed;
// these get recreated on _doPlot anyway, but just to be safe
// (and to have a record of them...)
delete gd._promises;
delete gd._redrawTimer;
delete gd._hmlumcount;
delete gd._hmpixcount;
delete gd._transitionData;
delete gd._transitioning;
delete gd._initialAutoSize;
delete gd._transitioningWithDuration;
// created during certain events, that *should* clean them up
// themselves, but may not if there was an error
delete gd._dragging;
delete gd._dragged;
delete gd._dragdata;
delete gd._hoverdata;
delete gd._snapshotInProgress;
delete gd._editing;
delete gd._mouseDownTime;
delete gd._legendMouseDownTime;
// remove all event listeners
if (gd.removeAllListeners) gd.removeAllListeners();
};
plots.style = function (gd) {
var _modules = gd._fullLayout._visibleModules;
var styleModules = [];
var i;
// some trace modules reuse the same style method,
// make sure to not unnecessary call them multiple times.
for (i = 0; i < _modules.length; i++) {
var _module = _modules[i];
if (_module.style) {
Lib.pushUnique(styleModules, _module.style);
}
}
for (i = 0; i < styleModules.length; i++) {
styleModules[i](gd);
}
};
plots.sanitizeMargins = function (fullLayout) {
// polar doesn't do margins...
if (!fullLayout || !fullLayout.margin) return;
var width = fullLayout.width;
var height = fullLayout.height;
var margin = fullLayout.margin;
var plotWidth = width - (margin.l + margin.r);
var plotHeight = height - (margin.t + margin.b);
var correction;
// if margin.l + margin.r = 0 then plotWidth > 0
// as width >= 10 by supplyDefaults
// similarly for margin.t + margin.b
if (plotWidth < 0) {
correction = (width - 1) / (margin.l + margin.r);
margin.l = Math.floor(correction * margin.l);
margin.r = Math.floor(correction * margin.r);
}
if (plotHeight < 0) {
correction = (height - 1) / (margin.t + margin.b);
margin.t = Math.floor(correction * margin.t);
margin.b = Math.floor(correction * margin.b);
}
};
plots.clearAutoMarginIds = function (gd) {
gd._fullLayout._pushmarginIds = {};
};
plots.allowAutoMargin = function (gd, id) {
gd._fullLayout._pushmarginIds[id] = 1;
};
function initMargins(fullLayout) {
var margin = fullLayout.margin;
if (!fullLayout._size) {
var gs = fullLayout._size = {
l: Math.round(margin.l),
r: Math.round(margin.r),
t: Math.round(margin.t),
b: Math.round(margin.b),
p: Math.round(margin.pad)
};
gs.w = Math.round(fullLayout.width) - gs.l - gs.r;
gs.h = Math.round(fullLayout.height) - gs.t - gs.b;
}
if (!fullLayout._pushmargin) fullLayout._pushmargin = {};
if (!fullLayout._pushmarginIds) fullLayout._pushmarginIds = {};
if (!fullLayout._reservedMargin) fullLayout._reservedMargin = {};
}
// non-negotiable - this is the smallest height we will allow users to specify via explicit margins
var MIN_SPECIFIED_WIDTH = 2;
var MIN_SPECIFIED_HEIGHT = 2;
/**
* autoMargin: called by components that may need to expand the margins to
* be rendered on-plot.
*
* @param {DOM element} gd
* @param {string} id - an identifier unique (within this plot) to this object,
* so we can remove a previous margin expansion from the same object.
* @param {object} o - the margin requirements of this object, or omit to delete
* this entry (like if it's hidden). Keys are:
* x, y: plot fraction of the anchor point.
* xl, xr, yt, yb: if the object has an extent defined in plot fraction,
* you can specify both edges as plot fractions in each dimension
* l, r, t, b: the pixels to pad past the plot fraction x[l|r] and y[t|b]
* pad: extra pixels to add in all directions, default 12 (why?)
*/
plots.autoMargin = function (gd, id, o) {
var fullLayout = gd._fullLayout;
var width = fullLayout.width;
var height = fullLayout.height;
var margin = fullLayout.margin;
var minreducedwidth = fullLayout.minreducedwidth;
var minreducedheight = fullLayout.minreducedheight;
var minFinalWidth = Lib.constrain(width - margin.l - margin.r, MIN_SPECIFIED_WIDTH, minreducedwidth);
var minFinalHeight = Lib.constrain(height - margin.t - margin.b, MIN_SPECIFIED_HEIGHT, minreducedheight);
var maxSpaceW = Math.max(0, width - minFinalWidth);
var maxSpaceH = Math.max(0, height - minFinalHeight);
var pushMargin = fullLayout._pushmargin;
var pushMarginIds = fullLayout._pushmarginIds;
if (margin.autoexpand !== false) {
if (!o) {
delete pushMargin[id];
delete pushMarginIds[id];
} else {
var pad = o.pad;
if (pad === undefined) {
// if no explicit pad is given, use 12px unless there's a
// specified margin that's smaller than that
pad = Math.min(12, margin.l, margin.r, margin.t, margin.b);
}
// if the item is too big, just give it enough automargin to
// make sure you can still grab it and bring it back
if (maxSpaceW) {
var rW = (o.l + o.r) / maxSpaceW;
if (rW > 1) {
o.l /= rW;
o.r /= rW;
}
}
if (maxSpaceH) {
var rH = (o.t + o.b) / maxSpaceH;
if (rH > 1) {
o.t /= rH;
o.b /= rH;
}
}
var xl = o.xl !== undefined ? o.xl : o.x;
var xr = o.xr !== undefined ? o.xr : o.x;
var yt = o.yt !== undefined ? o.yt : o.y;
var yb = o.yb !== undefined ? o.yb : o.y;
pushMargin[id] = {
l: {
val: xl,
size: o.l + pad
},
r: {
val: xr,
size: o.r + pad
},
b: {
val: yb,
size: o.b + pad
},
t: {
val: yt,
size: o.t + pad
}
};
pushMarginIds[id] = 1;
}
if (!fullLayout._replotting) {
return plots.doAutoMargin(gd);
}
}
};
function needsRedrawForShift(gd) {
if ('_redrawFromAutoMarginCount' in gd._fullLayout) {
return false;
}
var axList = axisIDs.list(gd, '', true);
for (var ax in axList) {
if (axList[ax].autoshift || axList[ax].shift) return true;
}
return false;
}
plots.doAutoMargin = function (gd) {
var fullLayout = gd._fullLayout;
var width = fullLayout.width;
var height = fullLayout.height;
if (!fullLayout._size) fullLayout._size = {};
initMargins(fullLayout);
var gs = fullLayout._size;
var margin = fullLayout.margin;
var reservedMargins = {
t: 0,
b: 0,
l: 0,
r: 0
};
var oldMargins = Lib.extendFlat({}, gs);
// adjust margins for outside components
// fullLayout.margin is the requested margin,
// fullLayout._size has margins and plotsize after adjustment
var ml = margin.l;
var mr = margin.r;
var mt = margin.t;
var mb = margin.b;
var pushMargin = fullLayout._pushmargin;
var pushMarginIds = fullLayout._pushmarginIds;
var minreducedwidth = fullLayout.minreducedwidth;
var minreducedheight = fullLayout.minreducedheight;
if (margin.autoexpand !== false) {
for (var k in pushMargin) {
if (!pushMarginIds[k]) delete pushMargin[k];
}
var margins = gd._fullLayout._reservedMargin;
for (var key in margins) {
for (var side in margins[key]) {
var val = margins[key][side];
reservedMargins[side] = Math.max(reservedMargins[side], val);
}
}
// fill in the requested margins
pushMargin.base = {
l: {
val: 0,
size: ml
},
r: {
val: 1,
size: mr
},
t: {
val: 1,
size: mt
},
b: {
val: 0,
size: mb
}
};
// make sure that the reservedMargin is the minimum needed
for (var s in reservedMargins) {
var autoMarginPush = 0;
for (var m in pushMargin) {
if (m !== 'base') {
if (isNumeric(pushMargin[m][s].size)) {
autoMarginPush = pushMargin[m][s].size > autoMarginPush ? pushMargin[m][s].size : autoMarginPush;
}
}
}
var extraMargin = Math.max(0, margin[s] - autoMarginPush);
reservedMargins[s] = Math.max(0, reservedMargins[s] - extraMargin);
}
// now cycle through all the combinations of l and r
// (and t and b) to find the required margins
for (var k1 in pushMargin) {
var pushleft = pushMargin[k1].l || {};
var pushbottom = pushMargin[k1].b || {};
var fl = pushleft.val;
var pl = pushleft.size;
var fb = pushbottom.val;
var pb = pushbottom.size;
var availableWidth = width - reservedMargins.r - reservedMargins.l;
var availableHeight = height - reservedMargins.t - reservedMargins.b;
for (var k2 in pushMargin) {
if (isNumeric(pl) && pushMargin[k2].r) {
var fr = pushMargin[k2].r.val;
var pr = pushMargin[k2].r.size;
if (fr > fl) {
var newL = (pl * fr + (pr - availableWidth) * fl) / (fr - fl);
var newR = (pr * (1 - fl) + (pl - availableWidth) * (1 - fr)) / (fr - fl);
if (newL + newR > ml + mr) {
ml = newL;
mr = newR;
}
}
}
if (isNumeric(pb) && pushMargin[k2].t) {
var ft = pushMargin[k2].t.val;
var pt = pushMargin[k2].t.size;
if (ft > fb) {
var newB = (pb * ft + (pt - availableHeight) * fb) / (ft - fb);
var newT = (pt * (1 - fb) + (pb - availableHeight) * (1 - ft)) / (ft - fb);
if (newB + newT > mb + mt) {
mb = newB;
mt = newT;
}
}
}
}
}
}
var minFinalWidth = Lib.constrain(width - margin.l - margin.r, MIN_SPECIFIED_WIDTH, minreducedwidth);
var minFinalHeight = Lib.constrain(height - margin.t - margin.b, MIN_SPECIFIED_HEIGHT, minreducedheight);
var maxSpaceW = Math.max(0, width - minFinalWidth);
var maxSpaceH = Math.max(0, height - minFinalHeight);
if (maxSpaceW) {
var rW = (ml + mr) / maxSpaceW;
if (rW > 1) {
ml /= rW;
mr /= rW;
}
}
if (maxSpaceH) {
var rH = (mb + mt) / maxSpaceH;
if (rH > 1) {
mb /= rH;
mt /= rH;
}
}
gs.l = Math.round(ml) + reservedMargins.l;
gs.r = Math.round(mr) + reservedMargins.r;
gs.t = Math.round(mt) + reservedMargins.t;
gs.b = Math.round(mb) + reservedMargins.b;
gs.p = Math.round(margin.pad);
gs.w = Math.round(width) - gs.l - gs.r;
gs.h = Math.round(height) - gs.t - gs.b;
// if things changed and we're not already redrawing, trigger a redraw
if (!fullLayout._replotting && (plots.didMarginChange(oldMargins, gs) || needsRedrawForShift(gd))) {
if ('_redrawFromAutoMarginCount' in fullLayout) {
fullLayout._redrawFromAutoMarginCount++;
} else {
fullLayout._redrawFromAutoMarginCount = 1;
}
// Always allow at least one redraw and give each margin-push
// call 3 loops to converge. Of course, for most cases this way too many,
// but let's keep things on the safe side until we fix our
// auto-margin pipeline problems:
// https://github.com/plotly/plotly.js/issues/2704
var maxNumberOfRedraws = 3 * (1 + Object.keys(pushMarginIds).length);
if (fullLayout._redrawFromAutoMarginCount < maxNumberOfRedraws) {
return Registry.call('_doPlot', gd);
} else {
fullLayout._size = oldMargins;
Lib.warn('Too many auto-margin redraws.');
}
}
refineTicks(gd);
};
function refineTicks(gd) {
var axList = axisIDs.list(gd, '', true);
['_adjustTickLabelsOverflow', '_hideCounterAxisInsideTickLabels'].forEach(function (k) {
for (var i = 0; i < axList.length; i++) {
var hideFn = axList[i][k];
if (hideFn) hideFn();
}
});
}
var marginKeys = ['l', 'r', 't', 'b', 'p', 'w', 'h'];
plots.didMarginChange = function (margin0, margin1) {
for (var i = 0; i < marginKeys.length; i++) {
var k = marginKeys[i];
var m0 = margin0[k];
var m1 = margin1[k];
// use 1px tolerance in case we old/new differ only
// by rounding errors, which can lead to infinite loops
if (!isNumeric(m0) || Math.abs(m1 - m0) > 1) {
return true;
}
}
return false;
};
/**
* JSONify the graph data and layout
*
* This function needs to recurse because some src can be inside
* sub-objects.
*
* It also strips out functions and private (starts with _) elements.
* Therefore, we can add temporary things to data and layout that don't
* get saved.
*
* @param gd The graphDiv
* @param {Boolean} dataonly If true, don't return layout.
* @param {'keepref'|'keepdata'|'keepall'} [mode='keepref'] Filter what's kept
* keepref: remove data for which there's a src present
* eg if there's xsrc present (and xsrc is well-formed,
* ie has : and some chars before it), strip out x
* keepdata: remove all src tags, don't remove the data itself
* keepall: keep data and src
* @param {String} output If you specify 'object', the result will not be stringified
* @param {Boolean} useDefaults If truthy, use _fullLayout and _fullData
* @param {Boolean} includeConfig If truthy, include _context
* @returns {Object|String}
*/
plots.graphJson = function (gd, dataonly, mode, output, useDefaults, includeConfig) {
// if the defaults aren't supplied yet, we need to do that...
if (useDefaults && dataonly && !gd._fullData || useDefaults && !dataonly && !gd._fullLayout) {
plots.supplyDefaults(gd);
}
var data = useDefaults ? gd._fullData : gd.data;
var layout = useDefaults ? gd._fullLayout : gd.layout;
var frames = (gd._transitionData || {})._frames;
function stripObj(d, keepFunction) {
if (typeof d === 'function') {
return keepFunction ? '_function_' : null;
}
if (Lib.isPlainObject(d)) {
var o = {};
var src;
Object.keys(d).sort().forEach(function (v) {
// remove private elements and functions
// _ is for private, [ is a mistake ie [object Object]
if (['_', '['].indexOf(v.charAt(0)) !== -1) return;
// if a function, add if necessary then move on
if (typeof d[v] === 'function') {
if (keepFunction) o[v] = '_function';
return;
}
// look for src/data matches and remove the appropriate one
if (mode === 'keepdata') {
// keepdata: remove all ...src tags
if (v.substr(v.length - 3) === 'src') {
return;
}
} else if (mode === 'keepstream') {
// keep sourced data if it's being streamed.
// similar to keepref, but if the 'stream' object exists
// in a trace, we will keep the data array.
src = d[v + 'src'];
if (typeof src === 'string' && src.indexOf(':') > 0) {
if (!Lib.isPlainObject(d.stream)) {
return;
}
}
} else if (mode !== 'keepall') {
// keepref: remove sourced data but only
// if the source tag is well-formed
src = d[v + 'src'];
if (typeof src === 'string' && src.indexOf(':') > 0) {
return;
}
}
// OK, we're including this... recurse into it
o[v] = stripObj(d[v], keepFunction);
});
return o;
}
var dIsArray = Array.isArray(d);
var dIsTypedArray = Lib.isTypedArray(d);
if ((dIsArray || dIsTypedArray) && d.dtype && d.shape) {
var bdata = d.bdata;
return stripObj({
dtype: d.dtype,
shape: d.shape,
bdata:
// case of ArrayBuffer
Lib.isArrayBuffer(bdata) ? b64encode.encode(bdata) :
// case of b64 string
bdata
}, keepFunction);
}
if (dIsArray) {
return d.map(function (x) {
return stripObj(x, keepFunction);
});
}
if (dIsTypedArray) {
return Lib.simpleMap(d, Lib.identity);
}
// convert native dates to date strings...
// mostly for external users exporting to plotly
if (Lib.isJSDate(d)) return Lib.ms2DateTimeLocal(+d);
return d;
}
var obj = {
data: (data || []).map(function (v) {
var d = stripObj(v);
// fit has some little arrays in it that don't contain data,
// just fit params and meta
if (dataonly) {
delete d.fit;
}
return d;
})
};
if (!dataonly) {
obj.layout = stripObj(layout);
if (useDefaults) {
var gs = layout._size;
obj.layout.computed = {
margin: {
b: gs.b,
l: gs.l,
r: gs.r,
t: gs.t
}
};
}
}
if (frames) obj.frames = stripObj(frames);
if (includeConfig) obj.config = stripObj(gd._context, true);
return output === 'object' ? obj : JSON.stringify(obj);
};
/**
* Modify a keyframe using a list of operations:
*
* @param {array of objects} operations
* Sequence of operations to be performed on the keyframes
*/
plots.modifyFrames = function (gd, operations) {
var i, op, frame;
var _frames = gd._transitionData._frames;
var _frameHash = gd._transitionData._frameHash;
for (i = 0; i < operations.length; i++) {
op = operations[i];
switch (op.type) {
// No reason this couldn't exist, but is currently unused/untested:
/* case 'rename':
frame = _frames[op.index];
delete _frameHash[frame.name];
_frameHash[op.name] = frame;
frame.name = op.name;
break;*/
case 'replace':
frame = op.value;
var oldName = (_frames[op.index] || {}).name;
var newName = frame.name;
_frames[op.index] = _frameHash[newName] = frame;
if (newName !== oldName) {
// If name has changed in addition to replacement, then update
// the lookup table:
delete _frameHash[oldName];
_frameHash[newName] = frame;
}
break;
case 'insert':
frame = op.value;
_frameHash[frame.name] = frame;
_frames.splice(op.index, 0, frame);
break;
case 'delete':
frame = _frames[op.index];
delete _frameHash[frame.name];
_frames.splice(op.index, 1);
break;
}
}
return Promise.resolve();
};
/*
* Compute a keyframe. Merge a keyframe into its base frame(s) and
* expand properties.
*
* @param {object} frameLookup
* An object containing frames keyed by name (i.e. gd._transitionData._frameHash)
* @param {string} frame
* The name of the keyframe to be computed
*
* Returns: a new object with the merged content
*/
plots.computeFrame = function (gd, frameName) {
var frameLookup = gd._transitionData._frameHash;
var i, traceIndices, traceIndex, destIndex;
// Null or undefined will fail on .toString(). We'll allow numbers since we
// make it clear frames must be given string names, but we'll allow numbers
// here since they're otherwise fine for looking up frames as long as they're
// properly cast to strings. We really just want to ensure here that this
// 1) doesn't fail, and
// 2) doens't give an incorrect answer (which String(frameName) would)
if (!frameName) {
throw new Error('computeFrame must be given a string frame name');
}
var framePtr = frameLookup[frameName.toString()];
// Return false if the name is invalid:
if (!framePtr) {
return false;
}
var frameStack = [framePtr];
var frameNameStack = [framePtr.name];
// Follow frame pointers:
while (framePtr.baseframe && (framePtr = frameLookup[framePtr.baseframe.toString()])) {
// Avoid infinite loops:
if (frameNameStack.indexOf(framePtr.name) !== -1) break;
frameStack.push(framePtr);
frameNameStack.push(framePtr.name);
}
// A new object for the merged result:
var result = {};
// Merge, starting with the last and ending with the desired frame:
while (framePtr = frameStack.pop()) {
if (framePtr.layout) {
result.layout = plots.extendLayout(result.layout, framePtr.layout);
}
if (framePtr.data) {
if (!result.data) {
result.data = [];
}
traceIndices = framePtr.traces;
if (!traceIndices) {
// If not defined, assume serial order starting at zero
traceIndices = [];
for (i = 0; i < framePtr.data.length; i++) {
traceIndices[i] = i;
}
}
if (!result.traces) {
result.traces = [];
}
for (i = 0; i < framePtr.data.length; i++) {
// Loop through this frames data, find out where it should go,
// and merge it!
traceIndex = traceIndices[i];
if (traceIndex === undefined || traceIndex === null) {
continue;
}
destIndex = result.traces.indexOf(traceIndex);
if (destIndex === -1) {
destIndex = result.data.length;
result.traces[destIndex] = traceIndex;
}
result.data[destIndex] = plots.extendTrace(result.data[destIndex], framePtr.data[i]);
}
}
}
return result;
};
/*
* Recompute the lookup table that maps frame name -> frame object. addFrames/
* deleteFrames already manages this data one at a time, so the only time this
* is necessary is if you poke around manually in `gd._transitionData._frames`
* and create and haven't updated the lookup table.
*/
plots.recomputeFrameHash = function (gd) {
var hash = gd._transitionData._frameHash = {};
var frames = gd._transitionData._frames;
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
if (frame && frame.name) {
hash[frame.name] = frame;
}
}
};
/**
* Extend an object, treating container arrays very differently by extracting
* their contents and merging them separately.
*
* This exists so that we can extendDeepNoArrays and avoid stepping into data
* arrays without knowledge of the plot schema, but so that we may also manually
* recurse into known container arrays, such as transforms.
*
* See extendTrace and extendLayout below for usage.
*/
plots.extendObjectWithContainers = function (dest, src, containerPaths) {
var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer;
var copy = Lib.extendDeepNoArrays({}, src || {});
var expandedObj = Lib.expandObjectPaths(copy);
var containerObj = {};
// Step through and extract any container properties. Otherwise extendDeepNoArrays
// will clobber any existing properties with an empty array and then supplyDefaults
// will reset everything to defaults.
if (containerPaths && containerPaths.length) {
for (i = 0; i < containerPaths.length; i++) {
containerProp = Lib.nestedProperty(expandedObj, containerPaths[i]);
containerVal = containerProp.get();
if (containerVal === undefined) {
Lib.nestedProperty(containerObj, containerPaths[i]).set(null);
} else {
containerProp.set(null);
Lib.nestedProperty(containerObj, containerPaths[i]).set(containerVal);
}
}
}
dest = Lib.extendDeepNoArrays(dest || {}, expandedObj);
if (containerPaths && containerPaths.length) {
for (i = 0; i < containerPaths.length; i++) {
srcProp = Lib.nestedProperty(containerObj, containerPaths[i]);
srcContainer = srcProp.get();
if (!srcContainer) continue;
destProp = Lib.nestedProperty(dest, containerPaths[i]);
destContainer = destProp.get();
if (!Array.isArray(destContainer)) {
destContainer = [];
destProp.set(destContainer);
}
for (j = 0; j < srcContainer.length; j++) {
var srcObj = srcContainer[j];
if (srcObj === null) destContainer[j] = null;else {
destContainer[j] = plots.extendObjectWithContainers(destContainer[j], srcObj);
}
}
destProp.set(destContainer);
}
}
return dest;
};
plots.dataArrayContainers = ['transforms', 'dimensions'];
plots.layoutArrayContainers = Registry.layoutArrayContainers;
/*
* Extend a trace definition. This method:
*
* 1. directly transfers any array references
* 2. manually recurses into container arrays like transforms
*
* The result is the original object reference with the new contents merged in.
*/
plots.extendTrace = function (destTrace, srcTrace) {
return plots.extendObjectWithContainers(destTrace, srcTrace, plots.dataArrayContainers);
};
/*
* Extend a layout definition. This method:
*
* 1. directly transfers any array references (not critically important for
* layout since there aren't really data arrays)
* 2. manually recurses into container arrays like annotations
*
* The result is the original object reference with the new contents merged in.
*/
plots.extendLayout = function (destLayout, srcLayout) {
return plots.extendObjectWithContainers(destLayout, srcLayout, plots.layoutArrayContainers);
};
/**
* Transition to a set of new data and layout properties from Plotly.animate
*
* @param {DOM element} gd
* @param {Object[]} data
* an array of data objects following the normal Plotly data definition format
* @param {Object} layout
* a layout object, following normal Plotly layout format
* @param {Number[]} traces
* indices of the corresponding traces specified in `data`
* @param {Object} frameOpts
* options for the frame (i.e. whether to redraw post-transition)
* @param {Object} transitionOpts
* options for the transition
*/
plots.transition = function (gd, data, layout, traces, frameOpts, transitionOpts) {
var opts = {
redraw: frameOpts.redraw
};
var transitionedTraces = {};
var axEdits = [];
opts.prepareFn = function () {
var dataLength = Array.isArray(data) ? data.length : 0;
var traceIndices = traces.slice(0, dataLength);
for (var i = 0; i < traceIndices.length; i++) {
var traceIdx = traceIndices[i];
var trace = gd._fullData[traceIdx];
var _module = trace._module;
// There's nothing to do if this module is not defined:
if (!_module) continue;
// Don't register the trace as transitioned if it doesn't know what to do.
// If it *is* registered, it will receive a callback that it's responsible
// for calling in order to register the transition as having completed.
if (_module.animatable) {
var n = _module.basePlotModule.name;
if (!transitionedTraces[n]) transitionedTraces[n] = [];
transitionedTraces[n].push(traceIdx);
}
gd.data[traceIndices[i]] = plots.extendTrace(gd.data[traceIndices[i]], data[i]);
}
// Follow the same procedure. Clone it so we don't mangle the input, then
// expand any object paths so we can merge deep into gd.layout:
var layoutUpdate = Lib.expandObjectPaths(Lib.extendDeepNoArrays({}, layout));
// Before merging though, we need to modify the incoming layout. We only
// know how to *transition* layout ranges, so it's imperative that a new
// range not be sent to the layout before the transition has started. So
// we must remove the things we can transition:
var axisAttrRe = /^[xy]axis[0-9]*$/;
for (var attr in layoutUpdate) {
if (!axisAttrRe.test(attr)) continue;
delete layoutUpdate[attr].range;
}
plots.extendLayout(gd.layout, layoutUpdate);
// Supply defaults after applying the incoming properties. Note that any attempt
// to simplify this step and reduce the amount of work resulted in the reconstruction
// of essentially the whole supplyDefaults step, so that it seems sensible to just use
// supplyDefaults even though it's heavier than would otherwise be desired for
// transitions:
// first delete calcdata so supplyDefaults knows a calc step is coming
delete gd.calcdata;
plots.supplyDefaults(gd);
plots.doCalcdata(gd);
var newLayout = Lib.expandObjectPaths(layout);
if (newLayout) {
var subplots = gd._fullLayout._plots;
for (var k in subplots) {
var plotinfo = subplots[k];
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var xr0 = xa.range.slice();
var yr0 = ya.range.slice();
var xr1 = null;
var yr1 = null;
var editX = null;
var editY = null;
if (Array.isArray(newLayout[xa._name + '.range'])) {
xr1 = newLayout[xa._name + '.range'].slice();
} else if (Array.isArray((newLayout[xa._name] || {}).range)) {
xr1 = newLayout[xa._name].range.slice();
}
if (Array.isArray(newLayout[ya._name + '.range'])) {
yr1 = newLayout[ya._name + '.range'].slice();
} else if (Array.isArray((newLayout[ya._name] || {}).range)) {
yr1 = newLayout[ya._name].range.slice();
}
if (xr0 && xr1 && (xa.r2l(xr0[0]) !== xa.r2l(xr1[0]) || xa.r2l(xr0[1]) !== xa.r2l(xr1[1]))) {
editX = {
xr0: xr0,
xr1: xr1
};
}
if (yr0 && yr1 && (ya.r2l(yr0[0]) !== ya.r2l(yr1[0]) || ya.r2l(yr0[1]) !== ya.r2l(yr1[1]))) {
editY = {
yr0: yr0,
yr1: yr1
};
}
if (editX || editY) {
axEdits.push(Lib.extendFlat({
plotinfo: plotinfo
}, editX, editY));
}
}
}
return Promise.resolve();
};
opts.runFn = function (makeCallback) {
var traceTransitionOpts;
var basePlotModules = gd._fullLayout._basePlotModules;
var hasAxisTransition = axEdits.length;
var i;
if (layout) {
for (i = 0; i < basePlotModules.length; i++) {
if (basePlotModules[i].transitionAxes) {
basePlotModules[i].transitionAxes(gd, axEdits, transitionOpts, makeCallback);
}
}
}
// Here handle the exception that we refuse to animate scales and axes at the same
// time. In other words, if there's an axis transition, then set the data transition
// to instantaneous.
if (hasAxisTransition) {
traceTransitionOpts = Lib.extendFlat({}, transitionOpts);
traceTransitionOpts.duration = 0;
// This means do not transition cartesian traces,
// this happens on layout-only (e.g. axis range) animations
delete transitionedTraces.cartesian;
} else {
traceTransitionOpts = transitionOpts;
}
// Note that we pass a callback to *create* the callback that must be invoked on completion.
// This is since not all traces know about transitions, so it greatly simplifies matters if
// the trace is responsible for creating a callback, if needed, and then executing it when
// the time is right.
for (var n in transitionedTraces) {
var traceIndices = transitionedTraces[n];
var _module = gd._fullData[traceIndices[0]]._module;
_module.basePlotModule.plot(gd, traceIndices, traceTransitionOpts, makeCallback);
}
};
return _transition(gd, transitionOpts, opts);
};
/**
* Transition to a set of new data and layout properties from Plotly.react
*
* @param {DOM element} gd
* @param {object} restyleFlags
* - anim {'all'|'some'}
* @param {object} relayoutFlags
* - anim {'all'|'some'}
* @param {object} oldFullLayout : old (pre Plotly.react) fullLayout
*/
plots.transitionFromReact = function (gd, restyleFlags, relayoutFlags, oldFullLayout) {
var fullLayout = gd._fullLayout;
var transitionOpts = fullLayout.transition;
var opts = {};
var axEdits = [];
opts.prepareFn = function () {
var subplots = fullLayout._plots;
// no need to redraw at end of transition,
// if all changes are animatable
opts.redraw = false;
if (restyleFlags.anim === 'some') opts.redraw = true;
if (relayoutFlags.anim === 'some') opts.redraw = true;
for (var k in subplots) {
var plotinfo = subplots[k];
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var xr0 = oldFullLayout[xa._name].range.slice();
var yr0 = oldFullLayout[ya._name].range.slice();
var xr1 = xa.range.slice();
var yr1 = ya.range.slice();
xa.setScale();
ya.setScale();
var editX = null;
var editY = null;
if (xa.r2l(xr0[0]) !== xa.r2l(xr1[0]) || xa.r2l(xr0[1]) !== xa.r2l(xr1[1])) {
editX = {
xr0: xr0,
xr1: xr1
};
}
if (ya.r2l(yr0[0]) !== ya.r2l(yr1[0]) || ya.r2l(yr0[1]) !== ya.r2l(yr1[1])) {
editY = {
yr0: yr0,
yr1: yr1
};
}
if (editX || editY) {
axEdits.push(Lib.extendFlat({
plotinfo: plotinfo
}, editX, editY));
}
}
return Promise.resolve();
};
opts.runFn = function (makeCallback) {
var fullData = gd._fullData;
var fullLayout = gd._fullLayout;
var basePlotModules = fullLayout._basePlotModules;
var axisTransitionOpts;
var traceTransitionOpts;
var transitionedTraces;
var allTraceIndices = [];
for (var i = 0; i < fullData.length; i++) {
allTraceIndices.push(i);
}
function transitionAxes() {
if (!gd._fullLayout) return;
for (var j = 0; j < basePlotModules.length; j++) {
if (basePlotModules[j].transitionAxes) {
basePlotModules[j].transitionAxes(gd, axEdits, axisTransitionOpts, makeCallback);
}
}
}
function transitionTraces() {
if (!gd._fullLayout) return;
for (var j = 0; j < basePlotModules.length; j++) {
basePlotModules[j].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
}
}
if (axEdits.length && restyleFlags.anim) {
if (transitionOpts.ordering === 'traces first') {
axisTransitionOpts = Lib.extendFlat({}, transitionOpts, {
duration: 0
});
transitionedTraces = allTraceIndices;
traceTransitionOpts = transitionOpts;
setTimeout(transitionAxes, transitionOpts.duration);
transitionTraces();
} else {
axisTransitionOpts = transitionOpts;
transitionedTraces = null;
traceTransitionOpts = Lib.extendFlat({}, transitionOpts, {
duration: 0
});
setTimeout(transitionTraces, axisTransitionOpts.duration);
transitionAxes();
}
} else if (axEdits.length) {
axisTransitionOpts = transitionOpts;
transitionAxes();
} else if (restyleFlags.anim) {
transitionedTraces = allTraceIndices;
traceTransitionOpts = transitionOpts;
transitionTraces();
}
};
return _transition(gd, transitionOpts, opts);
};
/**
* trace/layout transition wrapper that works
* for transitions initiated by Plotly.animate and Plotly.react.
*
* @param {DOM element} gd
* @param {object} transitionOpts
* @param {object} opts
* - redraw {boolean}
* - prepareFn {function} *should return a Promise*
* - runFn {function} ran inside executeTransitions
*/
function _transition(gd, transitionOpts, opts) {
var aborted = false;
function executeCallbacks(list) {
var p = Promise.resolve();
if (!list) return p;
while (list.length) {
p = p.then(list.shift());
}
return p;
}
function flushCallbacks(list) {
if (!list) return;
while (list.length) {
list.shift();
}
}
function executeTransitions() {
gd.emit('plotly_transitioning', []);
return new Promise(function (resolve) {
// This flag is used to disabled things like autorange:
gd._transitioning = true;
// When instantaneous updates are coming through quickly, it's too much to simply disable
// all interaction, so store this flag so we can disambiguate whether mouse interactions
// should be fully disabled or not:
if (transitionOpts.duration > 0) {
gd._transitioningWithDuration = true;
}
// If another transition is triggered, this callback will be executed simply because it's
// in the interruptCallbacks queue. If this transition completes, it will instead flush
// that queue and forget about this callback.
gd._transitionData._interruptCallbacks.push(function () {
aborted = true;
});
if (opts.redraw) {
gd._transitionData._interruptCallbacks.push(function () {
return Registry.call('redraw', gd);
});
}
// Emit this and make sure it happens last:
gd._transitionData._interruptCallbacks.push(function () {
gd.emit('plotly_transitioninterrupted', []);
});
// Construct callbacks that are executed on transition end. This ensures the d3 transitions
// are *complete* before anything else is done.
var numCallbacks = 0;
var numCompleted = 0;
function makeCallback() {
numCallbacks++;
return function () {
numCompleted++;
// When all are complete, perform a redraw:
if (!aborted && numCompleted === numCallbacks) {
completeTransition(resolve);
}
};
}
opts.runFn(makeCallback);
// If nothing else creates a callback, then this will trigger the completion in the next tick:
setTimeout(makeCallback());
});
}
function completeTransition(callback) {
// This a simple workaround for tests which purge the graph before animations
// have completed. That's not a very common case, so this is the simplest
// fix.
if (!gd._transitionData) return;
flushCallbacks(gd._transitionData._interruptCallbacks);
return Promise.resolve().then(function () {
if (opts.redraw) {
return Registry.call('redraw', gd);
}
}).then(function () {
// Set transitioning false again once the redraw has occurred. This is used, for example,
// to prevent the trailing redraw from autoranging:
gd._transitioning = false;
gd._transitioningWithDuration = false;
gd.emit('plotly_transitioned', []);
}).then(callback);
}
function interruptPreviousTransitions() {
// Fail-safe against purged plot:
if (!gd._transitionData) return;
// If a transition is interrupted, set this to false. At the moment, the only thing that would
// interrupt a transition is another transition, so that it will momentarily be set to true
// again, but this determines whether autorange or dragbox work, so it's for the sake of
// cleanliness:
gd._transitioning = false;
return executeCallbacks(gd._transitionData._interruptCallbacks);
}
var seq = [plots.previousPromises, interruptPreviousTransitions, opts.prepareFn, plots.rehover, plots.reselect, executeTransitions];
var transitionStarting = Lib.syncOrAsync(seq, gd);
if (!transitionStarting || !transitionStarting.then) {
transitionStarting = Promise.resolve();
}
return transitionStarting.then(function () {
return gd;
});
}
plots.doCalcdata = function (gd, traces) {
var axList = axisIDs.list(gd);
var fullData = gd._fullData;
var fullLayout = gd._fullLayout;
var trace, _module, i, j;
// XXX: Is this correct? Needs a closer look so that *some* traces can be recomputed without
// *all* needing doCalcdata:
var calcdata = new Array(fullData.length);
var oldCalcdata = (gd.calcdata || []).slice();
gd.calcdata = calcdata;
// extra helper variables
// how many box/violins plots do we have (in case they're grouped)
fullLayout._numBoxes = 0;
fullLayout._numViolins = 0;
// initialize violin per-scale-group stats container
fullLayout._violinScaleGroupStats = {};
// for calculating avg luminosity of heatmaps
gd._hmpixcount = 0;
gd._hmlumcount = 0;
// for sharing colors across pies / sunbursts / treemap / icicle / funnelarea (and for legend)
fullLayout._piecolormap = {};
fullLayout._sunburstcolormap = {};
fullLayout._treemapcolormap = {};
fullLayout._iciclecolormap = {};
fullLayout._funnelareacolormap = {};
// If traces were specified and this trace was not included,
// then transfer it over from the old calcdata:
for (i = 0; i < fullData.length; i++) {
if (Array.isArray(traces) && traces.indexOf(i) === -1) {
calcdata[i] = oldCalcdata[i];
continue;
}
}
for (i = 0; i < fullData.length; i++) {
trace = fullData[i];
trace._arrayAttrs = PlotSchema.findArrayAttributes(trace);
// keep track of trace extremes (for autorange) in here
trace._extremes = {};
}
// add polar axes to axis list
var polarIds = fullLayout._subplots.polar || [];
for (i = 0; i < polarIds.length; i++) {
axList.push(fullLayout[polarIds[i]].radialaxis, fullLayout[polarIds[i]].angularaxis);
}
// clear relinked cmin/cmax values in shared axes to start aggregation from scratch
for (var k in fullLayout._colorAxes) {
var cOpts = fullLayout[k];
if (cOpts.cauto !== false) {
delete cOpts.cmin;
delete cOpts.cmax;
}
}
var hasCalcTransform = false;
function transformCalci(i) {
trace = fullData[i];
_module = trace._module;
if (trace.visible === true && trace.transforms) {
// we need one round of trace module calc before
// the calc transform to 'fill in' the categories list
// used for example in the data-to-coordinate method
if (_module && _module.calc) {
var cdi = _module.calc(gd, trace);
// must clear scene 'batches', so that 2nd
// _module.calc call starts from scratch
if (cdi[0] && cdi[0].t && cdi[0].t._scene) {
delete cdi[0].t._scene.dirty;
}
}
for (j = 0; j < trace.transforms.length; j++) {
var transform = trace.transforms[j];
_module = transformsRegistry[transform.type];
if (_module && _module.calcTransform) {
trace._hasCalcTransform = true;
hasCalcTransform = true;
_module.calcTransform(gd, trace, transform);
}
}
}
}
function calci(i, isContainer) {
trace = fullData[i];
_module = trace._module;
if (!!_module.isContainer !== isContainer) return;
var cd = [];
if (trace.visible === true && trace._length !== 0) {
// clear existing ref in case it got relinked
delete trace._indexToPoints;
// keep ref of index-to-points map object of the *last* enabled transform,
// this index-to-points map object is required to determine the calcdata indices
// that correspond to input indices (e.g. from 'selectedpoints')
var transforms = trace.transforms || [];
for (j = transforms.length - 1; j >= 0; j--) {
if (transforms[j].enabled) {
trace._indexToPoints = transforms[j]._indexToPoints;
break;
}
}
if (_module && _module.calc) {
cd = _module.calc(gd, trace);
}
}
// Make sure there is a first point.
//
// This ensures there is a calcdata item for every trace,
// even if cartesian logic doesn't handle it (for things like legends).
if (!Array.isArray(cd) || !cd[0]) {
cd = [{
x: BADNUM,
y: BADNUM
}];
}
// add the trace-wide properties to the first point,
// per point properties to every point
// t is the holder for trace-wide properties
if (!cd[0].t) cd[0].t = {};
cd[0].trace = trace;
calcdata[i] = cd;
}
setupAxisCategories(axList, fullData, fullLayout);
// 'transform' loop - must calc container traces first
// so that if their dependent traces can get transform properly
for (i = 0; i < fullData.length; i++) calci(i, true);
for (i = 0; i < fullData.length; i++) transformCalci(i);
// clear stuff that should recomputed in 'regular' loop
if (hasCalcTransform) setupAxisCategories(axList, fullData, fullLayout);
// 'regular' loop - make sure container traces (eg carpet) calc before
// contained traces (eg contourcarpet)
for (i = 0; i < fullData.length; i++) calci(i, true);
for (i = 0; i < fullData.length; i++) calci(i, false);
doCrossTraceCalc(gd);
// Sort axis categories per value if specified
var sorted = sortAxisCategoriesByValue(axList, gd);
if (sorted.length) {
// how many box/violins plots do we have (in case they're grouped)
fullLayout._numBoxes = 0;
fullLayout._numViolins = 0;
// If a sort operation was performed, run calc() again
for (i = 0; i < sorted.length; i++) calci(sorted[i], true);
for (i = 0; i < sorted.length; i++) calci(sorted[i], false);
doCrossTraceCalc(gd);
}
Registry.getComponentMethod('fx', 'calc')(gd);
Registry.getComponentMethod('errorbars', 'calc')(gd);
};
var sortAxisCategoriesByValueRegex = /(total|sum|min|max|mean|geometric mean|median) (ascending|descending)/;
function sortAxisCategoriesByValue(axList, gd) {
var affectedTraces = [];
var i, j, k, l, o;
function zMapCategory(type, ax, value) {
var axLetter = ax._id.charAt(0);
if (type === 'histogram2dcontour') {
var counterAxLetter = ax._counterAxes[0];
var counterAx = axisIDs.getFromId(gd, counterAxLetter);
var xCategorical = axLetter === 'x' || counterAxLetter === 'x' && counterAx.type === 'category';
var yCategorical = axLetter === 'y' || counterAxLetter === 'y' && counterAx.type === 'category';
return function (o, l) {
if (o === 0 || l === 0) return -1; // Skip first row and column
if (xCategorical && o === value[l].length - 1) return -1;
if (yCategorical && l === value.length - 1) return -1;
return (axLetter === 'y' ? l : o) - 1;
};
} else {
return function (o, l) {
return axLetter === 'y' ? l : o;
};
}
}
var aggFn = {
min: function (values) {
return Lib.aggNums(Math.min, null, values);
},
max: function (values) {
return Lib.aggNums(Math.max, null, values);
},
sum: function (values) {
return Lib.aggNums(function (a, b) {
return a + b;
}, null, values);
},
total: function (values) {
return Lib.aggNums(function (a, b) {
return a + b;
}, null, values);
},
mean: function (values) {
return Lib.mean(values);
},
'geometric mean': function (values) {
return Lib.geometricMean(values);
},
median: function (values) {
return Lib.median(values);
}
};
function sortAscending(a, b) {
return a[1] - b[1];
}
function sortDescending(a, b) {
return b[1] - a[1];
}
for (i = 0; i < axList.length; i++) {
var ax = axList[i];
if (ax.type !== 'category') continue;
// Order by value
var match = ax.categoryorder.match(sortAxisCategoriesByValueRegex);
if (match) {
var aggregator = match[1];
var order = match[2];
var axLetter = ax._id.charAt(0);
var isX = axLetter === 'x';
// Store values associated with each category
var categoriesValue = [];
for (j = 0; j < ax._categories.length; j++) {
categoriesValue.push([ax._categories[j], []]);
}
// Collect values across traces
for (j = 0; j < ax._traceIndices.length; j++) {
var traceIndex = ax._traceIndices[j];
var fullTrace = gd._fullData[traceIndex];
// Skip over invisible traces
if (fullTrace.visible !== true) continue;
var type = fullTrace.type;
if (Registry.traceIs(fullTrace, 'histogram')) {
delete fullTrace._xautoBinFinished;
delete fullTrace._yautoBinFinished;
}
var isSplom = type === 'splom';
var isScattergl = type === 'scattergl';
var cd = gd.calcdata[traceIndex];
for (k = 0; k < cd.length; k++) {
var cdi = cd[k];
var catIndex, value;
if (isSplom) {
// If `splom`, collect values across dimensions
// Find which dimension the current axis is representing
var currentDimensionIndex = fullTrace._axesDim[ax._id];
// Apply logic to associated x axis if it's defined
if (!isX) {
var associatedXAxisID = fullTrace._diag[currentDimensionIndex][0];
if (associatedXAxisID) ax = gd._fullLayout[axisIDs.id2name(associatedXAxisID)];
}
var categories = cdi.trace.dimensions[currentDimensionIndex].values;
for (l = 0; l < categories.length; l++) {
catIndex = ax._categoriesMap[categories[l]];
// Collect associated values at index `l` over all other dimensions
for (o = 0; o < cdi.trace.dimensions.length; o++) {
if (o === currentDimensionIndex) continue;
var dimension = cdi.trace.dimensions[o];
categoriesValue[catIndex][1].push(dimension.values[l]);
}
}
} else if (isScattergl) {
// If `scattergl`, collect all values stashed under cdi.t
for (l = 0; l < cdi.t.x.length; l++) {
if (isX) {
catIndex = cdi.t.x[l];
value = cdi.t.y[l];
} else {
catIndex = cdi.t.y[l];
value = cdi.t.x[l];
}
categoriesValue[catIndex][1].push(value);
}
// must clear scene 'batches', so that 2nd
// _module.calc call starts from scratch
if (cdi.t && cdi.t._scene) {
delete cdi.t._scene.dirty;
}
} else if (cdi.hasOwnProperty('z')) {
// If 2dMap, collect values in `z`
value = cdi.z;
var mapping = zMapCategory(fullTrace.type, ax, value);
for (l = 0; l < value.length; l++) {
for (o = 0; o < value[l].length; o++) {
catIndex = mapping(o, l);
if (catIndex + 1) categoriesValue[catIndex][1].push(value[l][o]);
}
}
} else {
// For all other 2d cartesian traces
catIndex = cdi.p;
if (catIndex === undefined) catIndex = cdi[axLetter];
value = cdi.s;
if (value === undefined) value = cdi.v;
if (value === undefined) value = isX ? cdi.y : cdi.x;
if (!Array.isArray(value)) {
if (value === undefined) value = [];else value = [value];
}
for (l = 0; l < value.length; l++) {
categoriesValue[catIndex][1].push(value[l]);
}
}
}
}
ax._categoriesValue = categoriesValue;
var categoriesAggregatedValue = [];
for (j = 0; j < categoriesValue.length; j++) {
categoriesAggregatedValue.push([categoriesValue[j][0], aggFn[aggregator](categoriesValue[j][1])]);
}
// Sort by aggregated value
categoriesAggregatedValue.sort(order === 'descending' ? sortDescending : sortAscending);
ax._categoriesAggregatedValue = categoriesAggregatedValue;
// Set new category order
ax._initialCategories = categoriesAggregatedValue.map(function (c) {
return c[0];
});
// Sort all matching axes
affectedTraces = affectedTraces.concat(ax.sortByInitialCategories());
}
}
return affectedTraces;
}
function setupAxisCategories(axList, fullData, fullLayout) {
var axLookup = {};
function setupOne(ax) {
ax.clearCalc();
if (ax.type === 'multicategory') {
ax.setupMultiCategory(fullData);
}
axLookup[ax._id] = 1;
}
Lib.simpleMap(axList, setupOne);
// look into match groups for 'missing' axes
var matchGroups = fullLayout._axisMatchGroups || [];
for (var i = 0; i < matchGroups.length; i++) {
for (var axId in matchGroups[i]) {
if (!axLookup[axId]) {
setupOne(fullLayout[axisIDs.id2name(axId)]);
}
}
}
}
function doCrossTraceCalc(gd) {
var fullLayout = gd._fullLayout;
var modules = fullLayout._visibleModules;
var hash = {};
var i, j, k;
// position and range calculations for traces that
// depend on each other ie bars (stacked or grouped)
// and boxes (grouped) push each other out of the way
for (j = 0; j < modules.length; j++) {
var _module = modules[j];
var fn = _module.crossTraceCalc;
if (fn) {
var spType = _module.basePlotModule.name;
if (hash[spType]) {
Lib.pushUnique(hash[spType], fn);
} else {
hash[spType] = [fn];
}
}
}
for (k in hash) {
var methods = hash[k];
var subplots = fullLayout._subplots[k];
if (Array.isArray(subplots)) {
for (i = 0; i < subplots.length; i++) {
var sp = subplots[i];
var spInfo = k === 'cartesian' ? fullLayout._plots[sp] : fullLayout[sp];
for (j = 0; j < methods.length; j++) {
methods[j](gd, spInfo, sp);
}
}
} else {
for (j = 0; j < methods.length; j++) {
methods[j](gd);
}
}
}
}
plots.rehover = function (gd) {
if (gd._fullLayout._rehover) {
gd._fullLayout._rehover();
}
};
plots.redrag = function (gd) {
if (gd._fullLayout._redrag) {
gd._fullLayout._redrag();
}
};
plots.reselect = function (gd) {
var fullLayout = gd._fullLayout;
var A = (gd.layout || {}).selections;
var B = fullLayout._previousSelections;
fullLayout._previousSelections = A;
var mayEmitSelected = fullLayout._reselect || JSON.stringify(A) !== JSON.stringify(B);
Registry.getComponentMethod('selections', 'reselect')(gd, mayEmitSelected);
};
plots.generalUpdatePerTraceModule = function (gd, subplot, subplotCalcData, subplotLayout) {
var traceHashOld = subplot.traceHash;
var traceHash = {};
var i;
// build up moduleName -> calcData hash
for (i = 0; i < subplotCalcData.length; i++) {
var calcTraces = subplotCalcData[i];
var trace = calcTraces[0].trace;
// skip over visible === false traces
// as they don't have `_module` ref
if (trace.visible) {
traceHash[trace.type] = traceHash[trace.type] || [];
traceHash[trace.type].push(calcTraces);
}
}
// when a trace gets deleted, make sure that its module's
// plot method is called so that it is properly
// removed from the DOM.
for (var moduleNameOld in traceHashOld) {
if (!traceHash[moduleNameOld]) {
var fakeCalcTrace = traceHashOld[moduleNameOld][0];
var fakeTrace = fakeCalcTrace[0].trace;
fakeTrace.visible = false;
traceHash[moduleNameOld] = [fakeCalcTrace];
}
}
// call module plot method
for (var moduleName in traceHash) {
var moduleCalcData = traceHash[moduleName];
var _module = moduleCalcData[0][0].trace._module;
_module.plot(gd, subplot, Lib.filterVisible(moduleCalcData), subplotLayout);
}
// update moduleName -> calcData hash
subplot.traceHash = traceHash;
};
plots.plotBasePlot = function (desiredType, gd, traces, transitionOpts, makeOnCompleteCallback) {
var _module = Registry.getModule(desiredType);
var cdmodule = getModuleCalcData(gd.calcdata, _module)[0];
_module.plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback);
};
plots.cleanBasePlot = function (desiredType, newFullData, newFullLayout, oldFullData, oldFullLayout) {
var had = oldFullLayout._has && oldFullLayout._has(desiredType);
var has = newFullLayout._has && newFullLayout._has(desiredType);
if (had && !has) {
oldFullLayout['_' + desiredType + 'layer'].selectAll('g.trace').remove();
}
};
/***/ }),
/***/ 39360:
/***/ (function(module) {
"use strict";
module.exports = {
attr: 'subplot',
name: 'polar',
axisNames: ['angularaxis', 'radialaxis'],
axisName2dataArray: {
angularaxis: 'theta',
radialaxis: 'r'
},
layerNames: ['draglayer', 'plotbg', 'backplot', 'angular-grid', 'radial-grid', 'frontplot', 'angular-line', 'radial-line', 'angular-axis', 'radial-axis'],
radialDragBoxSize: 50,
angularDragBoxSize: 30,
cornerLen: 25,
cornerHalfWidth: 2,
// pixels to move mouse before you stop clamping to starting point
MINDRAG: 8,
// smallest radial distance [px] allowed for a zoombox
MINZOOM: 20,
// distance [px] off (r=0) or (r=radius) where we transition
// from single-sided to two-sided radial zoom
OFFEDGE: 20
};
/***/ }),
/***/ 57384:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var polygonTester = (__webpack_require__(92065).tester);
var findIndexOfMin = Lib.findIndexOfMin;
var isAngleInsideSector = Lib.isAngleInsideSector;
var angleDelta = Lib.angleDelta;
var angleDist = Lib.angleDist;
/**
* is pt (r,a) inside polygon made up vertices at angles 'vangles'
* inside a given polar sector
*
* @param {number} r : pt's radial coordinate
* @param {number} a : pt's angular coordinate in *radians*
* @param {2-item array} rBnds : sector's radial bounds
* @param {2-item array} aBnds : sector's angular bounds *radians*
* @param {array} vangles : angles of polygon vertices in *radians*
* @return {boolean}
*/
function isPtInsidePolygon(r, a, rBnds, aBnds, vangles) {
if (!isAngleInsideSector(a, aBnds)) return false;
var r0, r1;
if (rBnds[0] < rBnds[1]) {
r0 = rBnds[0];
r1 = rBnds[1];
} else {
r0 = rBnds[1];
r1 = rBnds[0];
}
var polygonIn = polygonTester(makePolygon(r0, aBnds[0], aBnds[1], vangles));
var polygonOut = polygonTester(makePolygon(r1, aBnds[0], aBnds[1], vangles));
var xy = [r * Math.cos(a), r * Math.sin(a)];
return polygonOut.contains(xy) && !polygonIn.contains(xy);
}
// find intersection of 'v0' <-> 'v1' edge with a ray at angle 'a'
// (i.e. a line that starts from the origin at angle 'a')
// given an (xp,yp) pair on the 'v0' <-> 'v1' line
// (N.B. 'v0' and 'v1' are angles in radians)
function findIntersectionXY(v0, v1, a, xpyp) {
var xstar, ystar;
var xp = xpyp[0];
var yp = xpyp[1];
var dsin = clampTiny(Math.sin(v1) - Math.sin(v0));
var dcos = clampTiny(Math.cos(v1) - Math.cos(v0));
var tanA = Math.tan(a);
var cotanA = clampTiny(1 / tanA);
var m = dsin / dcos;
var b = yp - m * xp;
if (cotanA) {
if (dsin && dcos) {
// given
// g(x) := v0 -> v1 line = m*x + b
// h(x) := ray at angle 'a' = m*x = tanA*x
// solve g(xstar) = h(xstar)
xstar = b / (tanA - m);
ystar = tanA * xstar;
} else if (dcos) {
// horizontal v0 -> v1
xstar = yp * cotanA;
ystar = yp;
} else {
// vertical v0 -> v1
xstar = xp;
ystar = xp * tanA;
}
} else {
// vertical ray
if (dsin && dcos) {
xstar = 0;
ystar = b;
} else if (dcos) {
xstar = 0;
ystar = yp;
} else {
// does this case exists?
xstar = ystar = NaN;
}
}
return [xstar, ystar];
}
// solves l^2 = (f(x)^2 - yp)^2 + (x - xp)^2
// rearranged into 0 = a*x^2 + b * x + c
//
// where f(x) = m*x + t + yp
// and (x0, x1) = (-b +/- del) / (2*a)
function findXYatLength(l, m, xp, yp) {
var t = -m * xp;
var a = m * m + 1;
var b = 2 * (m * t - xp);
var c = t * t + xp * xp - l * l;
var del = Math.sqrt(b * b - 4 * a * c);
var x0 = (-b + del) / (2 * a);
var x1 = (-b - del) / (2 * a);
return [[x0, m * x0 + t + yp], [x1, m * x1 + t + yp]];
}
function makeRegularPolygon(r, vangles) {
var len = vangles.length;
var vertices = new Array(len + 1);
var i;
for (i = 0; i < len; i++) {
var va = vangles[i];
vertices[i] = [r * Math.cos(va), r * Math.sin(va)];
}
vertices[i] = vertices[0].slice();
return vertices;
}
function makeClippedPolygon(r, a0, a1, vangles) {
var len = vangles.length;
var vertices = [];
var i, j;
function a2xy(a) {
return [r * Math.cos(a), r * Math.sin(a)];
}
function findXY(va0, va1, s) {
return findIntersectionXY(va0, va1, s, a2xy(va0));
}
function cycleIndex(ind) {
return Lib.mod(ind, len);
}
function isInside(v) {
return isAngleInsideSector(v, [a0, a1]);
}
// find index in sector closest to a0
// use it to find intersection of v[i0] <-> v[i0-1] edge with sector radius
var i0 = findIndexOfMin(vangles, function (v) {
return isInside(v) ? angleDist(v, a0) : Infinity;
});
var xy0 = findXY(vangles[i0], vangles[cycleIndex(i0 - 1)], a0);
vertices.push(xy0);
// fill in in-sector vertices
for (i = i0, j = 0; j < len; i++, j++) {
var va = vangles[cycleIndex(i)];
if (!isInside(va)) break;
vertices.push(a2xy(va));
}
// find index in sector closest to a1,
// use it to find intersection of v[iN] <-> v[iN+1] edge with sector radius
var iN = findIndexOfMin(vangles, function (v) {
return isInside(v) ? angleDist(v, a1) : Infinity;
});
var xyN = findXY(vangles[iN], vangles[cycleIndex(iN + 1)], a1);
vertices.push(xyN);
vertices.push([0, 0]);
vertices.push(vertices[0].slice());
return vertices;
}
function makePolygon(r, a0, a1, vangles) {
return Lib.isFullCircle([a0, a1]) ? makeRegularPolygon(r, vangles) : makeClippedPolygon(r, a0, a1, vangles);
}
function findPolygonOffset(r, a0, a1, vangles) {
var minX = Infinity;
var minY = Infinity;
var vertices = makePolygon(r, a0, a1, vangles);
for (var i = 0; i < vertices.length; i++) {
var v = vertices[i];
minX = Math.min(minX, v[0]);
minY = Math.min(minY, -v[1]);
}
return [minX, minY];
}
/**
* find vertex angles (in 'vangles') the enclose angle 'a'
*
* @param {number} a : angle in *radians*
* @param {array} vangles : angles of polygon vertices in *radians*
* @return {2-item array}
*/
function findEnclosingVertexAngles(a, vangles) {
var minFn = function (v) {
var adelta = angleDelta(v, a);
return adelta > 0 ? adelta : Infinity;
};
var i0 = findIndexOfMin(vangles, minFn);
var i1 = Lib.mod(i0 + 1, vangles.length);
return [vangles[i0], vangles[i1]];
}
// to more easily catch 'almost zero' numbers in if-else blocks
function clampTiny(v) {
return Math.abs(v) > 1e-10 ? v : 0;
}
function transformForSVG(pts0, cx, cy) {
cx = cx || 0;
cy = cy || 0;
var len = pts0.length;
var pts1 = new Array(len);
for (var i = 0; i < len; i++) {
var pt = pts0[i];
pts1[i] = [cx + pt[0], cy - pt[1]];
}
return pts1;
}
/**
* path polygon
*
* @param {number} r : polygon 'radius'
* @param {number} a0 : first angular coordinate in *radians*
* @param {number} a1 : second angular coordinate in *radians*
* @param {array} vangles : angles of polygon vertices in *radians*
* @param {number (optional)} cx : x coordinate of center
* @param {number (optional)} cy : y coordinate of center
* @return {string} svg path
*
*/
function pathPolygon(r, a0, a1, vangles, cx, cy) {
var poly = makePolygon(r, a0, a1, vangles);
return 'M' + transformForSVG(poly, cx, cy).join('L');
}
/**
* path a polygon 'annulus'
* i.e. a polygon with a concentric hole
*
* N.B. this routine uses the evenodd SVG rule
*
* @param {number} r0 : first radial coordinate
* @param {number} r1 : second radial coordinate
* @param {number} a0 : first angular coordinate in *radians*
* @param {number} a1 : second angular coordinate in *radians*
* @param {array} vangles : angles of polygon vertices in *radians*
* @param {number (optional)} cx : x coordinate of center
* @param {number (optional)} cy : y coordinate of center
* @return {string} svg path
*
*/
function pathPolygonAnnulus(r0, r1, a0, a1, vangles, cx, cy) {
var rStart, rEnd;
if (r0 < r1) {
rStart = r0;
rEnd = r1;
} else {
rStart = r1;
rEnd = r0;
}
var inner = transformForSVG(makePolygon(rStart, a0, a1, vangles), cx, cy);
var outer = transformForSVG(makePolygon(rEnd, a0, a1, vangles), cx, cy);
return 'M' + outer.reverse().join('L') + 'M' + inner.join('L');
}
module.exports = {
isPtInsidePolygon: isPtInsidePolygon,
findPolygonOffset: findPolygonOffset,
findEnclosingVertexAngles: findEnclosingVertexAngles,
findIntersectionXY: findIntersectionXY,
findXYatLength: findXYatLength,
clampTiny: clampTiny,
pathPolygon: pathPolygon,
pathPolygonAnnulus: pathPolygonAnnulus
};
/***/ }),
/***/ 40872:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var getSubplotCalcData = (__webpack_require__(84888)/* .getSubplotCalcData */ .KY);
var counterRegex = (__webpack_require__(3400).counterRegex);
var createPolar = __webpack_require__(62400);
var constants = __webpack_require__(39360);
var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);
var attributes = {};
attributes[attr] = {
valType: 'subplotid',
dflt: name,
editType: 'calc'
};
function plot(gd) {
var fullLayout = gd._fullLayout;
var calcData = gd.calcdata;
var subplotIds = fullLayout._subplots[name];
for (var i = 0; i < subplotIds.length; i++) {
var id = subplotIds[i];
var subplotCalcData = getSubplotCalcData(calcData, name, id);
var subplot = fullLayout[id]._subplot;
if (!subplot) {
subplot = createPolar(gd, id);
fullLayout[id]._subplot = subplot;
}
subplot.plot(subplotCalcData, fullLayout, gd._promises);
}
}
function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldIds = oldFullLayout._subplots[name] || [];
var hadGl = oldFullLayout._has && oldFullLayout._has('gl');
var hasGl = newFullLayout._has && newFullLayout._has('gl');
var mustCleanScene = hadGl && !hasGl;
for (var i = 0; i < oldIds.length; i++) {
var id = oldIds[i];
var oldSubplot = oldFullLayout[id]._subplot;
if (!newFullLayout[id] && !!oldSubplot) {
oldSubplot.framework.remove();
oldSubplot.layers['radial-axis-title'].remove();
for (var k in oldSubplot.clipPaths) {
oldSubplot.clipPaths[k].remove();
}
}
if (mustCleanScene && oldSubplot._scene) {
oldSubplot._scene.destroy();
oldSubplot._scene = null;
}
}
}
module.exports = {
attr: attr,
name: name,
idRoot: name,
idRegex: counter,
attrRegex: counter,
attributes: attributes,
layoutAttributes: __webpack_require__(95300),
supplyLayoutDefaults: __webpack_require__(84380),
plot: plot,
clean: clean,
toSVG: (__webpack_require__(57952).toSVG)
};
/***/ }),
/***/ 95300:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorAttrs = __webpack_require__(22548);
var axesAttrs = __webpack_require__(94724);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var extendFlat = (__webpack_require__(3400).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var axisLineGridAttr = overrideAll({
color: axesAttrs.color,
showline: extendFlat({}, axesAttrs.showline, {
dflt: true
}),
linecolor: axesAttrs.linecolor,
linewidth: axesAttrs.linewidth,
showgrid: extendFlat({}, axesAttrs.showgrid, {
dflt: true
}),
gridcolor: axesAttrs.gridcolor,
gridwidth: axesAttrs.gridwidth,
griddash: axesAttrs.griddash
// TODO add spike* attributes down the road
// should we add zeroline* attributes?
}, 'plot', 'from-root');
var axisTickAttrs = overrideAll({
tickmode: axesAttrs.minor.tickmode,
nticks: axesAttrs.nticks,
tick0: axesAttrs.tick0,
dtick: axesAttrs.dtick,
tickvals: axesAttrs.tickvals,
ticktext: axesAttrs.ticktext,
ticks: axesAttrs.ticks,
ticklen: axesAttrs.ticklen,
tickwidth: axesAttrs.tickwidth,
tickcolor: axesAttrs.tickcolor,
ticklabelstep: axesAttrs.ticklabelstep,
showticklabels: axesAttrs.showticklabels,
labelalias: axesAttrs.labelalias,
showtickprefix: axesAttrs.showtickprefix,
tickprefix: axesAttrs.tickprefix,
showticksuffix: axesAttrs.showticksuffix,
ticksuffix: axesAttrs.ticksuffix,
showexponent: axesAttrs.showexponent,
exponentformat: axesAttrs.exponentformat,
minexponent: axesAttrs.minexponent,
separatethousands: axesAttrs.separatethousands,
tickfont: axesAttrs.tickfont,
tickangle: axesAttrs.tickangle,
tickformat: axesAttrs.tickformat,
tickformatstops: axesAttrs.tickformatstops,
layer: axesAttrs.layer
}, 'plot', 'from-root');
var radialAxisAttrs = {
visible: extendFlat({}, axesAttrs.visible, {
dflt: true
}),
type: extendFlat({}, axesAttrs.type, {
values: ['-', 'linear', 'log', 'date', 'category']
}),
autotypenumbers: axesAttrs.autotypenumbers,
autorangeoptions: {
minallowed: axesAttrs.autorangeoptions.minallowed,
maxallowed: axesAttrs.autorangeoptions.maxallowed,
clipmin: axesAttrs.autorangeoptions.clipmin,
clipmax: axesAttrs.autorangeoptions.clipmax,
include: axesAttrs.autorangeoptions.include,
editType: 'plot'
},
autorange: extendFlat({}, axesAttrs.autorange, {
editType: 'plot'
}),
rangemode: {
valType: 'enumerated',
values: ['tozero', 'nonnegative', 'normal'],
dflt: 'tozero',
editType: 'calc'
},
minallowed: extendFlat({}, axesAttrs.minallowed, {
editType: 'plot'
}),
maxallowed: extendFlat({}, axesAttrs.maxallowed, {
editType: 'plot'
}),
range: extendFlat({}, axesAttrs.range, {
items: [{
valType: 'any',
editType: 'plot',
impliedEdits: {
'^autorange': false
}
}, {
valType: 'any',
editType: 'plot',
impliedEdits: {
'^autorange': false
}
}],
editType: 'plot'
}),
categoryorder: axesAttrs.categoryorder,
categoryarray: axesAttrs.categoryarray,
angle: {
valType: 'angle',
editType: 'plot'
},
autotickangles: axesAttrs.autotickangles,
side: {
valType: 'enumerated',
// TODO add 'center' for `showline: false` radial axes
values: ['clockwise', 'counterclockwise'],
dflt: 'clockwise',
editType: 'plot'
},
title: {
// radial title is not gui-editable at the moment,
// so it needs dflt: '', similar to carpet axes.
text: extendFlat({}, axesAttrs.title.text, {
editType: 'plot',
dflt: ''
}),
font: extendFlat({}, axesAttrs.title.font, {
editType: 'plot'
}),
// TODO
// - might need a 'titleside' and even 'titledirection' down the road
// - what about standoff ??
editType: 'plot'
},
hoverformat: axesAttrs.hoverformat,
uirevision: {
valType: 'any',
editType: 'none'
},
editType: 'calc',
_deprecated: {
title: axesAttrs._deprecated.title,
titlefont: axesAttrs._deprecated.titlefont
}
};
extendFlat(radialAxisAttrs,
// N.B. radialaxis grid lines are circular,
// but radialaxis lines are straight from circle center to outer bound
axisLineGridAttr, axisTickAttrs);
var angularAxisAttrs = {
visible: extendFlat({}, axesAttrs.visible, {
dflt: true
}),
type: {
valType: 'enumerated',
// 'linear' should maybe be called 'angle' or 'angular' here
// to make clear that axis here is periodic and more tightly match
// `thetaunit`?
//
// skip 'date' for first push
// no 'log' for now
values: ['-', 'linear', 'category'],
dflt: '-',
editType: 'calc',
_noTemplating: true
},
autotypenumbers: axesAttrs.autotypenumbers,
categoryorder: axesAttrs.categoryorder,
categoryarray: axesAttrs.categoryarray,
thetaunit: {
valType: 'enumerated',
values: ['radians', 'degrees'],
dflt: 'degrees',
editType: 'calc'
},
period: {
valType: 'number',
editType: 'calc',
min: 0
// Examples for date axes:
//
// - period that equals the timeseries length
// http://flowingdata.com/2017/01/24/one-dataset-visualized-25-ways/18-polar-coordinates/
// - and 1-year periods (focusing on seasonal change0
// http://otexts.org/fpp2/seasonal-plots.html
// https://blogs.scientificamerican.com/sa-visual/why-are-so-many-babies-born-around-8-00-a-m/
// http://www.seasonaladjustment.com/2012/09/05/clock-plot-visualising-seasonality-using-r-and-ggplot2-part-3/
// https://i.pinimg.com/736x/49/b9/72/49b972ccb3206a1a6d6f870dac543280.jpg
// https://www.climate-lab-book.ac.uk/spirals/
},
direction: {
valType: 'enumerated',
values: ['counterclockwise', 'clockwise'],
dflt: 'counterclockwise',
editType: 'calc'
},
rotation: {
valType: 'angle',
editType: 'calc'
},
hoverformat: axesAttrs.hoverformat,
uirevision: {
valType: 'any',
editType: 'none'
},
editType: 'calc'
};
extendFlat(angularAxisAttrs,
// N.B. angular grid lines are straight lines from circle center to outer bound
// the angular line is circular bounding the polar plot area.
axisLineGridAttr,
// N.B. ticksuffix defaults to '°' for angular axes with `thetaunit: 'degrees'`
axisTickAttrs);
module.exports = {
// TODO for x/y/zoom system for paper-based zooming:
// x: {},
// y: {},
// zoom: {},
domain: domainAttrs({
name: 'polar',
editType: 'plot'
}),
sector: {
valType: 'info_array',
items: [{
valType: 'number',
editType: 'plot'
}, {
valType: 'number',
editType: 'plot'
}],
dflt: [0, 360],
editType: 'plot'
},
hole: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
editType: 'plot'
},
bgcolor: {
valType: 'color',
editType: 'plot',
dflt: colorAttrs.background
},
radialaxis: radialAxisAttrs,
angularaxis: angularAxisAttrs,
gridshape: {
valType: 'enumerated',
values: ['circular', 'linear'],
dflt: 'circular',
editType: 'plot'
},
// TODO maybe?
// annotations:
uirevision: {
valType: 'any',
editType: 'none'
},
editType: 'calc'
};
/***/ }),
/***/ 84380:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var Template = __webpack_require__(31780);
var handleSubplotDefaults = __webpack_require__(168);
var getSubplotData = (__webpack_require__(84888)/* .getSubplotData */ .op);
var handleTickValueDefaults = __webpack_require__(26332);
var handleTickMarkDefaults = __webpack_require__(25404);
var handleTickLabelDefaults = __webpack_require__(95936);
var handlePrefixSuffixDefaults = __webpack_require__(42568);
var handleCategoryOrderDefaults = __webpack_require__(22416);
var handleLineGridDefaults = __webpack_require__(42136);
var handleAutorangeOptionsDefaults = __webpack_require__(76808);
var autoType = __webpack_require__(52976);
var layoutAttributes = __webpack_require__(95300);
var setConvert = __webpack_require__(57696);
var constants = __webpack_require__(39360);
var axisNames = constants.axisNames;
function handleDefaults(contIn, contOut, coerce, opts) {
var bgColor = coerce('bgcolor');
opts.bgColor = Color.combine(bgColor, opts.paper_bgcolor);
var sector = coerce('sector');
coerce('hole');
// could optimize, subplotData is not always needed!
var subplotData = getSubplotData(opts.fullData, constants.name, opts.id);
var layoutOut = opts.layoutOut;
var axName;
function coerceAxis(attr, dflt) {
return coerce(axName + '.' + attr, dflt);
}
for (var i = 0; i < axisNames.length; i++) {
axName = axisNames[i];
if (!Lib.isPlainObject(contIn[axName])) {
contIn[axName] = {};
}
var axIn = contIn[axName];
var axOut = Template.newContainer(contOut, axName);
axOut._id = axOut._name = axName;
axOut._attr = opts.id + '.' + axName;
axOut._traceIndices = subplotData.map(function (t) {
return t._expandedIndex;
});
var dataAttr = constants.axisName2dataArray[axName];
var axType = handleAxisTypeDefaults(axIn, axOut, coerceAxis, subplotData, dataAttr, opts);
handleCategoryOrderDefaults(axIn, axOut, coerceAxis, {
axData: subplotData,
dataAttr: dataAttr
});
var visible = coerceAxis('visible');
setConvert(axOut, contOut, layoutOut);
coerceAxis('uirevision', contOut.uirevision);
// We don't want to make downstream code call ax.setScale,
// as both radial and angular axes don't have a set domain.
// Furthermore, angular axes don't have a set range.
//
// Mocked domains and ranges are set by the polar subplot instances,
// but Axes.findExtremes uses the sign of _m to determine which padding value
// to use.
//
// By setting, _m to 1 here, we make Axes.findExtremes think that
// range[1] > range[0], and vice-versa for `autorange: 'reversed'` below.
axOut._m = 1;
switch (axName) {
case 'radialaxis':
coerceAxis('minallowed');
coerceAxis('maxallowed');
var range = coerceAxis('range');
var autorangeDflt = axOut.getAutorangeDflt(range);
var autorange = coerceAxis('autorange', autorangeDflt);
var shouldAutorange;
// validate range and set autorange true for invalid partial ranges
if (range && (range[0] === null && range[1] === null || (range[0] === null || range[1] === null) && (autorange === 'reversed' || autorange === true) || range[0] !== null && (autorange === 'min' || autorange === 'max reversed') || range[1] !== null && (autorange === 'max' || autorange === 'min reversed'))) {
range = undefined;
delete axOut.range;
axOut.autorange = true;
shouldAutorange = true;
}
if (!shouldAutorange) {
autorangeDflt = axOut.getAutorangeDflt(range);
autorange = coerceAxis('autorange', autorangeDflt);
}
axIn.autorange = autorange;
if (autorange) {
handleAutorangeOptionsDefaults(coerceAxis, autorange, range);
if (axType === 'linear' || axType === '-') coerceAxis('rangemode');
if (axOut.isReversed()) axOut._m = -1;
}
axOut.cleanRange('range', {
dfltRange: [0, 1]
});
break;
case 'angularaxis':
// We do not support 'true' date angular axes yet,
// users can still plot dates on angular axes by setting
// `angularaxis.type: 'category'`.
//
// Here, if a date angular axes is detected, we make
// all its corresponding traces invisible, so that
// when we do add support for data angular axes, the new
// behavior won't conflict with existing behavior
if (axType === 'date') {
Lib.log('Polar plots do not support date angular axes yet.');
for (var j = 0; j < subplotData.length; j++) {
subplotData[j].visible = false;
}
// turn this into a 'dummy' linear axis so that
// the subplot still renders ok
axType = axIn.type = axOut.type = 'linear';
}
if (axType === 'linear') {
coerceAxis('thetaunit');
} else {
coerceAxis('period');
}
var direction = coerceAxis('direction');
coerceAxis('rotation', {
counterclockwise: 0,
clockwise: 90
}[direction]);
break;
}
handlePrefixSuffixDefaults(axIn, axOut, coerceAxis, axOut.type, {
tickSuffixDflt: axOut.thetaunit === 'degrees' ? '°' : undefined
});
if (visible) {
var dfltColor;
var dfltFontColor;
var dfltFontSize;
var dfltFontFamily;
var dfltFontWeight;
var dfltFontStyle;
var dfltFontVariant;
var dfltFontTextcase;
var dfltFontLineposition;
var dfltFontShadow;
var font = opts.font || {};
dfltColor = coerceAxis('color');
dfltFontColor = dfltColor === axIn.color ? dfltColor : font.color;
dfltFontSize = font.size;
dfltFontFamily = font.family;
dfltFontWeight = font.weight;
dfltFontStyle = font.style;
dfltFontVariant = font.variant;
dfltFontTextcase = font.textcase;
dfltFontLineposition = font.lineposition;
dfltFontShadow = font.shadow;
handleTickValueDefaults(axIn, axOut, coerceAxis, axOut.type);
handleTickLabelDefaults(axIn, axOut, coerceAxis, axOut.type, {
font: {
weight: dfltFontWeight,
style: dfltFontStyle,
variant: dfltFontVariant,
textcase: dfltFontTextcase,
lineposition: dfltFontLineposition,
shadow: dfltFontShadow,
color: dfltFontColor,
size: dfltFontSize,
family: dfltFontFamily
},
noAutotickangles: axName === 'angularaxis',
noTicklabelshift: true,
noTicklabelstandoff: true
});
handleTickMarkDefaults(axIn, axOut, coerceAxis, {
outerTicks: true
});
handleLineGridDefaults(axIn, axOut, coerceAxis, {
dfltColor: dfltColor,
bgColor: opts.bgColor,
// default grid color is darker here (60%, vs cartesian default ~91%)
// because the grid is not square so the eye needs heavier cues to follow
blend: 60,
showLine: true,
showGrid: true,
noZeroLine: true,
attributes: layoutAttributes[axName]
});
coerceAxis('layer');
if (axName === 'radialaxis') {
coerceAxis('side');
coerceAxis('angle', sector[0]);
coerceAxis('title.text');
Lib.coerceFont(coerceAxis, 'title.font', {
weight: dfltFontWeight,
style: dfltFontStyle,
variant: dfltFontVariant,
textcase: dfltFontTextcase,
lineposition: dfltFontLineposition,
shadow: dfltFontShadow,
color: dfltFontColor,
size: Lib.bigFont(dfltFontSize),
family: dfltFontFamily
});
}
}
if (axType !== 'category') coerceAxis('hoverformat');
axOut._input = axIn;
}
if (contOut.angularaxis.type === 'category') {
coerce('gridshape');
}
}
function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr, options) {
var autotypenumbers = coerce('autotypenumbers', options.autotypenumbersDflt);
var axType = coerce('type');
if (axType === '-') {
var trace;
for (var i = 0; i < subplotData.length; i++) {
if (subplotData[i].visible) {
trace = subplotData[i];
break;
}
}
if (trace && trace[dataAttr]) {
axOut.type = autoType(trace[dataAttr], 'gregorian', {
noMultiCategory: true,
autotypenumbers: autotypenumbers
});
}
if (axOut.type === '-') {
axOut.type = 'linear';
} else {
// copy autoType back to input axis
// note that if this object didn't exist
// in the input layout, we have to put it in
// this happens in the main supplyDefaults function
axIn.type = axOut.type;
}
}
return axOut.type;
}
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
handleSubplotDefaults(layoutIn, layoutOut, fullData, {
type: constants.name,
attributes: layoutAttributes,
handleDefaults: handleDefaults,
font: layoutOut.font,
autotypenumbersDflt: layoutOut.autotypenumbers,
paper_bgcolor: layoutOut.paper_bgcolor,
fullData: fullData,
layoutOut: layoutOut
});
};
/***/ }),
/***/ 62400:
/***/ (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 Lib = __webpack_require__(3400);
var strRotate = Lib.strRotate;
var strTranslate = Lib.strTranslate;
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Plots = __webpack_require__(7316);
var Axes = __webpack_require__(54460);
var setConvertCartesian = __webpack_require__(78344);
var setConvertPolar = __webpack_require__(57696);
var doAutoRange = (__webpack_require__(19280).doAutoRange);
var dragBox = __webpack_require__(51184);
var dragElement = __webpack_require__(86476);
var Fx = __webpack_require__(93024);
var Titles = __webpack_require__(81668);
var prepSelect = (__webpack_require__(22676).prepSelect);
var selectOnClick = (__webpack_require__(22676).selectOnClick);
var clearOutline = (__webpack_require__(22676).clearOutline);
var setCursor = __webpack_require__(93972);
var clearGlCanvases = __webpack_require__(73696);
var redrawReglTraces = (__webpack_require__(39172).redrawReglTraces);
var MID_SHIFT = (__webpack_require__(84284).MID_SHIFT);
var constants = __webpack_require__(39360);
var helpers = __webpack_require__(57384);
var smithHelpers = __webpack_require__(36416);
var smith = smithHelpers.smith;
var reactanceArc = smithHelpers.reactanceArc;
var resistanceArc = smithHelpers.resistanceArc;
var smithTransform = smithHelpers.smithTransform;
var _ = Lib._;
var mod = Lib.mod;
var deg2rad = Lib.deg2rad;
var rad2deg = Lib.rad2deg;
function Polar(gd, id, isSmith) {
this.isSmith = isSmith || false;
this.id = id;
this.gd = gd;
this._hasClipOnAxisFalse = null;
this.vangles = null;
this.radialAxisAngle = null;
this.traceHash = {};
this.layers = {};
this.clipPaths = {};
this.clipIds = {};
this.viewInitial = {};
var fullLayout = gd._fullLayout;
var clipIdBase = 'clip' + fullLayout._uid + id;
this.clipIds.forTraces = clipIdBase + '-for-traces';
this.clipPaths.forTraces = fullLayout._clips.append('clipPath').attr('id', this.clipIds.forTraces);
this.clipPaths.forTraces.append('path');
this.framework = fullLayout['_' + (isSmith ? 'smith' : 'polar') + 'layer'].append('g').attr('class', id);
this.getHole = function (s) {
return this.isSmith ? 0 : s.hole;
};
this.getSector = function (s) {
return this.isSmith ? [0, 360] : s.sector;
};
this.getRadial = function (s) {
return this.isSmith ? s.realaxis : s.radialaxis;
};
this.getAngular = function (s) {
return this.isSmith ? s.imaginaryaxis : s.angularaxis;
};
if (!isSmith) {
// unfortunately, we have to keep track of some axis tick settings
// as polar subplots do not implement the 'ticks' editType
this.radialTickLayout = null;
this.angularTickLayout = null;
}
}
var proto = Polar.prototype;
module.exports = function createPolar(gd, id, isSmith) {
return new Polar(gd, id, isSmith);
};
proto.plot = function (polarCalcData, fullLayout) {
var _this = this;
var polarLayout = fullLayout[_this.id];
var found = false;
for (var i = 0; i < polarCalcData.length; i++) {
var trace = polarCalcData[i][0].trace;
if (trace.cliponaxis === false) {
found = true;
break;
}
}
_this._hasClipOnAxisFalse = found;
_this.updateLayers(fullLayout, polarLayout);
_this.updateLayout(fullLayout, polarLayout);
Plots.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout);
_this.updateFx(fullLayout, polarLayout);
if (_this.isSmith) {
delete polarLayout.realaxis.range;
delete polarLayout.imaginaryaxis.range;
}
};
proto.updateLayers = function (fullLayout, polarLayout) {
var _this = this;
var isSmith = _this.isSmith;
var layers = _this.layers;
var radialLayout = _this.getRadial(polarLayout);
var angularLayout = _this.getAngular(polarLayout);
var layerNames = constants.layerNames;
var frontPlotIndex = layerNames.indexOf('frontplot');
var layerData = layerNames.slice(0, frontPlotIndex);
var isAngularAxisBelowTraces = angularLayout.layer === 'below traces';
var isRadialAxisBelowTraces = radialLayout.layer === 'below traces';
if (isAngularAxisBelowTraces) layerData.push('angular-line');
if (isRadialAxisBelowTraces) layerData.push('radial-line');
if (isAngularAxisBelowTraces) layerData.push('angular-axis');
if (isRadialAxisBelowTraces) layerData.push('radial-axis');
layerData.push('frontplot');
if (!isAngularAxisBelowTraces) layerData.push('angular-line');
if (!isRadialAxisBelowTraces) layerData.push('radial-line');
if (!isAngularAxisBelowTraces) layerData.push('angular-axis');
if (!isRadialAxisBelowTraces) layerData.push('radial-axis');
var subLayer = (isSmith ? 'smith' : 'polar') + 'sublayer';
var join = _this.framework.selectAll('.' + subLayer).data(layerData, String);
join.enter().append('g').attr('class', function (d) {
return subLayer + ' ' + d;
}).each(function (d) {
var sel = layers[d] = d3.select(this);
switch (d) {
case 'frontplot':
// TODO add option to place in 'backplot' layer??
if (!isSmith) {
sel.append('g').classed('barlayer', true);
}
sel.append('g').classed('scatterlayer', true);
break;
case 'backplot':
sel.append('g').classed('maplayer', true);
break;
case 'plotbg':
layers.bg = sel.append('path');
break;
case 'radial-grid':
sel.style('fill', 'none');
break;
case 'angular-grid':
sel.style('fill', 'none');
break;
case 'radial-line':
sel.append('line').style('fill', 'none');
break;
case 'angular-line':
sel.append('path').style('fill', 'none');
break;
}
});
join.order();
};
/* Polar subplots juggle with 6 'axis objects' (!), these are:
*
* - getRadial(polarLayout) (aka radialLayout in this file):
* - getAngular(polarLayout) (aka angularLayout in this file):
* used for data -> calcdata conversions (aka d2c) during the calc step
*
* - this.radialAxis
* extends getRadial(polarLayout), adds mocked 'domain' and
* few other keys in order to reuse Cartesian doAutoRange and the Axes
* drawing routines.
* used for calcdata -> geometric conversions (aka c2g) during the plot step
* + setGeometry setups ax.c2g for given ax.range
* + setScale setups ax._m,ax._b for given ax.range
*
* - this.angularAxis
* extends getAngular(polarLayout), adds mocked 'range' and 'domain' and
* a few other keys in order to reuse the Axes drawing routines.
* used for calcdata -> geometric conversions (aka c2g) during the plot step
* + setGeometry setups ax.c2g given ax.rotation, ax.direction & ax._categories,
* and mocks ax.range
* + setScale setups ax._m,ax._b with that mocked ax.range
*
* - this.xaxis
* - this.yaxis
* setup so that polar traces can reuse plot methods of Cartesian traces
* which mostly rely on 2pixel methods (e.g ax.c2p)
*/
proto.updateLayout = function (fullLayout, polarLayout) {
var _this = this;
var layers = _this.layers;
var gs = fullLayout._size;
// axis attributes
var radialLayout = _this.getRadial(polarLayout);
var angularLayout = _this.getAngular(polarLayout);
// layout domains
var xDomain = polarLayout.domain.x;
var yDomain = polarLayout.domain.y;
// offsets from paper edge to layout domain box
_this.xOffset = gs.l + gs.w * xDomain[0];
_this.yOffset = gs.t + gs.h * (1 - yDomain[1]);
// lengths of the layout domain box
var xLength = _this.xLength = gs.w * (xDomain[1] - xDomain[0]);
var yLength = _this.yLength = gs.h * (yDomain[1] - yDomain[0]);
// sector to plot
var sector = _this.getSector(polarLayout);
_this.sectorInRad = sector.map(deg2rad);
var sectorBBox = _this.sectorBBox = computeSectorBBox(sector);
var dxSectorBBox = sectorBBox[2] - sectorBBox[0];
var dySectorBBox = sectorBBox[3] - sectorBBox[1];
// aspect ratios
var arDomain = yLength / xLength;
var arSector = Math.abs(dySectorBBox / dxSectorBBox);
// actual lengths and domains of subplot box
var xLength2, yLength2;
var xDomain2, yDomain2;
var gap;
if (arDomain > arSector) {
xLength2 = xLength;
yLength2 = xLength * arSector;
gap = (yLength - yLength2) / gs.h / 2;
xDomain2 = [xDomain[0], xDomain[1]];
yDomain2 = [yDomain[0] + gap, yDomain[1] - gap];
} else {
xLength2 = yLength / arSector;
yLength2 = yLength;
gap = (xLength - xLength2) / gs.w / 2;
xDomain2 = [xDomain[0] + gap, xDomain[1] - gap];
yDomain2 = [yDomain[0], yDomain[1]];
}
_this.xLength2 = xLength2;
_this.yLength2 = yLength2;
_this.xDomain2 = xDomain2;
_this.yDomain2 = yDomain2;
// actual offsets from paper edge to the subplot box top-left corner
var xOffset2 = _this.xOffset2 = gs.l + gs.w * xDomain2[0];
var yOffset2 = _this.yOffset2 = gs.t + gs.h * (1 - yDomain2[1]);
// circle radius in px
var radius = _this.radius = xLength2 / dxSectorBBox;
// 'inner' radius in px (when polar.hole is set)
var innerRadius = _this.innerRadius = _this.getHole(polarLayout) * radius;
// circle center position in px
var cx = _this.cx = xOffset2 - radius * sectorBBox[0];
var cy = _this.cy = yOffset2 + radius * sectorBBox[3];
// circle center in the coordinate system of plot area
var cxx = _this.cxx = cx - xOffset2;
var cyy = _this.cyy = cy - yOffset2;
var side = radialLayout.side;
var trueSide;
if (side === 'counterclockwise') {
trueSide = side;
side = 'top';
} else if (side === 'clockwise') {
trueSide = side;
side = 'bottom';
}
_this.radialAxis = _this.mockAxis(fullLayout, polarLayout, radialLayout, {
// make this an 'x' axis to make positioning (especially rotation) easier
_id: 'x',
// convert to 'x' axis equivalent
side: side,
// keep track of real side
_trueSide: trueSide,
// spans length 1 radius
domain: [innerRadius / gs.w, radius / gs.w]
});
_this.angularAxis = _this.mockAxis(fullLayout, polarLayout, angularLayout, {
side: 'right',
// to get auto nticks right
domain: [0, Math.PI],
// don't pass through autorange logic
autorange: false
});
_this.doAutoRange(fullLayout, polarLayout);
// N.B. this sets _this.vangles
_this.updateAngularAxis(fullLayout, polarLayout);
// N.B. this sets _this.radialAxisAngle
_this.updateRadialAxis(fullLayout, polarLayout);
_this.updateRadialAxisTitle(fullLayout, polarLayout);
_this.xaxis = _this.mockCartesianAxis(fullLayout, polarLayout, {
_id: 'x',
domain: xDomain2
});
_this.yaxis = _this.mockCartesianAxis(fullLayout, polarLayout, {
_id: 'y',
domain: yDomain2
});
var dPath = _this.pathSubplot();
_this.clipPaths.forTraces.select('path').attr('d', dPath).attr('transform', strTranslate(cxx, cyy));
layers.frontplot.attr('transform', strTranslate(xOffset2, yOffset2)).call(Drawing.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.forTraces, _this.gd);
layers.bg.attr('d', dPath).attr('transform', strTranslate(cx, cy)).call(Color.fill, polarLayout.bgcolor);
};
proto.mockAxis = function (fullLayout, polarLayout, axLayout, opts) {
var ax = Lib.extendFlat({}, axLayout, opts);
setConvertPolar(ax, polarLayout, fullLayout);
return ax;
};
proto.mockCartesianAxis = function (fullLayout, polarLayout, opts) {
var _this = this;
var isSmith = _this.isSmith;
var axId = opts._id;
var ax = Lib.extendFlat({
type: 'linear'
}, opts);
setConvertCartesian(ax, fullLayout);
var bboxIndices = {
x: [0, 2],
y: [1, 3]
};
ax.setRange = function () {
var sectorBBox = _this.sectorBBox;
var ind = bboxIndices[axId];
var rl = _this.radialAxis._rl;
var drl = (rl[1] - rl[0]) / (1 - _this.getHole(polarLayout));
ax.range = [sectorBBox[ind[0]] * drl, sectorBBox[ind[1]] * drl];
};
ax.isPtWithinRange = axId === 'x' && !isSmith ? function (d) {
return _this.isPtInside(d);
} : function () {
return true;
};
ax.setRange();
ax.setScale();
return ax;
};
proto.doAutoRange = function (fullLayout, polarLayout) {
var _this = this;
var gd = _this.gd;
var radialAxis = _this.radialAxis;
var radialLayout = _this.getRadial(polarLayout);
doAutoRange(gd, radialAxis);
var rng = radialAxis.range;
radialLayout.range = rng.slice();
radialLayout._input.range = rng.slice();
radialAxis._rl = [radialAxis.r2l(rng[0], null, 'gregorian'), radialAxis.r2l(rng[1], null, 'gregorian')];
if (radialAxis.minallowed !== undefined) {
var minallowed = radialAxis.r2l(radialAxis.minallowed);
if (radialAxis._rl[0] > radialAxis._rl[1]) {
radialAxis._rl[1] = Math.max(radialAxis._rl[1], minallowed);
} else {
radialAxis._rl[0] = Math.max(radialAxis._rl[0], minallowed);
}
}
if (radialAxis.maxallowed !== undefined) {
var maxallowed = radialAxis.r2l(radialAxis.maxallowed);
if (radialAxis._rl[0] < radialAxis._rl[1]) {
radialAxis._rl[1] = Math.min(radialAxis._rl[1], maxallowed);
} else {
radialAxis._rl[0] = Math.min(radialAxis._rl[0], maxallowed);
}
}
};
proto.updateRadialAxis = function (fullLayout, polarLayout) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var radius = _this.radius;
var innerRadius = _this.innerRadius;
var cx = _this.cx;
var cy = _this.cy;
var radialLayout = _this.getRadial(polarLayout);
var a0 = mod(_this.getSector(polarLayout)[0], 360);
var ax = _this.radialAxis;
var hasRoomForIt = innerRadius < radius;
var isSmith = _this.isSmith;
if (!isSmith) {
_this.fillViewInitialKey('radialaxis.angle', radialLayout.angle);
_this.fillViewInitialKey('radialaxis.range', ax.range.slice());
ax.setGeometry();
}
// rotate auto tick labels by 180 if in quadrant II and III to make them
// readable from left-to-right
//
// TODO try moving deeper in Axes.drawLabels for better results?
if (ax.tickangle === 'auto' && a0 > 90 && a0 <= 270) {
ax.tickangle = 180;
}
// easier to set rotate angle with custom translate function
var transFn = isSmith ? function (d) {
var t = smithTransform(_this, smith([d.x, 0]));
return strTranslate(t[0] - cx, t[1] - cy);
} : function (d) {
return strTranslate(ax.l2p(d.x) + innerRadius, 0);
};
// set special grid path function
var gridPathFn = isSmith ? function (d) {
return resistanceArc(_this, d.x, -Infinity, Infinity);
} : function (d) {
return _this.pathArc(ax.r2p(d.x) + innerRadius);
};
var newTickLayout = strTickLayout(radialLayout);
if (_this.radialTickLayout !== newTickLayout) {
layers['radial-axis'].selectAll('.xtick').remove();
_this.radialTickLayout = newTickLayout;
}
if (hasRoomForIt) {
ax.setScale();
var labelShift = 0;
var vals = isSmith ? (ax.tickvals || []).filter(function (x) {
// filter negative
return x >= 0;
}).map(function (x) {
return Axes.tickText(ax, x, true, false);
}) : Axes.calcTicks(ax);
var valsClipped = isSmith ? vals : Axes.clipEnds(ax, vals);
var tickSign = Axes.getTickSigns(ax)[2];
if (isSmith) {
if (ax.ticks === 'top' && ax.side === 'bottom' || ax.ticks === 'bottom' && ax.side === 'top') {
// invert sign
tickSign = -tickSign;
}
if (ax.ticks === 'top' && ax.side === 'top') labelShift = -ax.ticklen;
if (ax.ticks === 'bottom' && ax.side === 'bottom') labelShift = ax.ticklen;
}
Axes.drawTicks(gd, ax, {
vals: vals,
layer: layers['radial-axis'],
path: Axes.makeTickPath(ax, 0, tickSign),
transFn: transFn,
crisp: false
});
Axes.drawGrid(gd, ax, {
vals: valsClipped,
layer: layers['radial-grid'],
path: gridPathFn,
transFn: Lib.noop,
crisp: false
});
Axes.drawLabels(gd, ax, {
vals: vals,
layer: layers['radial-axis'],
transFn: transFn,
labelFns: Axes.makeLabelFns(ax, labelShift)
});
}
// stash 'actual' radial axis angle for drag handlers (in degrees)
var angle = _this.radialAxisAngle = _this.vangles ? rad2deg(snapToVertexAngle(deg2rad(radialLayout.angle), _this.vangles)) : radialLayout.angle;
var tLayer = strTranslate(cx, cy);
var tLayer2 = tLayer + strRotate(-angle);
updateElement(layers['radial-axis'], hasRoomForIt && (radialLayout.showticklabels || radialLayout.ticks), {
transform: tLayer2
});
updateElement(layers['radial-grid'], hasRoomForIt && radialLayout.showgrid, {
transform: isSmith ? '' : tLayer
});
updateElement(layers['radial-line'].select('line'), hasRoomForIt && radialLayout.showline, {
x1: isSmith ? -radius : innerRadius,
y1: 0,
x2: radius,
y2: 0,
transform: tLayer2
}).attr('stroke-width', radialLayout.linewidth).call(Color.stroke, radialLayout.linecolor);
};
proto.updateRadialAxisTitle = function (fullLayout, polarLayout, _angle) {
if (this.isSmith) return;
var _this = this;
var gd = _this.gd;
var radius = _this.radius;
var cx = _this.cx;
var cy = _this.cy;
var radialLayout = _this.getRadial(polarLayout);
var titleClass = _this.id + 'title';
var pad = 0;
// Hint: no need to check if there is in fact a title.text set
// because if plot is editable, pad needs to be calculated anyways
// to properly show placeholder text when title is empty.
if (radialLayout.title) {
var h = Drawing.bBox(_this.layers['radial-axis'].node()).height;
var ts = radialLayout.title.font.size;
var side = radialLayout.side;
pad = side === 'top' ? ts : side === 'counterclockwise' ? -(h + ts * 0.4) : h + ts * 0.8;
}
var angle = _angle !== undefined ? _angle : _this.radialAxisAngle;
var angleRad = deg2rad(angle);
var cosa = Math.cos(angleRad);
var sina = Math.sin(angleRad);
var x = cx + radius / 2 * cosa + pad * sina;
var y = cy - radius / 2 * sina + pad * cosa;
_this.layers['radial-axis-title'] = Titles.draw(gd, titleClass, {
propContainer: radialLayout,
propName: _this.id + '.radialaxis.title',
placeholder: _(gd, 'Click to enter radial axis title'),
attributes: {
x: x,
y: y,
'text-anchor': 'middle'
},
transform: {
rotate: -angle
}
});
};
proto.updateAngularAxis = function (fullLayout, polarLayout) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var radius = _this.radius;
var innerRadius = _this.innerRadius;
var cx = _this.cx;
var cy = _this.cy;
var angularLayout = _this.getAngular(polarLayout);
var ax = _this.angularAxis;
var isSmith = _this.isSmith;
if (!isSmith) {
_this.fillViewInitialKey('angularaxis.rotation', angularLayout.rotation);
ax.setGeometry();
ax.setScale();
}
// 't'ick to 'g'eometric radians is used all over the place here
var t2g = isSmith ? function (d) {
var t = smithTransform(_this, smith([0, d.x]));
return Math.atan2(t[0] - cx, t[1] - cy) - Math.PI / 2;
} : function (d) {
return ax.t2g(d.x);
};
// run rad2deg on tick0 and ditck for thetaunit: 'radians' axes
if (ax.type === 'linear' && ax.thetaunit === 'radians') {
ax.tick0 = rad2deg(ax.tick0);
ax.dtick = rad2deg(ax.dtick);
}
var _transFn = function (rad) {
return strTranslate(cx + radius * Math.cos(rad), cy - radius * Math.sin(rad));
};
var transFn = isSmith ? function (d) {
var t = smithTransform(_this, smith([0, d.x]));
return strTranslate(t[0], t[1]);
} : function (d) {
return _transFn(t2g(d));
};
var transFn2 = isSmith ? function (d) {
var t = smithTransform(_this, smith([0, d.x]));
var rad = Math.atan2(t[0] - cx, t[1] - cy) - Math.PI / 2;
return strTranslate(t[0], t[1]) + strRotate(-rad2deg(rad));
} : function (d) {
var rad = t2g(d);
return _transFn(rad) + strRotate(-rad2deg(rad));
};
var gridPathFn = isSmith ? function (d) {
return reactanceArc(_this, d.x, 0, Infinity);
} : function (d) {
var rad = t2g(d);
var cosRad = Math.cos(rad);
var sinRad = Math.sin(rad);
return 'M' + [cx + innerRadius * cosRad, cy - innerRadius * sinRad] + 'L' + [cx + radius * cosRad, cy - radius * sinRad];
};
var out = Axes.makeLabelFns(ax, 0);
var labelStandoff = out.labelStandoff;
var labelFns = {};
labelFns.xFn = function (d) {
var rad = t2g(d);
return Math.cos(rad) * labelStandoff;
};
labelFns.yFn = function (d) {
var rad = t2g(d);
var ff = Math.sin(rad) > 0 ? 0.2 : 1;
return -Math.sin(rad) * (labelStandoff + d.fontSize * ff) + Math.abs(Math.cos(rad)) * (d.fontSize * MID_SHIFT);
};
labelFns.anchorFn = function (d) {
var rad = t2g(d);
var cos = Math.cos(rad);
return Math.abs(cos) < 0.1 ? 'middle' : cos > 0 ? 'start' : 'end';
};
labelFns.heightFn = function (d, a, h) {
var rad = t2g(d);
return -0.5 * (1 + Math.sin(rad)) * h;
};
var newTickLayout = strTickLayout(angularLayout);
if (_this.angularTickLayout !== newTickLayout) {
layers['angular-axis'].selectAll('.' + ax._id + 'tick').remove();
_this.angularTickLayout = newTickLayout;
}
var vals = isSmith ? [Infinity].concat(ax.tickvals || []).map(function (x) {
return Axes.tickText(ax, x, true, false);
}) : Axes.calcTicks(ax);
if (isSmith) {
vals[0].text = '∞';
vals[0].fontSize *= 1.75;
}
// angle of polygon vertices in geometric radians (null means circles)
// TODO what to do when ax.period > ax._categories ??
var vangles;
if (polarLayout.gridshape === 'linear') {
vangles = vals.map(t2g);
// ax._vals should be always ordered, make them
// always turn counterclockwise for convenience here
if (Lib.angleDelta(vangles[0], vangles[1]) < 0) {
vangles = vangles.slice().reverse();
}
} else {
vangles = null;
}
_this.vangles = vangles;
// Use tickval filter for category axes instead of tweaking
// the range w.r.t sector, so that sectors that cross 360 can
// show all their ticks.
if (ax.type === 'category') {
vals = vals.filter(function (d) {
return Lib.isAngleInsideSector(t2g(d), _this.sectorInRad);
});
}
if (ax.visible) {
var tickSign = ax.ticks === 'inside' ? -1 : 1;
var pad = (ax.linewidth || 1) / 2;
Axes.drawTicks(gd, ax, {
vals: vals,
layer: layers['angular-axis'],
path: 'M' + tickSign * pad + ',0h' + tickSign * ax.ticklen,
transFn: transFn2,
crisp: false
});
Axes.drawGrid(gd, ax, {
vals: vals,
layer: layers['angular-grid'],
path: gridPathFn,
transFn: Lib.noop,
crisp: false
});
Axes.drawLabels(gd, ax, {
vals: vals,
layer: layers['angular-axis'],
repositionOnUpdate: true,
transFn: transFn,
labelFns: labelFns
});
}
// TODO maybe two arcs is better here?
// maybe split style attributes between inner and outer angular axes?
updateElement(layers['angular-line'].select('path'), angularLayout.showline, {
d: _this.pathSubplot(),
transform: strTranslate(cx, cy)
}).attr('stroke-width', angularLayout.linewidth).call(Color.stroke, angularLayout.linecolor);
};
proto.updateFx = function (fullLayout, polarLayout) {
if (!this.gd._context.staticPlot) {
var hasDrag = !this.isSmith;
if (hasDrag) {
this.updateAngularDrag(fullLayout);
this.updateRadialDrag(fullLayout, polarLayout, 0);
this.updateRadialDrag(fullLayout, polarLayout, 1);
}
this.updateHoverAndMainDrag(fullLayout);
}
};
proto.updateHoverAndMainDrag = function (fullLayout) {
var _this = this;
var isSmith = _this.isSmith;
var gd = _this.gd;
var layers = _this.layers;
var zoomlayer = fullLayout._zoomlayer;
var MINZOOM = constants.MINZOOM;
var OFFEDGE = constants.OFFEDGE;
var radius = _this.radius;
var innerRadius = _this.innerRadius;
var cx = _this.cx;
var cy = _this.cy;
var cxx = _this.cxx;
var cyy = _this.cyy;
var sectorInRad = _this.sectorInRad;
var vangles = _this.vangles;
var radialAxis = _this.radialAxis;
var clampTiny = helpers.clampTiny;
var findXYatLength = helpers.findXYatLength;
var findEnclosingVertexAngles = helpers.findEnclosingVertexAngles;
var chw = constants.cornerHalfWidth;
var chl = constants.cornerLen / 2;
var scaleX;
var scaleY;
var mainDrag = dragBox.makeDragger(layers, 'path', 'maindrag', fullLayout.dragmode === false ? 'none' : 'crosshair');
d3.select(mainDrag).attr('d', _this.pathSubplot()).attr('transform', strTranslate(cx, cy));
mainDrag.onmousemove = function (evt) {
Fx.hover(gd, evt, _this.id);
gd._fullLayout._lasthover = mainDrag;
gd._fullLayout._hoversubplot = _this.id;
};
mainDrag.onmouseout = function (evt) {
if (gd._dragging) return;
dragElement.unhover(gd, evt);
};
var dragOpts = {
element: mainDrag,
gd: gd,
subplot: _this.id,
plotinfo: {
id: _this.id,
xaxis: _this.xaxis,
yaxis: _this.yaxis
},
xaxes: [_this.xaxis],
yaxes: [_this.yaxis]
};
// mouse px position at drag start (0), move (1)
var x0, y0;
// radial distance from circle center at drag start (0), move (1)
var r0, r1;
// zoombox persistent quantities
var path0, dimmed, lum;
// zoombox, corners elements
var zb, corners;
function norm(x, y) {
return Math.sqrt(x * x + y * y);
}
function xy2r(x, y) {
return norm(x - cxx, y - cyy);
}
function xy2a(x, y) {
return Math.atan2(cyy - y, x - cxx);
}
function ra2xy(r, a) {
return [r * Math.cos(a), r * Math.sin(-a)];
}
function pathCorner(r, a) {
if (r === 0) return _this.pathSector(2 * chw);
var da = chl / r;
var am = a - da;
var ap = a + da;
var rb = Math.max(0, Math.min(r, radius));
var rm = rb - chw;
var rp = rb + chw;
return 'M' + ra2xy(rm, am) + 'A' + [rm, rm] + ' 0,0,0 ' + ra2xy(rm, ap) + 'L' + ra2xy(rp, ap) + 'A' + [rp, rp] + ' 0,0,1 ' + ra2xy(rp, am) + 'Z';
}
// (x,y) is the pt at middle of the va0 <-> va1 edge
//
// ... we could eventually add another mode for cursor
// angles 'close to' enough to a particular vertex.
function pathCornerForPolygons(r, va0, va1) {
if (r === 0) return _this.pathSector(2 * chw);
var xy0 = ra2xy(r, va0);
var xy1 = ra2xy(r, va1);
var x = clampTiny((xy0[0] + xy1[0]) / 2);
var y = clampTiny((xy0[1] + xy1[1]) / 2);
var innerPts, outerPts;
if (x && y) {
var m = y / x;
var mperp = -1 / m;
var midPts = findXYatLength(chw, m, x, y);
innerPts = findXYatLength(chl, mperp, midPts[0][0], midPts[0][1]);
outerPts = findXYatLength(chl, mperp, midPts[1][0], midPts[1][1]);
} else {
var dx, dy;
if (y) {
// horizontal handles
dx = chl;
dy = chw;
} else {
// vertical handles
dx = chw;
dy = chl;
}
innerPts = [[x - dx, y - dy], [x + dx, y - dy]];
outerPts = [[x - dx, y + dy], [x + dx, y + dy]];
}
return 'M' + innerPts.join('L') + 'L' + outerPts.reverse().join('L') + 'Z';
}
function zoomPrep() {
r0 = null;
r1 = null;
path0 = _this.pathSubplot();
dimmed = false;
var polarLayoutNow = gd._fullLayout[_this.id];
lum = tinycolor(polarLayoutNow.bgcolor).getLuminance();
zb = dragBox.makeZoombox(zoomlayer, lum, cx, cy, path0);
zb.attr('fill-rule', 'evenodd');
corners = dragBox.makeCorners(zoomlayer, cx, cy);
clearOutline(gd);
}
// N.B. this sets scoped 'r0' and 'r1'
// return true if 'valid' zoom distance, false otherwise
function clampAndSetR0R1(rr0, rr1) {
rr1 = Math.max(Math.min(rr1, radius), innerRadius);
// starting or ending drag near center (outer edge),
// clamps radial distance at origin (at r=radius)
if (rr0 < OFFEDGE) rr0 = 0;else if (radius - rr0 < OFFEDGE) rr0 = radius;else if (rr1 < OFFEDGE) rr1 = 0;else if (radius - rr1 < OFFEDGE) rr1 = radius;
// make sure r0 < r1,
// to get correct fill pattern in path1 below
if (Math.abs(rr1 - rr0) > MINZOOM) {
if (rr0 < rr1) {
r0 = rr0;
r1 = rr1;
} else {
r0 = rr1;
r1 = rr0;
}
return true;
} else {
r0 = null;
r1 = null;
return false;
}
}
function applyZoomMove(path1, cpath) {
path1 = path1 || path0;
cpath = cpath || 'M0,0Z';
zb.attr('d', path1);
corners.attr('d', cpath);
dragBox.transitionZoombox(zb, corners, dimmed, lum);
dimmed = true;
var updateObj = {};
computeZoomUpdates(updateObj);
gd.emit('plotly_relayouting', updateObj);
}
function zoomMove(dx, dy) {
dx = dx * scaleX;
dy = dy * scaleY;
var x1 = x0 + dx;
var y1 = y0 + dy;
var rr0 = xy2r(x0, y0);
var rr1 = Math.min(xy2r(x1, y1), radius);
var a0 = xy2a(x0, y0);
var path1;
var cpath;
if (clampAndSetR0R1(rr0, rr1)) {
path1 = path0 + _this.pathSector(r1);
if (r0) path1 += _this.pathSector(r0);
// keep 'starting' angle
cpath = pathCorner(r0, a0) + pathCorner(r1, a0);
}
applyZoomMove(path1, cpath);
}
function findPolygonRadius(x, y, va0, va1) {
var xy = helpers.findIntersectionXY(va0, va1, va0, [x - cxx, cyy - y]);
return norm(xy[0], xy[1]);
}
function zoomMoveForPolygons(dx, dy) {
var x1 = x0 + dx;
var y1 = y0 + dy;
var a0 = xy2a(x0, y0);
var a1 = xy2a(x1, y1);
var vangles0 = findEnclosingVertexAngles(a0, vangles);
var vangles1 = findEnclosingVertexAngles(a1, vangles);
var rr0 = findPolygonRadius(x0, y0, vangles0[0], vangles0[1]);
var rr1 = Math.min(findPolygonRadius(x1, y1, vangles1[0], vangles1[1]), radius);
var path1;
var cpath;
if (clampAndSetR0R1(rr0, rr1)) {
path1 = path0 + _this.pathSector(r1);
if (r0) path1 += _this.pathSector(r0);
// keep 'starting' angle here too
cpath = [pathCornerForPolygons(r0, vangles0[0], vangles0[1]), pathCornerForPolygons(r1, vangles0[0], vangles0[1])].join(' ');
}
applyZoomMove(path1, cpath);
}
function zoomDone() {
dragBox.removeZoombox(gd);
if (r0 === null || r1 === null) return;
var updateObj = {};
computeZoomUpdates(updateObj);
dragBox.showDoubleClickNotifier(gd);
Registry.call('_guiRelayout', gd, updateObj);
}
function computeZoomUpdates(update) {
var rl = radialAxis._rl;
var m = (rl[1] - rl[0]) / (1 - innerRadius / radius) / radius;
var newRng = [rl[0] + (r0 - innerRadius) * m, rl[0] + (r1 - innerRadius) * m];
update[_this.id + '.radialaxis.range'] = newRng;
}
function zoomClick(numClicks, evt) {
var clickMode = gd._fullLayout.clickmode;
dragBox.removeZoombox(gd);
// TODO double once vs twice logic (autorange vs fixed range)
if (numClicks === 2) {
var updateObj = {};
for (var k in _this.viewInitial) {
updateObj[_this.id + '.' + k] = _this.viewInitial[k];
}
gd.emit('plotly_doubleclick', null);
Registry.call('_guiRelayout', gd, updateObj);
}
if (clickMode.indexOf('select') > -1 && numClicks === 1) {
selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, dragOpts);
}
if (clickMode.indexOf('event') > -1) {
Fx.click(gd, evt, _this.id);
}
}
dragOpts.prepFn = function (evt, startX, startY) {
var dragModeNow = gd._fullLayout.dragmode;
var bbox = mainDrag.getBoundingClientRect();
gd._fullLayout._calcInverseTransform(gd);
var inverse = gd._fullLayout._invTransform;
scaleX = gd._fullLayout._invScaleX;
scaleY = gd._fullLayout._invScaleY;
var transformedCoords = Lib.apply3DTransform(inverse)(startX - bbox.left, startY - bbox.top);
x0 = transformedCoords[0];
y0 = transformedCoords[1];
// need to offset x/y as bbox center does not
// match origin for asymmetric polygons
if (vangles) {
var offset = helpers.findPolygonOffset(radius, sectorInRad[0], sectorInRad[1], vangles);
x0 += cxx + offset[0];
y0 += cyy + offset[1];
}
switch (dragModeNow) {
case 'zoom':
dragOpts.clickFn = zoomClick;
if (!isSmith) {
if (vangles) {
dragOpts.moveFn = zoomMoveForPolygons;
} else {
dragOpts.moveFn = zoomMove;
}
dragOpts.doneFn = zoomDone;
zoomPrep(evt, startX, startY);
}
break;
case 'select':
case 'lasso':
prepSelect(evt, startX, startY, dragOpts, dragModeNow);
break;
}
};
dragElement.init(dragOpts);
};
proto.updateRadialDrag = function (fullLayout, polarLayout, rngIndex) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var radius = _this.radius;
var innerRadius = _this.innerRadius;
var cx = _this.cx;
var cy = _this.cy;
var radialAxis = _this.radialAxis;
var bl = constants.radialDragBoxSize;
var bl2 = bl / 2;
if (!radialAxis.visible) return;
var angle0 = deg2rad(_this.radialAxisAngle);
var rl = radialAxis._rl;
var rl0 = rl[0];
var rl1 = rl[1];
var rbase = rl[rngIndex];
var m = 0.75 * (rl[1] - rl[0]) / (1 - _this.getHole(polarLayout)) / radius;
var tx, ty, className;
if (rngIndex) {
tx = cx + (radius + bl2) * Math.cos(angle0);
ty = cy - (radius + bl2) * Math.sin(angle0);
className = 'radialdrag';
} else {
// the 'inner' box can get called:
// - when polar.hole>0
// - when polar.sector isn't a full circle
// otherwise it is hidden behind the main drag.
tx = cx + (innerRadius - bl2) * Math.cos(angle0);
ty = cy - (innerRadius - bl2) * Math.sin(angle0);
className = 'radialdrag-inner';
}
var radialDrag = dragBox.makeRectDragger(layers, className, 'crosshair', -bl2, -bl2, bl, bl);
var dragOpts = {
element: radialDrag,
gd: gd
};
if (fullLayout.dragmode === false) {
dragOpts.dragmode = false;
}
updateElement(d3.select(radialDrag), radialAxis.visible && innerRadius < radius, {
transform: strTranslate(tx, ty)
});
// move function (either rotate or re-range flavor)
var moveFn2;
// rotate angle on done
var angle1;
// re-range range[1] (or range[0]) on done
var rprime;
function moveFn(dx, dy) {
if (moveFn2) {
moveFn2(dx, dy);
} else {
var dvec = [dx, -dy];
var rvec = [Math.cos(angle0), Math.sin(angle0)];
var comp = Math.abs(Lib.dot(dvec, rvec) / Math.sqrt(Lib.dot(dvec, dvec)));
// mostly perpendicular motions rotate,
// mostly parallel motions re-range
if (!isNaN(comp)) {
moveFn2 = comp < 0.5 ? rotateMove : rerangeMove;
}
}
var update = {};
computeRadialAxisUpdates(update);
gd.emit('plotly_relayouting', update);
}
function computeRadialAxisUpdates(update) {
if (angle1 !== null) {
update[_this.id + '.radialaxis.angle'] = angle1;
} else if (rprime !== null) {
update[_this.id + '.radialaxis.range[' + rngIndex + ']'] = rprime;
}
}
function doneFn() {
if (angle1 !== null) {
Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.angle', angle1);
} else if (rprime !== null) {
Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.range[' + rngIndex + ']', rprime);
}
}
function rotateMove(dx, dy) {
// disable for inner drag boxes
if (rngIndex === 0) return;
var x1 = tx + dx;
var y1 = ty + dy;
angle1 = Math.atan2(cy - y1, x1 - cx);
if (_this.vangles) angle1 = snapToVertexAngle(angle1, _this.vangles);
angle1 = rad2deg(angle1);
var transform = strTranslate(cx, cy) + strRotate(-angle1);
layers['radial-axis'].attr('transform', transform);
layers['radial-line'].select('line').attr('transform', transform);
var fullLayoutNow = _this.gd._fullLayout;
var polarLayoutNow = fullLayoutNow[_this.id];
_this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, angle1);
}
function rerangeMove(dx, dy) {
// project (dx, dy) unto unit radial axis vector
var dr = Lib.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]);
rprime = rbase - m * dr;
// make sure rprime does not change the range[0] -> range[1] sign
if (m > 0 !== (rngIndex ? rprime > rl0 : rprime < rl1)) {
rprime = null;
return;
}
var fullLayoutNow = gd._fullLayout;
var polarLayoutNow = fullLayoutNow[_this.id];
// update radial range -> update c2g -> update _m,_b
radialAxis.range[rngIndex] = rprime;
radialAxis._rl[rngIndex] = rprime;
_this.updateRadialAxis(fullLayoutNow, polarLayoutNow);
_this.xaxis.setRange();
_this.xaxis.setScale();
_this.yaxis.setRange();
_this.yaxis.setScale();
var hasRegl = false;
for (var traceType in _this.traceHash) {
var moduleCalcData = _this.traceHash[traceType];
var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
var _module = moduleCalcData[0][0].trace._module;
_module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
if (Registry.traceIs(traceType, 'gl') && moduleCalcDataVisible.length) hasRegl = true;
}
if (hasRegl) {
clearGlCanvases(gd);
redrawReglTraces(gd);
}
}
dragOpts.prepFn = function () {
moveFn2 = null;
angle1 = null;
rprime = null;
dragOpts.moveFn = moveFn;
dragOpts.doneFn = doneFn;
clearOutline(gd);
};
dragOpts.clampFn = function (dx, dy) {
if (Math.sqrt(dx * dx + dy * dy) < constants.MINDRAG) {
dx = 0;
dy = 0;
}
return [dx, dy];
};
dragElement.init(dragOpts);
};
proto.updateAngularDrag = function (fullLayout) {
var _this = this;
var gd = _this.gd;
var layers = _this.layers;
var radius = _this.radius;
var angularAxis = _this.angularAxis;
var cx = _this.cx;
var cy = _this.cy;
var cxx = _this.cxx;
var cyy = _this.cyy;
var dbs = constants.angularDragBoxSize;
var angularDrag = dragBox.makeDragger(layers, 'path', 'angulardrag', fullLayout.dragmode === false ? 'none' : 'move');
var dragOpts = {
element: angularDrag,
gd: gd
};
if (fullLayout.dragmode === false) {
dragOpts.dragmode = false;
} else {
d3.select(angularDrag).attr('d', _this.pathAnnulus(radius, radius + dbs)).attr('transform', strTranslate(cx, cy)).call(setCursor, 'move');
}
function xy2a(x, y) {
return Math.atan2(cyy + dbs - y, x - cxx - dbs);
}
// scatter trace, points and textpoints selections
var scatterTraces = layers.frontplot.select('.scatterlayer').selectAll('.trace');
var scatterPoints = scatterTraces.selectAll('.point');
var scatterTextPoints = scatterTraces.selectAll('.textpoint');
// mouse px position at drag start (0), move (1)
var x0, y0;
// angular axis angle rotation at drag start (0), move (1)
var rot0, rot1;
// induced radial axis rotation (only used on polygon grids)
var rrot1;
// angle about circle center at drag start
var a0;
function moveFn(dx, dy) {
var fullLayoutNow = _this.gd._fullLayout;
var polarLayoutNow = fullLayoutNow[_this.id];
var x1 = x0 + dx * fullLayout._invScaleX;
var y1 = y0 + dy * fullLayout._invScaleY;
var a1 = xy2a(x1, y1);
var da = rad2deg(a1 - a0);
rot1 = rot0 + da;
layers.frontplot.attr('transform', strTranslate(_this.xOffset2, _this.yOffset2) + strRotate([-da, cxx, cyy]));
if (_this.vangles) {
rrot1 = _this.radialAxisAngle + da;
var trans = strTranslate(cx, cy) + strRotate(-da);
var trans2 = strTranslate(cx, cy) + strRotate(-rrot1);
layers.bg.attr('transform', trans);
layers['radial-grid'].attr('transform', trans);
layers['radial-axis'].attr('transform', trans2);
layers['radial-line'].select('line').attr('transform', trans2);
_this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, rrot1);
} else {
_this.clipPaths.forTraces.select('path').attr('transform', strTranslate(cxx, cyy) + strRotate(da));
}
// 'un-rotate' marker and text points
scatterPoints.each(function () {
var sel = d3.select(this);
var xy = Drawing.getTranslate(sel);
sel.attr('transform', strTranslate(xy.x, xy.y) + strRotate([da]));
});
scatterTextPoints.each(function () {
var sel = d3.select(this);
var tx = sel.select('text');
var xy = Drawing.getTranslate(sel);
// N.B rotate -> translate ordering matters
sel.attr('transform', strRotate([da, tx.attr('x'), tx.attr('y')]) + strTranslate(xy.x, xy.y));
});
// update rotation -> range -> _m,_b
angularAxis.rotation = Lib.modHalf(rot1, 360);
_this.updateAngularAxis(fullLayoutNow, polarLayoutNow);
if (_this._hasClipOnAxisFalse && !Lib.isFullCircle(_this.sectorInRad)) {
scatterTraces.call(Drawing.hideOutsideRangePoints, _this);
}
var hasRegl = false;
for (var traceType in _this.traceHash) {
if (Registry.traceIs(traceType, 'gl')) {
var moduleCalcData = _this.traceHash[traceType];
var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
var _module = moduleCalcData[0][0].trace._module;
_module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
if (moduleCalcDataVisible.length) hasRegl = true;
}
}
if (hasRegl) {
clearGlCanvases(gd);
redrawReglTraces(gd);
}
var update = {};
computeRotationUpdates(update);
gd.emit('plotly_relayouting', update);
}
function computeRotationUpdates(updateObj) {
updateObj[_this.id + '.angularaxis.rotation'] = rot1;
if (_this.vangles) {
updateObj[_this.id + '.radialaxis.angle'] = rrot1;
}
}
function doneFn() {
scatterTextPoints.select('text').attr('transform', null);
var updateObj = {};
computeRotationUpdates(updateObj);
Registry.call('_guiRelayout', gd, updateObj);
}
dragOpts.prepFn = function (evt, startX, startY) {
var polarLayoutNow = fullLayout[_this.id];
rot0 = polarLayoutNow.angularaxis.rotation;
var bbox = angularDrag.getBoundingClientRect();
x0 = startX - bbox.left;
y0 = startY - bbox.top;
gd._fullLayout._calcInverseTransform(gd);
var transformedCoords = Lib.apply3DTransform(fullLayout._invTransform)(x0, y0);
x0 = transformedCoords[0];
y0 = transformedCoords[1];
a0 = xy2a(x0, y0);
dragOpts.moveFn = moveFn;
dragOpts.doneFn = doneFn;
clearOutline(gd);
};
// I don't what we should do in this case, skip we now
if (_this.vangles && !Lib.isFullCircle(_this.sectorInRad)) {
dragOpts.prepFn = Lib.noop;
setCursor(d3.select(angularDrag), null);
}
dragElement.init(dragOpts);
};
proto.isPtInside = function (d) {
if (this.isSmith) return true;
var sectorInRad = this.sectorInRad;
var vangles = this.vangles;
var thetag = this.angularAxis.c2g(d.theta);
var radialAxis = this.radialAxis;
var r = radialAxis.c2l(d.r);
var rl = radialAxis._rl;
var fn = vangles ? helpers.isPtInsidePolygon : Lib.isPtInsideSector;
return fn(r, thetag, rl, sectorInRad, vangles);
};
proto.pathArc = function (r) {
var sectorInRad = this.sectorInRad;
var vangles = this.vangles;
var fn = vangles ? helpers.pathPolygon : Lib.pathArc;
return fn(r, sectorInRad[0], sectorInRad[1], vangles);
};
proto.pathSector = function (r) {
var sectorInRad = this.sectorInRad;
var vangles = this.vangles;
var fn = vangles ? helpers.pathPolygon : Lib.pathSector;
return fn(r, sectorInRad[0], sectorInRad[1], vangles);
};
proto.pathAnnulus = function (r0, r1) {
var sectorInRad = this.sectorInRad;
var vangles = this.vangles;
var fn = vangles ? helpers.pathPolygonAnnulus : Lib.pathAnnulus;
return fn(r0, r1, sectorInRad[0], sectorInRad[1], vangles);
};
proto.pathSubplot = function () {
var r0 = this.innerRadius;
var r1 = this.radius;
return r0 ? this.pathAnnulus(r0, r1) : this.pathSector(r1);
};
proto.fillViewInitialKey = function (key, val) {
if (!(key in this.viewInitial)) {
this.viewInitial[key] = val;
}
};
function strTickLayout(axLayout) {
var out = axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
if ('side' in axLayout) out += axLayout.side;
return out;
}
// Finds the bounding box of a given circle sector,
// inspired by https://math.stackexchange.com/q/1852703
//
// assumes:
// - sector[0] < sector[1]
// - counterclockwise rotation
function computeSectorBBox(sector) {
var s0 = sector[0];
var s1 = sector[1];
var arc = s1 - s0;
var a0 = mod(s0, 360);
var a1 = a0 + arc;
var ax0 = Math.cos(deg2rad(a0));
var ay0 = Math.sin(deg2rad(a0));
var ax1 = Math.cos(deg2rad(a1));
var ay1 = Math.sin(deg2rad(a1));
var x0, y0, x1, y1;
if (a0 <= 90 && a1 >= 90 || a0 > 90 && a1 >= 450) {
y1 = 1;
} else if (ay0 <= 0 && ay1 <= 0) {
y1 = 0;
} else {
y1 = Math.max(ay0, ay1);
}
if (a0 <= 180 && a1 >= 180 || a0 > 180 && a1 >= 540) {
x0 = -1;
} else if (ax0 >= 0 && ax1 >= 0) {
x0 = 0;
} else {
x0 = Math.min(ax0, ax1);
}
if (a0 <= 270 && a1 >= 270 || a0 > 270 && a1 >= 630) {
y0 = -1;
} else if (ay0 >= 0 && ay1 >= 0) {
y0 = 0;
} else {
y0 = Math.min(ay0, ay1);
}
if (a1 >= 360) {
x1 = 1;
} else if (ax0 <= 0 && ax1 <= 0) {
x1 = 0;
} else {
x1 = Math.max(ax0, ax1);
}
return [x0, y0, x1, y1];
}
function snapToVertexAngle(a, vangles) {
var fn = function (v) {
return Lib.angleDist(a, v);
};
var ind = Lib.findIndexOfMin(vangles, fn);
return vangles[ind];
}
function updateElement(sel, showAttr, attrs) {
if (showAttr) {
sel.attr('display', null);
sel.attr(attrs);
} else if (sel) {
sel.attr('display', 'none');
}
return sel;
}
/***/ }),
/***/ 57696:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var setConvertCartesian = __webpack_require__(78344);
var deg2rad = Lib.deg2rad;
var rad2deg = Lib.rad2deg;
/**
* setConvert for polar axes!
*
* @param {object} ax
* axis in question (works for both radial and angular axes)
* @param {object} polarLayout
* full polar layout of the subplot associated with 'ax'
* @param {object} fullLayout
* full layout
*
* Here, reuse some of the Cartesian setConvert logic,
* but we must extend some of it, as both radial and angular axes
* don't have domains and angular axes don't have _true_ ranges.
*
* Moreover, we introduce two new coordinate systems:
* - 'g' for geometric coordinates and
* - 't' for angular ticks
*
* Radial axis coordinate systems:
* - d, c and l: same as for cartesian axes
* - g: like calcdata but translated about `radialaxis.range[0]` & `polar.hole`
*
* Angular axis coordinate systems:
* - d: data, in whatever form it's provided
* - c: calcdata, turned into radians (for linear axes)
* or category indices (category axes)
* - t: tick calcdata, just like 'c' but in degrees for linear axes
* - g: geometric calcdata, radians coordinates that take into account
* axis rotation and direction
*
* Then, 'g'eometric data is ready to be converted to (x,y).
*/
module.exports = function setConvert(ax, polarLayout, fullLayout) {
setConvertCartesian(ax, fullLayout);
switch (ax._id) {
case 'x':
case 'radialaxis':
setConvertRadial(ax, polarLayout);
break;
case 'angularaxis':
setConvertAngular(ax, polarLayout);
break;
}
};
function setConvertRadial(ax, polarLayout) {
var subplot = polarLayout._subplot;
ax.setGeometry = function () {
var rl0 = ax._rl[0];
var rl1 = ax._rl[1];
var b = subplot.innerRadius;
var m = (subplot.radius - b) / (rl1 - rl0);
var b2 = b / m;
var rFilter = rl0 > rl1 ? function (v) {
return v <= 0;
} : function (v) {
return v >= 0;
};
ax.c2g = function (v) {
var r = ax.c2l(v) - rl0;
return (rFilter(r) ? r : 0) + b2;
};
ax.g2c = function (v) {
return ax.l2c(v + rl0 - b2);
};
ax.g2p = function (v) {
return v * m;
};
ax.c2p = function (v) {
return ax.g2p(ax.c2g(v));
};
};
}
function toRadians(v, unit) {
return unit === 'degrees' ? deg2rad(v) : v;
}
function fromRadians(v, unit) {
return unit === 'degrees' ? rad2deg(v) : v;
}
function setConvertAngular(ax, polarLayout) {
var axType = ax.type;
if (axType === 'linear') {
var _d2c = ax.d2c;
var _c2d = ax.c2d;
ax.d2c = function (v, unit) {
return toRadians(_d2c(v), unit);
};
ax.c2d = function (v, unit) {
return _c2d(fromRadians(v, unit));
};
}
// override makeCalcdata to handle thetaunit and special theta0/dtheta logic
ax.makeCalcdata = function (trace, coord) {
var arrayIn = trace[coord];
var len = trace._length;
var arrayOut, i;
var _d2c = function (v) {
return ax.d2c(v, trace.thetaunit);
};
if (arrayIn) {
arrayOut = new Array(len);
for (i = 0; i < len; i++) {
arrayOut[i] = _d2c(arrayIn[i]);
}
} else {
var coord0 = coord + '0';
var dcoord = 'd' + coord;
var v0 = coord0 in trace ? _d2c(trace[coord0]) : 0;
var dv = trace[dcoord] ? _d2c(trace[dcoord]) : (ax.period || 2 * Math.PI) / len;
arrayOut = new Array(len);
for (i = 0; i < len; i++) {
arrayOut[i] = v0 + i * dv;
}
}
return arrayOut;
};
// N.B. we mock the axis 'range' here
ax.setGeometry = function () {
var sector = polarLayout.sector;
var sectorInRad = sector.map(deg2rad);
var dir = {
clockwise: -1,
counterclockwise: 1
}[ax.direction];
var rot = deg2rad(ax.rotation);
var rad2g = function (v) {
return dir * v + rot;
};
var g2rad = function (v) {
return (v - rot) / dir;
};
var rad2c, c2rad;
var rad2t, t2rad;
switch (axType) {
case 'linear':
c2rad = rad2c = Lib.identity;
t2rad = deg2rad;
rad2t = rad2deg;
// Set the angular range in degrees to make auto-tick computation cleaner,
// changing rotation/direction should not affect the angular tick value.
ax.range = Lib.isFullCircle(sectorInRad) ? [sector[0], sector[0] + 360] : sectorInRad.map(g2rad).map(rad2deg);
break;
case 'category':
var catLen = ax._categories.length;
var _period = ax.period ? Math.max(ax.period, catLen) : catLen;
// fallback in case all categories have been filtered out
if (_period === 0) _period = 1;
c2rad = t2rad = function (v) {
return v * 2 * Math.PI / _period;
};
rad2c = rad2t = function (v) {
return v * _period / Math.PI / 2;
};
ax.range = [0, _period];
break;
}
ax.c2g = function (v) {
return rad2g(c2rad(v));
};
ax.g2c = function (v) {
return rad2c(g2rad(v));
};
ax.t2g = function (v) {
return rad2g(t2rad(v));
};
ax.g2t = function (v) {
return rad2t(g2rad(v));
};
};
}
/***/ }),
/***/ 55012:
/***/ (function(module) {
"use strict";
module.exports = {
attr: 'subplot',
name: 'smith',
axisNames: ['realaxis', 'imaginaryaxis' // imaginary axis should be second here so that the `tickvals` defaults could be inherited from realaxis
],
axisName2dataArray: {
imaginaryaxis: 'imag',
realaxis: 'real'
}
};
/***/ }),
/***/ 36416:
/***/ (function(module) {
"use strict";
function sign(x) {
return x < 0 ? -1 : x > 0 ? 1 : 0;
}
// adapted from Mike Bostock's https://observablehq.com/@mbostock/smith-chart
function smith(a) {
var R = a[0];
var X = a[1];
if (!isFinite(R) || !isFinite(X)) return [1, 0];
var D = (R + 1) * (R + 1) + X * X;
return [(R * R + X * X - 1) / D, 2 * X / D];
}
function transform(subplot, a) {
var x = a[0];
var y = a[1];
return [x * subplot.radius + subplot.cx, -y * subplot.radius + subplot.cy];
}
function scale(subplot, r) {
return r * subplot.radius;
}
function reactanceArc(subplot, X, R1, R2) {
var t1 = transform(subplot, smith([R1, X]));
var x1 = t1[0];
var y1 = t1[1];
var t2 = transform(subplot, smith([R2, X]));
var x2 = t2[0];
var y2 = t2[1];
if (X === 0) {
return ['M' + x1 + ',' + y1, 'L' + x2 + ',' + y2].join(' ');
}
var r = scale(subplot, 1 / Math.abs(X));
return ['M' + x1 + ',' + y1, 'A' + r + ',' + r + ' 0 0,' + (X < 0 ? 1 : 0) + ' ' + x2 + ',' + y2].join(' ');
}
function resistanceArc(subplot, R, X1, X2) {
var r = scale(subplot, 1 / (R + 1));
var t1 = transform(subplot, smith([R, X1]));
var x1 = t1[0];
var y1 = t1[1];
var t2 = transform(subplot, smith([R, X2]));
var x2 = t2[0];
var y2 = t2[1];
if (sign(X1) !== sign(X2)) {
var t0 = transform(subplot, smith([R, 0]));
var x0 = t0[0];
var y0 = t0[1];
return ['M' + x1 + ',' + y1, 'A' + r + ',' + r + ' 0 0,' + (0 < X1 ? 0 : 1) + ' ' + x0 + ',' + y0, 'A' + r + ',' + r + ' 0 0,' + (X2 < 0 ? 0 : 1) + x2 + ',' + y2].join(' ');
}
return ['M' + x1 + ',' + y1, 'A' + r + ',' + r + ' 0 0,' + (X2 < X1 ? 0 : 1) + ' ' + x2 + ',' + y2].join(' ');
}
module.exports = {
smith: smith,
reactanceArc: reactanceArc,
resistanceArc: resistanceArc,
smithTransform: transform
};
/***/ }),
/***/ 47788:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var getSubplotCalcData = (__webpack_require__(84888)/* .getSubplotCalcData */ .KY);
var counterRegex = (__webpack_require__(3400).counterRegex);
var createPolar = __webpack_require__(62400);
var constants = __webpack_require__(55012);
var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);
var attributes = {};
attributes[attr] = {
valType: 'subplotid',
dflt: name,
editType: 'calc'
};
function plot(gd) {
var fullLayout = gd._fullLayout;
var calcData = gd.calcdata;
var subplotIds = fullLayout._subplots[name];
for (var i = 0; i < subplotIds.length; i++) {
var id = subplotIds[i];
var subplotCalcData = getSubplotCalcData(calcData, name, id);
var subplot = fullLayout[id]._subplot;
if (!subplot) {
subplot = createPolar(gd, id, true);
fullLayout[id]._subplot = subplot;
}
subplot.plot(subplotCalcData, fullLayout, gd._promises);
}
}
function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldIds = oldFullLayout._subplots[name] || [];
for (var i = 0; i < oldIds.length; i++) {
var id = oldIds[i];
var oldSubplot = oldFullLayout[id]._subplot;
if (!newFullLayout[id] && !!oldSubplot) {
oldSubplot.framework.remove();
for (var k in oldSubplot.clipPaths) {
oldSubplot.clipPaths[k].remove();
}
}
}
}
module.exports = {
attr: attr,
name: name,
idRoot: name,
idRegex: counter,
attrRegex: counter,
attributes: attributes,
layoutAttributes: __webpack_require__(6183),
supplyLayoutDefaults: __webpack_require__(22836),
plot: plot,
clean: clean,
toSVG: (__webpack_require__(57952).toSVG)
};
/***/ }),
/***/ 6183:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorAttrs = __webpack_require__(22548);
var axesAttrs = __webpack_require__(94724);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var extendFlat = (__webpack_require__(3400).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var axisLineGridAttr = overrideAll({
color: axesAttrs.color,
showline: extendFlat({}, axesAttrs.showline, {
dflt: true
}),
linecolor: axesAttrs.linecolor,
linewidth: axesAttrs.linewidth,
showgrid: extendFlat({}, axesAttrs.showgrid, {
dflt: true
}),
gridcolor: axesAttrs.gridcolor,
gridwidth: axesAttrs.gridwidth,
griddash: axesAttrs.griddash
}, 'plot', 'from-root');
var axisTickAttrs = overrideAll({
ticklen: axesAttrs.ticklen,
tickwidth: extendFlat({}, axesAttrs.tickwidth, {
dflt: 2
}),
tickcolor: axesAttrs.tickcolor,
showticklabels: axesAttrs.showticklabels,
labelalias: axesAttrs.labelalias,
showtickprefix: axesAttrs.showtickprefix,
tickprefix: axesAttrs.tickprefix,
showticksuffix: axesAttrs.showticksuffix,
ticksuffix: axesAttrs.ticksuffix,
tickfont: axesAttrs.tickfont,
tickformat: axesAttrs.tickformat,
hoverformat: axesAttrs.hoverformat,
layer: axesAttrs.layer
}, 'plot', 'from-root');
var realAxisAttrs = extendFlat({
visible: extendFlat({}, axesAttrs.visible, {
dflt: true
}),
tickvals: {
dflt: [0.2, 0.5, 1, 2, 5],
valType: 'data_array',
editType: 'plot'
},
tickangle: extendFlat({}, axesAttrs.tickangle, {
dflt: 90
}),
ticks: {
valType: 'enumerated',
values: ['top', 'bottom', ''],
editType: 'ticks'
},
side: {
valType: 'enumerated',
values: ['top', 'bottom'],
dflt: 'top',
editType: 'plot'
},
editType: 'calc'
}, axisLineGridAttr, axisTickAttrs);
var imaginaryAxisAttrs = extendFlat({
visible: extendFlat({}, axesAttrs.visible, {
dflt: true
}),
tickvals: {
valType: 'data_array',
editType: 'plot'
},
ticks: axesAttrs.ticks,
editType: 'calc'
}, axisLineGridAttr, axisTickAttrs);
module.exports = {
domain: domainAttrs({
name: 'smith',
editType: 'plot'
}),
bgcolor: {
valType: 'color',
editType: 'plot',
dflt: colorAttrs.background
},
realaxis: realAxisAttrs,
imaginaryaxis: imaginaryAxisAttrs,
editType: 'calc'
};
/***/ }),
/***/ 22836:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var Template = __webpack_require__(31780);
var handleSubplotDefaults = __webpack_require__(168);
var getSubplotData = (__webpack_require__(84888)/* .getSubplotData */ .op);
var handlePrefixSuffixDefaults = __webpack_require__(42568);
var handleTickLabelDefaults = __webpack_require__(95936);
var handleLineGridDefaults = __webpack_require__(42136);
var setConvertCartesian = __webpack_require__(78344);
var layoutAttributes = __webpack_require__(6183);
var constants = __webpack_require__(55012);
var axisNames = constants.axisNames;
var makeImagDflt = memoize(function (realTickvals) {
// TODO: handle this case outside supply defaults step
if (Lib.isTypedArray(realTickvals)) realTickvals = Array.from(realTickvals);
return realTickvals.slice().reverse().map(function (x) {
return -x;
}).concat([0]).concat(realTickvals);
}, String);
function handleDefaults(contIn, contOut, coerce, opts) {
var bgColor = coerce('bgcolor');
opts.bgColor = Color.combine(bgColor, opts.paper_bgcolor);
var subplotData = getSubplotData(opts.fullData, constants.name, opts.id);
var layoutOut = opts.layoutOut;
var axName;
function coerceAxis(attr, dflt) {
return coerce(axName + '.' + attr, dflt);
}
for (var i = 0; i < axisNames.length; i++) {
axName = axisNames[i];
if (!Lib.isPlainObject(contIn[axName])) {
contIn[axName] = {};
}
var axIn = contIn[axName];
var axOut = Template.newContainer(contOut, axName);
axOut._id = axOut._name = axName;
axOut._attr = opts.id + '.' + axName;
axOut._traceIndices = subplotData.map(function (t) {
return t._expandedIndex;
});
var visible = coerceAxis('visible');
axOut.type = 'linear';
setConvertCartesian(axOut, layoutOut);
handlePrefixSuffixDefaults(axIn, axOut, coerceAxis, axOut.type);
if (visible) {
var isRealAxis = axName === 'realaxis';
if (isRealAxis) coerceAxis('side');
if (isRealAxis) {
coerceAxis('tickvals');
} else {
var imagTickvalsDflt = makeImagDflt(contOut.realaxis.tickvals || layoutAttributes.realaxis.tickvals.dflt);
coerceAxis('tickvals', imagTickvalsDflt);
}
// TODO: handle this case outside supply defaults step
if (Lib.isTypedArray(axOut.tickvals)) axOut.tickvals = Array.from(axOut.tickvals);
var dfltColor;
var dfltFontColor;
var dfltFontSize;
var dfltFontFamily;
var font = opts.font || {};
if (visible) {
dfltColor = coerceAxis('color');
dfltFontColor = dfltColor === axIn.color ? dfltColor : font.color;
dfltFontSize = font.size;
dfltFontFamily = font.family;
}
handleTickLabelDefaults(axIn, axOut, coerceAxis, axOut.type, {
noAutotickangles: true,
noTicklabelshift: true,
noTicklabelstandoff: true,
noTicklabelstep: true,
noAng: !isRealAxis,
noExp: true,
font: {
color: dfltFontColor,
size: dfltFontSize,
family: dfltFontFamily
}
});
Lib.coerce2(contIn, contOut, layoutAttributes, axName + '.ticklen');
Lib.coerce2(contIn, contOut, layoutAttributes, axName + '.tickwidth');
Lib.coerce2(contIn, contOut, layoutAttributes, axName + '.tickcolor', contOut.color);
var showTicks = coerceAxis('ticks');
if (!showTicks) {
delete contOut[axName].ticklen;
delete contOut[axName].tickwidth;
delete contOut[axName].tickcolor;
}
handleLineGridDefaults(axIn, axOut, coerceAxis, {
dfltColor: dfltColor,
bgColor: opts.bgColor,
// default grid color is darker here (60%, vs cartesian default ~91%)
// because the grid is not square so the eye needs heavier cues to follow
blend: 60,
showLine: true,
showGrid: true,
noZeroLine: true,
attributes: layoutAttributes[axName]
});
coerceAxis('layer');
}
coerceAxis('hoverformat');
delete axOut.type;
axOut._input = axIn;
}
}
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
handleSubplotDefaults(layoutIn, layoutOut, fullData, {
noUirevision: true,
type: constants.name,
attributes: layoutAttributes,
handleDefaults: handleDefaults,
font: layoutOut.font,
paper_bgcolor: layoutOut.paper_bgcolor,
fullData: fullData,
layoutOut: layoutOut
});
};
function memoize(fn, keyFn) {
var cache = {};
return function (val) {
var newKey = keyFn ? keyFn(val) : val;
if (newKey in cache) {
return cache[newKey];
}
var out = fn(val);
cache[newKey] = out;
return out;
};
}
/***/ }),
/***/ 168:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Template = __webpack_require__(31780);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
/**
* Find and supply defaults to all subplots of a given type
* This handles subplots that are contained within one container - so
* gl3d, geo, ternary... but not 2d axes which have separate x and y axes
* finds subplots, coerces their `domain` attributes, then calls the
* given handleDefaults function to fill in everything else.
*
* layoutIn: the complete user-supplied input layout
* layoutOut: the complete finished layout
* fullData: the finished data array, used only to find subplots
* opts: {
* type: subplot type string
* attributes: subplot attributes object
* partition: 'x' or 'y', which direction to divide domain space by default
* (default 'x', ie side-by-side subplots)
* TODO: this option is only here because 3D and geo made opposite
* choices in this regard previously and I didn't want to change it.
* Instead we should do:
* - something consistent
* - something more square (4 cuts 2x2, 5/6 cuts 2x3, etc.)
* - something that includes all subplot types in one arrangement,
* now that we can have them together!
* handleDefaults: function of (subplotLayoutIn, subplotLayoutOut, coerce, opts)
* this opts object is passed through to handleDefaults, so attach any
* additional items needed by this function here as well
* }
*/
module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) {
var subplotType = opts.type;
var subplotAttributes = opts.attributes;
var handleDefaults = opts.handleDefaults;
var partition = opts.partition || 'x';
var ids = layoutOut._subplots[subplotType];
var idsLength = ids.length;
var baseId = idsLength && ids[0].replace(/\d+$/, '');
var subplotLayoutIn, subplotLayoutOut;
function coerce(attr, dflt) {
return Lib.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt);
}
for (var i = 0; i < idsLength; i++) {
var id = ids[i];
// ternary traces get a layout ternary for free!
if (layoutIn[id]) subplotLayoutIn = layoutIn[id];else subplotLayoutIn = layoutIn[id] = {};
subplotLayoutOut = Template.newContainer(layoutOut, id, baseId);
if (!opts.noUirevision) coerce('uirevision', layoutOut.uirevision);
var dfltDomains = {};
dfltDomains[partition] = [i / idsLength, (i + 1) / idsLength];
handleDomainDefaults(subplotLayoutOut, layoutOut, coerce, dfltDomains);
opts.id = id;
handleDefaults(subplotLayoutIn, subplotLayoutOut, coerce, opts);
}
};
/***/ }),
/***/ 21776:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var docs = __webpack_require__(26880);
var FORMAT_LINK = docs.FORMAT_LINK;
var DATE_FORMAT_LINK = docs.DATE_FORMAT_LINK;
function templateFormatStringDescription(opts) {
var supportOther = opts && opts.supportOther;
return ['Variables are inserted using %{variable},', 'for example "y: %{y}"' + (supportOther ? ' as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, *xother* will be added to those with different x positions from the first point. An underscore before or after *(x|y)other* will add a space on that side, only when this field is shown.' : '.'), 'Numbers are formatted using d3-format\'s syntax %{variable:d3-format}, for example "Price: %{y:$.2f}".', FORMAT_LINK, 'for details on the formatting syntax.', 'Dates are formatted using d3-time-format\'s syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}".', DATE_FORMAT_LINK, 'for details on the date formatting syntax.'].join(' ');
}
function shapeTemplateFormatStringDescription() {
return ['Variables are inserted using %{variable},', 'for example "x0: %{x0}".', 'Numbers are formatted using d3-format\'s syntax %{variable:d3-format}, for example "Price: %{x0:$.2f}". See', FORMAT_LINK, 'for details on the formatting syntax.', 'Dates are formatted using d3-time-format\'s syntax %{variable|d3-time-format}, for example "Day: %{x0|%m %b %Y}". See', DATE_FORMAT_LINK, 'for details on the date formatting syntax.', 'A single multiplication or division operation may be applied to numeric variables, and combined with', 'd3 number formatting, for example "Length in cm: %{x0*2.54}", "%{slope*60:.1f} meters per second."', 'For log axes, variable values are given in log units.', 'For date axes, x/y coordinate variables and center variables use datetimes, while all other variable values use values in ms.'].join(' ');
}
function describeVariables(extra) {
var descPart = extra.description ? ' ' + extra.description : '';
var keys = extra.keys || [];
if (keys.length > 0) {
var quotedKeys = [];
for (var i = 0; i < keys.length; i++) {
quotedKeys[i] = '`' + keys[i] + '`';
}
descPart = descPart + 'Finally, the template string has access to ';
if (keys.length === 1) {
descPart = descPart + 'variable ' + quotedKeys[0];
} else {
descPart = descPart + 'variables ' + quotedKeys.slice(0, -1).join(', ') + ' and ' + quotedKeys.slice(-1) + '.';
}
}
return descPart;
}
exports.Ks = function (opts, extra) {
opts = opts || {};
extra = extra || {};
var descPart = describeVariables(extra);
var hovertemplate = {
valType: 'string',
dflt: '',
editType: opts.editType || 'none'
};
if (opts.arrayOk !== false) {
hovertemplate.arrayOk = true;
}
return hovertemplate;
};
exports.Gw = function (opts, extra) {
opts = opts || {};
extra = extra || {};
var descPart = describeVariables(extra);
var texttemplate = {
valType: 'string',
dflt: '',
editType: opts.editType || 'calc'
};
if (opts.arrayOk !== false) {
texttemplate.arrayOk = true;
}
return texttemplate;
};
exports.ye = function (opts, extra) {
opts = opts || {};
extra = extra || {};
var newStr = opts.newshape ? 'new ' : '';
var descPart = describeVariables(extra);
var texttemplate = {
valType: 'string',
dflt: '',
editType: opts.editType || 'arraydraw'
};
return texttemplate;
};
/***/ }),
/***/ 19352:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Ternary = __webpack_require__(24696);
var getSubplotCalcData = (__webpack_require__(84888)/* .getSubplotCalcData */ .KY);
var counterRegex = (__webpack_require__(3400).counterRegex);
var TERNARY = 'ternary';
exports.name = TERNARY;
var attr = exports.attr = 'subplot';
exports.idRoot = TERNARY;
exports.idRegex = exports.attrRegex = counterRegex(TERNARY);
var attributes = exports.attributes = {};
attributes[attr] = {
valType: 'subplotid',
dflt: 'ternary',
editType: 'calc'
};
exports.layoutAttributes = __webpack_require__(86379);
exports.supplyLayoutDefaults = __webpack_require__(38536);
exports.plot = function plot(gd) {
var fullLayout = gd._fullLayout;
var calcData = gd.calcdata;
var ternaryIds = fullLayout._subplots[TERNARY];
for (var i = 0; i < ternaryIds.length; i++) {
var ternaryId = ternaryIds[i];
var ternaryCalcData = getSubplotCalcData(calcData, TERNARY, ternaryId);
var ternary = fullLayout[ternaryId]._subplot;
// If ternary is not instantiated, create one!
if (!ternary) {
ternary = new Ternary({
id: ternaryId,
graphDiv: gd,
container: fullLayout._ternarylayer.node()
}, fullLayout);
fullLayout[ternaryId]._subplot = ternary;
}
ternary.plot(ternaryCalcData, fullLayout, gd._promises);
}
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldTernaryKeys = oldFullLayout._subplots[TERNARY] || [];
for (var i = 0; i < oldTernaryKeys.length; i++) {
var oldTernaryKey = oldTernaryKeys[i];
var oldTernary = oldFullLayout[oldTernaryKey]._subplot;
if (!newFullLayout[oldTernaryKey] && !!oldTernary) {
oldTernary.plotContainer.remove();
oldTernary.clipDef.remove();
oldTernary.clipDefRelative.remove();
oldTernary.layers['a-title'].remove();
oldTernary.layers['b-title'].remove();
oldTernary.layers['c-title'].remove();
}
}
};
/***/ }),
/***/ 86379:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorAttrs = __webpack_require__(22548);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var axesAttrs = __webpack_require__(94724);
var overrideAll = (__webpack_require__(67824).overrideAll);
var extendFlat = (__webpack_require__(92880).extendFlat);
var ternaryAxesAttrs = {
title: {
text: axesAttrs.title.text,
font: axesAttrs.title.font
// TODO does standoff here make sense?
},
color: axesAttrs.color,
// ticks
tickmode: axesAttrs.minor.tickmode,
nticks: extendFlat({}, axesAttrs.nticks, {
dflt: 6,
min: 1
}),
tick0: axesAttrs.tick0,
dtick: axesAttrs.dtick,
tickvals: axesAttrs.tickvals,
ticktext: axesAttrs.ticktext,
ticks: axesAttrs.ticks,
ticklen: axesAttrs.ticklen,
tickwidth: axesAttrs.tickwidth,
tickcolor: axesAttrs.tickcolor,
ticklabelstep: axesAttrs.ticklabelstep,
showticklabels: axesAttrs.showticklabels,
labelalias: axesAttrs.labelalias,
showtickprefix: axesAttrs.showtickprefix,
tickprefix: axesAttrs.tickprefix,
showticksuffix: axesAttrs.showticksuffix,
ticksuffix: axesAttrs.ticksuffix,
showexponent: axesAttrs.showexponent,
exponentformat: axesAttrs.exponentformat,
minexponent: axesAttrs.minexponent,
separatethousands: axesAttrs.separatethousands,
tickfont: axesAttrs.tickfont,
tickangle: axesAttrs.tickangle,
tickformat: axesAttrs.tickformat,
tickformatstops: axesAttrs.tickformatstops,
hoverformat: axesAttrs.hoverformat,
// lines and grids
showline: extendFlat({}, axesAttrs.showline, {
dflt: true
}),
linecolor: axesAttrs.linecolor,
linewidth: axesAttrs.linewidth,
showgrid: extendFlat({}, axesAttrs.showgrid, {
dflt: true
}),
gridcolor: axesAttrs.gridcolor,
gridwidth: axesAttrs.gridwidth,
griddash: axesAttrs.griddash,
layer: axesAttrs.layer,
// range
min: {
valType: 'number',
dflt: 0,
min: 0
},
_deprecated: {
title: axesAttrs._deprecated.title,
titlefont: axesAttrs._deprecated.titlefont
}
};
var attrs = module.exports = overrideAll({
domain: domainAttrs({
name: 'ternary'
}),
bgcolor: {
valType: 'color',
dflt: colorAttrs.background
},
sum: {
valType: 'number',
dflt: 1,
min: 0
},
aaxis: ternaryAxesAttrs,
baxis: ternaryAxesAttrs,
caxis: ternaryAxesAttrs
}, 'plot', 'from-root');
// set uirevisions outside of `overrideAll` so we can get `editType: none`
attrs.uirevision = {
valType: 'any',
editType: 'none'
};
attrs.aaxis.uirevision = attrs.baxis.uirevision = attrs.caxis.uirevision = {
valType: 'any',
editType: 'none'
};
/***/ }),
/***/ 38536:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var Template = __webpack_require__(31780);
var Lib = __webpack_require__(3400);
var handleSubplotDefaults = __webpack_require__(168);
var handleTickLabelDefaults = __webpack_require__(95936);
var handlePrefixSuffixDefaults = __webpack_require__(42568);
var handleTickMarkDefaults = __webpack_require__(25404);
var handleTickValueDefaults = __webpack_require__(26332);
var handleLineGridDefaults = __webpack_require__(42136);
var layoutAttributes = __webpack_require__(86379);
var axesNames = ['aaxis', 'baxis', 'caxis'];
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
handleSubplotDefaults(layoutIn, layoutOut, fullData, {
type: 'ternary',
attributes: layoutAttributes,
handleDefaults: handleTernaryDefaults,
font: layoutOut.font,
paper_bgcolor: layoutOut.paper_bgcolor
});
};
function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, options) {
var bgColor = coerce('bgcolor');
var sum = coerce('sum');
options.bgColor = Color.combine(bgColor, options.paper_bgcolor);
var axName, containerIn, containerOut;
// TODO: allow most (if not all) axis attributes to be set
// in the outer container and used as defaults in the individual axes?
for (var j = 0; j < axesNames.length; j++) {
axName = axesNames[j];
containerIn = ternaryLayoutIn[axName] || {};
containerOut = Template.newContainer(ternaryLayoutOut, axName);
containerOut._name = axName;
handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut);
}
// if the min values contradict each other, set them all to default (0)
// and delete *all* the inputs so the user doesn't get confused later by
// changing one and having them all change.
var aaxis = ternaryLayoutOut.aaxis;
var baxis = ternaryLayoutOut.baxis;
var caxis = ternaryLayoutOut.caxis;
if (aaxis.min + baxis.min + caxis.min >= sum) {
aaxis.min = 0;
baxis.min = 0;
caxis.min = 0;
if (ternaryLayoutIn.aaxis) delete ternaryLayoutIn.aaxis.min;
if (ternaryLayoutIn.baxis) delete ternaryLayoutIn.baxis.min;
if (ternaryLayoutIn.caxis) delete ternaryLayoutIn.caxis.min;
}
}
function handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut) {
var axAttrs = layoutAttributes[containerOut._name];
function coerce(attr, dflt) {
return Lib.coerce(containerIn, containerOut, axAttrs, attr, dflt);
}
coerce('uirevision', ternaryLayoutOut.uirevision);
containerOut.type = 'linear'; // no other types allowed for ternary
var dfltColor = coerce('color');
// if axis.color was provided, use it for fonts too; otherwise,
// inherit from global font color in case that was provided.
var dfltFontColor = dfltColor !== axAttrs.color.dflt ? dfltColor : options.font.color;
var axName = containerOut._name;
var letterUpper = axName.charAt(0).toUpperCase();
var dfltTitle = 'Component ' + letterUpper;
var title = coerce('title.text', dfltTitle);
containerOut._hovertitle = title === dfltTitle ? title : letterUpper;
Lib.coerceFont(coerce, 'title.font', options.font, {
overrideDflt: {
size: Lib.bigFont(options.font.size),
color: dfltFontColor
}
});
// range is just set by 'min' - max is determined by the other axes mins
coerce('min');
handleTickValueDefaults(containerIn, containerOut, coerce, 'linear');
handlePrefixSuffixDefaults(containerIn, containerOut, coerce, 'linear');
handleTickLabelDefaults(containerIn, containerOut, coerce, 'linear', {
noAutotickangles: true,
noTicklabelshift: true,
noTicklabelstandoff: true
});
handleTickMarkDefaults(containerIn, containerOut, coerce, {
outerTicks: true
});
var showTickLabels = coerce('showticklabels');
if (showTickLabels) {
Lib.coerceFont(coerce, 'tickfont', options.font, {
overrideDflt: {
color: dfltFontColor
}
});
coerce('tickangle');
coerce('tickformat');
}
handleLineGridDefaults(containerIn, containerOut, coerce, {
dfltColor: dfltColor,
bgColor: options.bgColor,
// default grid color is darker here (60%, vs cartesian default ~91%)
// because the grid is not square so the eye needs heavier cues to follow
blend: 60,
showLine: true,
showGrid: true,
noZeroLine: true,
attributes: axAttrs
});
coerce('hoverformat');
coerce('layer');
}
/***/ }),
/***/ 24696:
/***/ (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 Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var _ = Lib._;
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var setConvert = __webpack_require__(78344);
var extendFlat = (__webpack_require__(92880).extendFlat);
var Plots = __webpack_require__(7316);
var Axes = __webpack_require__(54460);
var dragElement = __webpack_require__(86476);
var Fx = __webpack_require__(93024);
var dragHelpers = __webpack_require__(72760);
var freeMode = dragHelpers.freeMode;
var rectMode = dragHelpers.rectMode;
var Titles = __webpack_require__(81668);
var prepSelect = (__webpack_require__(22676).prepSelect);
var selectOnClick = (__webpack_require__(22676).selectOnClick);
var clearOutline = (__webpack_require__(22676).clearOutline);
var clearSelectionsCache = (__webpack_require__(22676).clearSelectionsCache);
var constants = __webpack_require__(33816);
function Ternary(options, fullLayout) {
this.id = options.id;
this.graphDiv = options.graphDiv;
this.init(fullLayout);
this.makeFramework(fullLayout);
// unfortunately, we have to keep track of some axis tick settings
// as ternary subplots do not implement the 'ticks' editType
this.aTickLayout = null;
this.bTickLayout = null;
this.cTickLayout = null;
}
module.exports = Ternary;
var proto = Ternary.prototype;
proto.init = function (fullLayout) {
this.container = fullLayout._ternarylayer;
this.defs = fullLayout._defs;
this.layoutId = fullLayout._uid;
this.traceHash = {};
this.layers = {};
};
proto.plot = function (ternaryCalcData, fullLayout) {
var _this = this;
var ternaryLayout = fullLayout[_this.id];
var graphSize = fullLayout._size;
_this._hasClipOnAxisFalse = false;
for (var i = 0; i < ternaryCalcData.length; i++) {
var trace = ternaryCalcData[i][0].trace;
if (trace.cliponaxis === false) {
_this._hasClipOnAxisFalse = true;
break;
}
}
_this.updateLayers(ternaryLayout);
_this.adjustLayout(ternaryLayout, graphSize);
Plots.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout);
_this.layers.plotbg.select('path').call(Color.fill, ternaryLayout.bgcolor);
};
proto.makeFramework = function (fullLayout) {
var _this = this;
var gd = _this.graphDiv;
var ternaryLayout = fullLayout[_this.id];
var clipId = _this.clipId = 'clip' + _this.layoutId + _this.id;
var clipIdRelative = _this.clipIdRelative = 'clip-relative' + _this.layoutId + _this.id;
// clippath for this ternary subplot
_this.clipDef = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function (s) {
s.append('path').attr('d', 'M0,0Z');
});
// 'relative' clippath (i.e. no translation) for this ternary subplot
_this.clipDefRelative = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipIdRelative, function (s) {
s.append('path').attr('d', 'M0,0Z');
});
// container for everything in this ternary subplot
_this.plotContainer = Lib.ensureSingle(_this.container, 'g', _this.id);
_this.updateLayers(ternaryLayout);
Drawing.setClipUrl(_this.layers.backplot, clipId, gd);
Drawing.setClipUrl(_this.layers.grids, clipId, gd);
};
proto.updateLayers = function (ternaryLayout) {
var _this = this;
var layers = _this.layers;
// inside that container, we have one container for the data, and
// one each for the three axes around it.
var plotLayers = ['draglayer', 'plotbg', 'backplot', 'grids'];
if (ternaryLayout.aaxis.layer === 'below traces') {
plotLayers.push('aaxis', 'aline');
}
if (ternaryLayout.baxis.layer === 'below traces') {
plotLayers.push('baxis', 'bline');
}
if (ternaryLayout.caxis.layer === 'below traces') {
plotLayers.push('caxis', 'cline');
}
plotLayers.push('frontplot');
if (ternaryLayout.aaxis.layer === 'above traces') {
plotLayers.push('aaxis', 'aline');
}
if (ternaryLayout.baxis.layer === 'above traces') {
plotLayers.push('baxis', 'bline');
}
if (ternaryLayout.caxis.layer === 'above traces') {
plotLayers.push('caxis', 'cline');
}
var toplevel = _this.plotContainer.selectAll('g.toplevel').data(plotLayers, String);
var grids = ['agrid', 'bgrid', 'cgrid'];
toplevel.enter().append('g').attr('class', function (d) {
return 'toplevel ' + d;
}).each(function (d) {
var s = d3.select(this);
layers[d] = s;
// containers for different trace types.
// NOTE - this is different from cartesian, where all traces
// are in front of grids. Here I'm putting maps behind the grids
// so the grids will always be visible if they're requested.
// Perhaps we want that for cartesian too?
if (d === 'frontplot') {
s.append('g').classed('scatterlayer', true);
} else if (d === 'backplot') {
s.append('g').classed('maplayer', true);
} else if (d === 'plotbg') {
s.append('path').attr('d', 'M0,0Z');
} else if (d === 'aline' || d === 'bline' || d === 'cline') {
s.append('path');
} else if (d === 'grids') {
grids.forEach(function (d) {
layers[d] = s.append('g').classed('grid ' + d, true);
});
}
});
toplevel.order();
};
var whRatio = Math.sqrt(4 / 3);
proto.adjustLayout = function (ternaryLayout, graphSize) {
var _this = this;
var domain = ternaryLayout.domain;
var xDomainCenter = (domain.x[0] + domain.x[1]) / 2;
var yDomainCenter = (domain.y[0] + domain.y[1]) / 2;
var xDomain = domain.x[1] - domain.x[0];
var yDomain = domain.y[1] - domain.y[0];
var wmax = xDomain * graphSize.w;
var hmax = yDomain * graphSize.h;
var sum = ternaryLayout.sum;
var amin = ternaryLayout.aaxis.min;
var bmin = ternaryLayout.baxis.min;
var cmin = ternaryLayout.caxis.min;
var x0, y0, w, h, xDomainFinal, yDomainFinal;
if (wmax > whRatio * hmax) {
h = hmax;
w = h * whRatio;
} else {
w = wmax;
h = w / whRatio;
}
xDomainFinal = xDomain * w / wmax;
yDomainFinal = yDomain * h / hmax;
x0 = graphSize.l + graphSize.w * xDomainCenter - w / 2;
y0 = graphSize.t + graphSize.h * (1 - yDomainCenter) - h / 2;
_this.x0 = x0;
_this.y0 = y0;
_this.w = w;
_this.h = h;
_this.sum = sum;
// set up the x and y axis objects we'll use to lay out the points
_this.xaxis = {
type: 'linear',
range: [amin + 2 * cmin - sum, sum - amin - 2 * bmin],
domain: [xDomainCenter - xDomainFinal / 2, xDomainCenter + xDomainFinal / 2],
_id: 'x'
};
setConvert(_this.xaxis, _this.graphDiv._fullLayout);
_this.xaxis.setScale();
_this.xaxis.isPtWithinRange = function (d) {
return d.a >= _this.aaxis.range[0] && d.a <= _this.aaxis.range[1] && d.b >= _this.baxis.range[1] && d.b <= _this.baxis.range[0] && d.c >= _this.caxis.range[1] && d.c <= _this.caxis.range[0];
};
_this.yaxis = {
type: 'linear',
range: [amin, sum - bmin - cmin],
domain: [yDomainCenter - yDomainFinal / 2, yDomainCenter + yDomainFinal / 2],
_id: 'y'
};
setConvert(_this.yaxis, _this.graphDiv._fullLayout);
_this.yaxis.setScale();
_this.yaxis.isPtWithinRange = function () {
return true;
};
// set up the modified axes for tick drawing
var yDomain0 = _this.yaxis.domain[0];
// aaxis goes up the left side. Set it up as a y axis, but with
// fictitious angles and domain, but then rotate and translate
// it into place at the end
var aaxis = _this.aaxis = extendFlat({}, ternaryLayout.aaxis, {
range: [amin, sum - bmin - cmin],
side: 'left',
// tickangle = 'auto' means 0 anyway for a y axis, need to coerce to 0 here
// so we can shift by 30.
tickangle: (+ternaryLayout.aaxis.tickangle || 0) - 30,
domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
anchor: 'free',
position: 0,
_id: 'y',
_length: w
});
setConvert(aaxis, _this.graphDiv._fullLayout);
aaxis.setScale();
// baxis goes across the bottom (backward). We can set it up as an x axis
// without any enclosing transformation.
var baxis = _this.baxis = extendFlat({}, ternaryLayout.baxis, {
range: [sum - amin - cmin, bmin],
side: 'bottom',
domain: _this.xaxis.domain,
anchor: 'free',
position: 0,
_id: 'x',
_length: w
});
setConvert(baxis, _this.graphDiv._fullLayout);
baxis.setScale();
// caxis goes down the right side. Set it up as a y axis, with
// post-transformation similar to aaxis
var caxis = _this.caxis = extendFlat({}, ternaryLayout.caxis, {
range: [sum - amin - bmin, cmin],
side: 'right',
tickangle: (+ternaryLayout.caxis.tickangle || 0) + 30,
domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
anchor: 'free',
position: 0,
_id: 'y',
_length: w
});
setConvert(caxis, _this.graphDiv._fullLayout);
caxis.setScale();
var triangleClip = 'M' + x0 + ',' + (y0 + h) + 'h' + w + 'l-' + w / 2 + ',-' + h + 'Z';
_this.clipDef.select('path').attr('d', triangleClip);
_this.layers.plotbg.select('path').attr('d', triangleClip);
var triangleClipRelative = 'M0,' + h + 'h' + w + 'l-' + w / 2 + ',-' + h + 'Z';
_this.clipDefRelative.select('path').attr('d', triangleClipRelative);
var plotTransform = strTranslate(x0, y0);
_this.plotContainer.selectAll('.scatterlayer,.maplayer').attr('transform', plotTransform);
_this.clipDefRelative.select('path').attr('transform', null);
// TODO: shift axes to accommodate linewidth*sin(30) tick mark angle
// TODO: there's probably an easier way to handle these translations/offsets now...
var bTransform = strTranslate(x0 - baxis._offset, y0 + h);
_this.layers.baxis.attr('transform', bTransform);
_this.layers.bgrid.attr('transform', bTransform);
var aTransform = strTranslate(x0 + w / 2, y0) + 'rotate(30)' + strTranslate(0, -aaxis._offset);
_this.layers.aaxis.attr('transform', aTransform);
_this.layers.agrid.attr('transform', aTransform);
var cTransform = strTranslate(x0 + w / 2, y0) + 'rotate(-30)' + strTranslate(0, -caxis._offset);
_this.layers.caxis.attr('transform', cTransform);
_this.layers.cgrid.attr('transform', cTransform);
_this.drawAxes(true);
_this.layers.aline.select('path').attr('d', aaxis.showline ? 'M' + x0 + ',' + (y0 + h) + 'l' + w / 2 + ',-' + h : 'M0,0').call(Color.stroke, aaxis.linecolor || '#000').style('stroke-width', (aaxis.linewidth || 0) + 'px');
_this.layers.bline.select('path').attr('d', baxis.showline ? 'M' + x0 + ',' + (y0 + h) + 'h' + w : 'M0,0').call(Color.stroke, baxis.linecolor || '#000').style('stroke-width', (baxis.linewidth || 0) + 'px');
_this.layers.cline.select('path').attr('d', caxis.showline ? 'M' + (x0 + w / 2) + ',' + y0 + 'l' + w / 2 + ',' + h : 'M0,0').call(Color.stroke, caxis.linecolor || '#000').style('stroke-width', (caxis.linewidth || 0) + 'px');
if (!_this.graphDiv._context.staticPlot) {
_this.initInteractions();
}
Drawing.setClipUrl(_this.layers.frontplot, _this._hasClipOnAxisFalse ? null : _this.clipId, _this.graphDiv);
};
proto.drawAxes = function (doTitles) {
var _this = this;
var gd = _this.graphDiv;
var titlesuffix = _this.id.substr(7) + 'title';
var layers = _this.layers;
var aaxis = _this.aaxis;
var baxis = _this.baxis;
var caxis = _this.caxis;
_this.drawAx(aaxis);
_this.drawAx(baxis);
_this.drawAx(caxis);
if (doTitles) {
var apad = Math.max(aaxis.showticklabels ? aaxis.tickfont.size / 2 : 0, (caxis.showticklabels ? caxis.tickfont.size * 0.75 : 0) + (caxis.ticks === 'outside' ? caxis.ticklen * 0.87 : 0));
var bpad = (baxis.showticklabels ? baxis.tickfont.size : 0) + (baxis.ticks === 'outside' ? baxis.ticklen : 0) + 3;
layers['a-title'] = Titles.draw(gd, 'a' + titlesuffix, {
propContainer: aaxis,
propName: _this.id + '.aaxis.title',
placeholder: _(gd, 'Click to enter Component A title'),
attributes: {
x: _this.x0 + _this.w / 2,
y: _this.y0 - aaxis.title.font.size / 3 - apad,
'text-anchor': 'middle'
}
});
layers['b-title'] = Titles.draw(gd, 'b' + titlesuffix, {
propContainer: baxis,
propName: _this.id + '.baxis.title',
placeholder: _(gd, 'Click to enter Component B title'),
attributes: {
x: _this.x0 - bpad,
y: _this.y0 + _this.h + baxis.title.font.size * 0.83 + bpad,
'text-anchor': 'middle'
}
});
layers['c-title'] = Titles.draw(gd, 'c' + titlesuffix, {
propContainer: caxis,
propName: _this.id + '.caxis.title',
placeholder: _(gd, 'Click to enter Component C title'),
attributes: {
x: _this.x0 + _this.w + bpad,
y: _this.y0 + _this.h + caxis.title.font.size * 0.83 + bpad,
'text-anchor': 'middle'
}
});
}
};
proto.drawAx = function (ax) {
var _this = this;
var gd = _this.graphDiv;
var axName = ax._name;
var axLetter = axName.charAt(0);
var axId = ax._id;
var axLayer = _this.layers[axName];
var counterAngle = 30;
var stashKey = axLetter + 'tickLayout';
var newTickLayout = strTickLayout(ax);
if (_this[stashKey] !== newTickLayout) {
axLayer.selectAll('.' + axId + 'tick').remove();
_this[stashKey] = newTickLayout;
}
ax.setScale();
var vals = Axes.calcTicks(ax);
var valsClipped = Axes.clipEnds(ax, vals);
var transFn = Axes.makeTransTickFn(ax);
var tickSign = Axes.getTickSigns(ax)[2];
var caRad = Lib.deg2rad(counterAngle);
var pad = tickSign * (ax.linewidth || 1) / 2;
var len = tickSign * ax.ticklen;
var w = _this.w;
var h = _this.h;
var tickPath = axLetter === 'b' ? 'M0,' + pad + 'l' + Math.sin(caRad) * len + ',' + Math.cos(caRad) * len : 'M' + pad + ',0l' + Math.cos(caRad) * len + ',' + -Math.sin(caRad) * len;
var gridPath = {
a: 'M0,0l' + h + ',-' + w / 2,
b: 'M0,0l-' + w / 2 + ',-' + h,
c: 'M0,0l-' + h + ',' + w / 2
}[axLetter];
Axes.drawTicks(gd, ax, {
vals: ax.ticks === 'inside' ? valsClipped : vals,
layer: axLayer,
path: tickPath,
transFn: transFn,
crisp: false
});
Axes.drawGrid(gd, ax, {
vals: valsClipped,
layer: _this.layers[axLetter + 'grid'],
path: gridPath,
transFn: transFn,
crisp: false
});
Axes.drawLabels(gd, ax, {
vals: vals,
layer: axLayer,
transFn: transFn,
labelFns: Axes.makeLabelFns(ax, 0, counterAngle)
});
};
function strTickLayout(axLayout) {
return axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
}
// hard coded paths for zoom corners
// uses the same sizing as cartesian, length is MINZOOM/2, width is 3px
var CLEN = constants.MINZOOM / 2 + 0.87;
var BLPATH = 'm-0.87,.5h' + CLEN + 'v3h-' + (CLEN + 5.2) + 'l' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) + 'l2.6,1.5l-' + CLEN / 2 + ',' + CLEN * 0.87 + 'Z';
var BRPATH = 'm0.87,.5h-' + CLEN + 'v3h' + (CLEN + 5.2) + 'l-' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) + 'l-2.6,1.5l' + CLEN / 2 + ',' + CLEN * 0.87 + 'Z';
var TOPPATH = 'm0,1l' + CLEN / 2 + ',' + CLEN * 0.87 + 'l2.6,-1.5l-' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) + 'l-' + (CLEN / 2 + 2.6) + ',' + (CLEN * 0.87 + 4.5) + 'l2.6,1.5l' + CLEN / 2 + ',-' + CLEN * 0.87 + 'Z';
var STARTMARKER = 'm0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z';
// I guess this could be shared with cartesian... but for now it's separate.
var SHOWZOOMOUTTIP = true;
proto.clearOutline = function () {
clearSelectionsCache(this.dragOptions);
clearOutline(this.dragOptions.gd);
};
proto.initInteractions = function () {
var _this = this;
var dragger = _this.layers.plotbg.select('path').node();
var gd = _this.graphDiv;
var zoomLayer = gd._fullLayout._zoomlayer;
var scaleX;
var scaleY;
// use plotbg for the main interactions
this.dragOptions = {
element: dragger,
gd: gd,
plotinfo: {
id: _this.id,
domain: gd._fullLayout[_this.id].domain,
xaxis: _this.xaxis,
yaxis: _this.yaxis
},
subplot: _this.id,
prepFn: function (e, startX, startY) {
// these aren't available yet when initInteractions
// is called
_this.dragOptions.xaxes = [_this.xaxis];
_this.dragOptions.yaxes = [_this.yaxis];
scaleX = gd._fullLayout._invScaleX;
scaleY = gd._fullLayout._invScaleY;
var dragModeNow = _this.dragOptions.dragmode = gd._fullLayout.dragmode;
if (freeMode(dragModeNow)) _this.dragOptions.minDrag = 1;else _this.dragOptions.minDrag = undefined;
if (dragModeNow === 'zoom') {
_this.dragOptions.moveFn = zoomMove;
_this.dragOptions.clickFn = clickZoomPan;
_this.dragOptions.doneFn = zoomDone;
zoomPrep(e, startX, startY);
} else if (dragModeNow === 'pan') {
_this.dragOptions.moveFn = plotDrag;
_this.dragOptions.clickFn = clickZoomPan;
_this.dragOptions.doneFn = dragDone;
panPrep();
_this.clearOutline(gd);
} else if (rectMode(dragModeNow) || freeMode(dragModeNow)) {
prepSelect(e, startX, startY, _this.dragOptions, dragModeNow);
}
}
};
var x0, y0, mins0, span0, mins, lum, path0, dimmed, zb, corners;
function makeUpdate(_mins) {
var attrs = {};
attrs[_this.id + '.aaxis.min'] = _mins.a;
attrs[_this.id + '.baxis.min'] = _mins.b;
attrs[_this.id + '.caxis.min'] = _mins.c;
return attrs;
}
function clickZoomPan(numClicks, evt) {
var clickMode = gd._fullLayout.clickmode;
removeZoombox(gd);
if (numClicks === 2) {
gd.emit('plotly_doubleclick', null);
Registry.call('_guiRelayout', gd, makeUpdate({
a: 0,
b: 0,
c: 0
}));
}
if (clickMode.indexOf('select') > -1 && numClicks === 1) {
selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, _this.dragOptions);
}
if (clickMode.indexOf('event') > -1) {
Fx.click(gd, evt, _this.id);
}
}
function zoomPrep(e, startX, startY) {
var dragBBox = dragger.getBoundingClientRect();
x0 = startX - dragBBox.left;
y0 = startY - dragBBox.top;
gd._fullLayout._calcInverseTransform(gd);
var inverse = gd._fullLayout._invTransform;
var transformedCoords = Lib.apply3DTransform(inverse)(x0, y0);
x0 = transformedCoords[0];
y0 = transformedCoords[1];
mins0 = {
a: _this.aaxis.range[0],
b: _this.baxis.range[1],
c: _this.caxis.range[1]
};
mins = mins0;
span0 = _this.aaxis.range[1] - mins0.a;
lum = tinycolor(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance();
path0 = 'M0,' + _this.h + 'L' + _this.w / 2 + ', 0L' + _this.w + ',' + _this.h + 'Z';
dimmed = false;
zb = zoomLayer.append('path').attr('class', 'zoombox').attr('transform', strTranslate(_this.x0, _this.y0)).style({
fill: lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
'stroke-width': 0
}).attr('d', path0);
corners = zoomLayer.append('path').attr('class', 'zoombox-corners').attr('transform', strTranslate(_this.x0, _this.y0)).style({
fill: Color.background,
stroke: Color.defaultLine,
'stroke-width': 1,
opacity: 0
}).attr('d', 'M0,0Z');
_this.clearOutline(gd);
}
function getAFrac(x, y) {
return 1 - y / _this.h;
}
function getBFrac(x, y) {
return 1 - (x + (_this.h - y) / Math.sqrt(3)) / _this.w;
}
function getCFrac(x, y) {
return (x - (_this.h - y) / Math.sqrt(3)) / _this.w;
}
function zoomMove(dx0, dy0) {
var x1 = x0 + dx0 * scaleX;
var y1 = y0 + dy0 * scaleY;
var afrac = Math.max(0, Math.min(1, getAFrac(x0, y0), getAFrac(x1, y1)));
var bfrac = Math.max(0, Math.min(1, getBFrac(x0, y0), getBFrac(x1, y1)));
var cfrac = Math.max(0, Math.min(1, getCFrac(x0, y0), getCFrac(x1, y1)));
var xLeft = (afrac / 2 + cfrac) * _this.w;
var xRight = (1 - afrac / 2 - bfrac) * _this.w;
var xCenter = (xLeft + xRight) / 2;
var xSpan = xRight - xLeft;
var yBottom = (1 - afrac) * _this.h;
var yTop = yBottom - xSpan / whRatio;
if (xSpan < constants.MINZOOM) {
mins = mins0;
zb.attr('d', path0);
corners.attr('d', 'M0,0Z');
} else {
mins = {
a: mins0.a + afrac * span0,
b: mins0.b + bfrac * span0,
c: mins0.c + cfrac * span0
};
zb.attr('d', path0 + 'M' + xLeft + ',' + yBottom + 'H' + xRight + 'L' + xCenter + ',' + yTop + 'L' + xLeft + ',' + yBottom + 'Z');
corners.attr('d', 'M' + x0 + ',' + y0 + STARTMARKER + 'M' + xLeft + ',' + yBottom + BLPATH + 'M' + xRight + ',' + yBottom + BRPATH + 'M' + xCenter + ',' + yTop + TOPPATH);
}
if (!dimmed) {
zb.transition().style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : 'rgba(255,255,255,0.3)').duration(200);
corners.transition().style('opacity', 1).duration(200);
dimmed = true;
}
gd.emit('plotly_relayouting', makeUpdate(mins));
}
function zoomDone() {
removeZoombox(gd);
if (mins === mins0) return;
Registry.call('_guiRelayout', gd, makeUpdate(mins));
if (SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
Lib.notifier(_(gd, 'Double-click to zoom back out'), 'long');
SHOWZOOMOUTTIP = false;
}
}
function panPrep() {
mins0 = {
a: _this.aaxis.range[0],
b: _this.baxis.range[1],
c: _this.caxis.range[1]
};
mins = mins0;
}
function plotDrag(dx, dy) {
var dxScaled = dx / _this.xaxis._m;
var dyScaled = dy / _this.yaxis._m;
mins = {
a: mins0.a - dyScaled,
b: mins0.b + (dxScaled + dyScaled) / 2,
c: mins0.c - (dxScaled - dyScaled) / 2
};
var minsorted = [mins.a, mins.b, mins.c].sort(Lib.sorterAsc);
var minindices = {
a: minsorted.indexOf(mins.a),
b: minsorted.indexOf(mins.b),
c: minsorted.indexOf(mins.c)
};
if (minsorted[0] < 0) {
if (minsorted[1] + minsorted[0] / 2 < 0) {
minsorted[2] += minsorted[0] + minsorted[1];
minsorted[0] = minsorted[1] = 0;
} else {
minsorted[2] += minsorted[0] / 2;
minsorted[1] += minsorted[0] / 2;
minsorted[0] = 0;
}
mins = {
a: minsorted[minindices.a],
b: minsorted[minindices.b],
c: minsorted[minindices.c]
};
dy = (mins0.a - mins.a) * _this.yaxis._m;
dx = (mins0.c - mins.c - mins0.b + mins.b) * _this.xaxis._m;
}
// move the data (translate, don't redraw)
var plotTransform = strTranslate(_this.x0 + dx, _this.y0 + dy);
_this.plotContainer.selectAll('.scatterlayer,.maplayer').attr('transform', plotTransform);
var plotTransform2 = strTranslate(-dx, -dy);
_this.clipDefRelative.select('path').attr('transform', plotTransform2);
// move the ticks
_this.aaxis.range = [mins.a, _this.sum - mins.b - mins.c];
_this.baxis.range = [_this.sum - mins.a - mins.c, mins.b];
_this.caxis.range = [_this.sum - mins.a - mins.b, mins.c];
_this.drawAxes(false);
if (_this._hasClipOnAxisFalse) {
_this.plotContainer.select('.scatterlayer').selectAll('.trace').call(Drawing.hideOutsideRangePoints, _this);
}
gd.emit('plotly_relayouting', makeUpdate(mins));
}
function dragDone() {
Registry.call('_guiRelayout', gd, makeUpdate(mins));
}
// finally, set up hover and click
// these event handlers must already be set before dragElement.init
// so it can stash them and override them.
dragger.onmousemove = function (evt) {
Fx.hover(gd, evt, _this.id);
gd._fullLayout._lasthover = dragger;
gd._fullLayout._hoversubplot = _this.id;
};
dragger.onmouseout = function (evt) {
if (gd._dragging) return;
dragElement.unhover(gd, evt);
};
dragElement.init(this.dragOptions);
};
function removeZoombox(gd) {
d3.select(gd).selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners').remove();
}
/***/ }),
/***/ 24040:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Loggers = __webpack_require__(24248);
var noop = __webpack_require__(16628);
var pushUnique = __webpack_require__(52416);
var isPlainObject = __webpack_require__(63620);
var addStyleRule = (__webpack_require__(52200).addStyleRule);
var ExtendModule = __webpack_require__(92880);
var basePlotAttributes = __webpack_require__(45464);
var baseLayoutAttributes = __webpack_require__(64859);
var extendFlat = ExtendModule.extendFlat;
var extendDeepAll = ExtendModule.extendDeepAll;
exports.modules = {};
exports.allCategories = {};
exports.allTypes = [];
exports.subplotsRegistry = {};
exports.transformsRegistry = {};
exports.componentsRegistry = {};
exports.layoutArrayContainers = [];
exports.layoutArrayRegexes = [];
exports.traceLayoutAttributes = {};
exports.localeRegistry = {};
exports.apiMethodRegistry = {};
exports.collectableSubplotTypes = null;
/**
* Top-level register routine, exported as Plotly.register
*
* @param {object array or array of objects} _modules :
* module object or list of module object to register.
*
* A valid `moduleType: 'trace'` module has fields:
* - name {string} : the trace type
* - categories {array} : categories associated with this trace type,
* tested with Register.traceIs()
* - meta {object} : meta info (mostly for plot-schema)
*
* A valid `moduleType: 'locale'` module has fields:
* - name {string} : the locale name. Should be a 2-digit language string ('en', 'de')
* optionally with a country/region code ('en-GB', 'de-CH'). If a country
* code is used but the base language locale has not yet been supplied,
* we will use this locale for the base as well.
* - dictionary {object} : the dictionary mapping input strings to localized strings
* generally the keys should be the literal input strings, but
* if default translations are provided you can use any string as a key.
* - format {object} : a `d3.locale` format specifier for this locale
* any omitted keys we'll fall back on en-US.
*
* A valid `moduleType: 'transform'` module has fields:
* - name {string} : transform name
* - transform {function} : default-level transform function
* - calcTransform {function} : calc-level transform function
* - attributes {object} : transform attributes declarations
* - supplyDefaults {function} : attributes default-supply function
*
* A valid `moduleType: 'component'` module has fields:
* - name {string} : the component name, used it with Register.getComponentMethod()
* to employ component method.
*
* A valid `moduleType: 'apiMethod'` module has fields:
* - name {string} : the api method name.
* - fn {function} : the api method called with Register.call();
*
*/
exports.register = function register(_modules) {
exports.collectableSubplotTypes = null;
if (!_modules) {
throw new Error('No argument passed to Plotly.register.');
} else if (_modules && !Array.isArray(_modules)) {
_modules = [_modules];
}
for (var i = 0; i < _modules.length; i++) {
var newModule = _modules[i];
if (!newModule) {
throw new Error('Invalid module was attempted to be registered!');
}
switch (newModule.moduleType) {
case 'trace':
registerTraceModule(newModule);
break;
case 'transform':
registerTransformModule(newModule);
break;
case 'component':
registerComponentModule(newModule);
break;
case 'locale':
registerLocale(newModule);
break;
case 'apiMethod':
var name = newModule.name;
exports.apiMethodRegistry[name] = newModule.fn;
break;
default:
throw new Error('Invalid module was attempted to be registered!');
}
}
};
/**
* Get registered module using trace object or trace type
*
* @param {object||string} trace
* trace object with prop 'type' or trace type as a string
* @return {object}
* module object corresponding to trace type
*/
exports.getModule = function (trace) {
var _module = exports.modules[getTraceType(trace)];
if (!_module) return false;
return _module._module;
};
/**
* Determine if this trace type is in a given category
*
* @param {object||string} traceType
* a trace (object) or trace type (string)
* @param {string} category
* category in question
* @return {boolean}
*/
exports.traceIs = function (traceType, category) {
traceType = getTraceType(traceType);
// old Chart Studio Cloud workspace hack, nothing to see here
if (traceType === 'various') return false;
var _module = exports.modules[traceType];
if (!_module) {
if (traceType) {
Loggers.log('Unrecognized trace type ' + traceType + '.');
}
_module = exports.modules[basePlotAttributes.type.dflt];
}
return !!_module.categories[category];
};
/**
* Determine if this trace has a transform of the given type and return
* array of matching indices.
*
* @param {object} data
* a trace object (member of data or fullData)
* @param {string} type
* type of trace to test
* @return {array}
* array of matching indices. If none found, returns []
*/
exports.getTransformIndices = function (data, type) {
var indices = [];
var transforms = data.transforms || [];
for (var i = 0; i < transforms.length; i++) {
if (transforms[i].type === type) {
indices.push(i);
}
}
return indices;
};
/**
* Determine if this trace has a transform of the given type
*
* @param {object} data
* a trace object (member of data or fullData)
* @param {string} type
* type of trace to test
* @return {boolean}
*/
exports.hasTransform = function (data, type) {
var transforms = data.transforms || [];
for (var i = 0; i < transforms.length; i++) {
if (transforms[i].type === type) {
return true;
}
}
return false;
};
/**
* Retrieve component module method. Falls back on noop if either the
* module or the method is missing, so the result can always be safely called
*
* @param {string} name
* name of component (as declared in component module)
* @param {string} method
* name of component module method
* @return {function}
*/
exports.getComponentMethod = function (name, method) {
var _module = exports.componentsRegistry[name];
if (!_module) return noop;
return _module[method] || noop;
};
/**
* Call registered api method.
*
* @param {string} name : api method name
* @param {...array} args : arguments passed to api method
* @return {any} : returns api method output
*/
exports.call = function () {
var name = arguments[0];
var args = [].slice.call(arguments, 1);
return exports.apiMethodRegistry[name].apply(null, args);
};
function registerTraceModule(_module) {
var thisType = _module.name;
var categoriesIn = _module.categories;
var meta = _module.meta;
if (exports.modules[thisType]) {
Loggers.log('Type ' + thisType + ' already registered');
return;
}
if (!exports.subplotsRegistry[_module.basePlotModule.name]) {
registerSubplot(_module.basePlotModule);
}
var categoryObj = {};
for (var i = 0; i < categoriesIn.length; i++) {
categoryObj[categoriesIn[i]] = true;
exports.allCategories[categoriesIn[i]] = true;
}
exports.modules[thisType] = {
_module: _module,
categories: categoryObj
};
if (meta && Object.keys(meta).length) {
exports.modules[thisType].meta = meta;
}
exports.allTypes.push(thisType);
for (var componentName in exports.componentsRegistry) {
mergeComponentAttrsToTrace(componentName, thisType);
}
/*
* Collect all trace layout attributes in one place for easier lookup later
* but don't merge them into the base schema as it would confuse the docs
* (at least after https://github.com/plotly/documentation/issues/202 gets done!)
*/
if (_module.layoutAttributes) {
extendFlat(exports.traceLayoutAttributes, _module.layoutAttributes);
}
var basePlotModule = _module.basePlotModule;
var bpmName = basePlotModule.name;
// add mapbox-gl CSS here to avoid console warning on instantiation
if (bpmName === 'mapbox') {
var styleRules = basePlotModule.constants.styleRules;
for (var k in styleRules) {
addStyleRule('.js-plotly-plot .plotly .mapboxgl-' + k, styleRules[k]);
}
}
// if `plotly-geo-assets.js` is not included,
// add `PlotlyGeoAssets` global to stash references to all fetched
// topojson / geojson data
if ((bpmName === 'geo' || bpmName === 'mapbox') && window.PlotlyGeoAssets === undefined) {
window.PlotlyGeoAssets = {
topojson: {}
};
}
}
function registerSubplot(_module) {
var plotType = _module.name;
if (exports.subplotsRegistry[plotType]) {
Loggers.log('Plot type ' + plotType + ' already registered.');
return;
}
// relayout array handling will look for component module methods with this
// name and won't find them because this is a subplot module... but that
// should be fine, it will just fall back on redrawing the plot.
findArrayRegexps(_module);
// not sure what's best for the 'cartesian' type at this point
exports.subplotsRegistry[plotType] = _module;
for (var componentName in exports.componentsRegistry) {
mergeComponentAttrsToSubplot(componentName, _module.name);
}
}
function registerComponentModule(_module) {
if (typeof _module.name !== 'string') {
throw new Error('Component module *name* must be a string.');
}
var name = _module.name;
exports.componentsRegistry[name] = _module;
if (_module.layoutAttributes) {
if (_module.layoutAttributes._isLinkedToArray) {
pushUnique(exports.layoutArrayContainers, name);
}
findArrayRegexps(_module);
}
for (var traceType in exports.modules) {
mergeComponentAttrsToTrace(name, traceType);
}
for (var subplotName in exports.subplotsRegistry) {
mergeComponentAttrsToSubplot(name, subplotName);
}
for (var transformType in exports.transformsRegistry) {
mergeComponentAttrsToTransform(name, transformType);
}
if (_module.schema && _module.schema.layout) {
extendDeepAll(baseLayoutAttributes, _module.schema.layout);
}
}
function registerTransformModule(_module) {
if (typeof _module.name !== 'string') {
throw new Error('Transform module *name* must be a string.');
}
var prefix = 'Transform module ' + _module.name;
var hasTransform = typeof _module.transform === 'function';
var hasCalcTransform = typeof _module.calcTransform === 'function';
if (!hasTransform && !hasCalcTransform) {
throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.');
}
if (hasTransform && hasCalcTransform) {
Loggers.log([prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.'].join(' '));
}
if (!isPlainObject(_module.attributes)) {
Loggers.log(prefix + ' registered without an *attributes* object.');
}
if (typeof _module.supplyDefaults !== 'function') {
Loggers.log(prefix + ' registered without a *supplyDefaults* method.');
}
exports.transformsRegistry[_module.name] = _module;
for (var componentName in exports.componentsRegistry) {
mergeComponentAttrsToTransform(componentName, _module.name);
}
}
function registerLocale(_module) {
var locale = _module.name;
var baseLocale = locale.split('-')[0];
var newDict = _module.dictionary;
var newFormat = _module.format;
var hasDict = newDict && Object.keys(newDict).length;
var hasFormat = newFormat && Object.keys(newFormat).length;
var locales = exports.localeRegistry;
var localeObj = locales[locale];
if (!localeObj) locales[locale] = localeObj = {};
// Should we use this dict for the base locale?
// In case we're overwriting a previous dict for this locale, check
// whether the base matches the full locale dict now. If we're not
// overwriting, locales[locale] is undefined so this just checks if
// baseLocale already had a dict or not.
// Same logic for dateFormats
if (baseLocale !== locale) {
var baseLocaleObj = locales[baseLocale];
if (!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {};
if (hasDict && baseLocaleObj.dictionary === localeObj.dictionary) {
baseLocaleObj.dictionary = newDict;
}
if (hasFormat && baseLocaleObj.format === localeObj.format) {
baseLocaleObj.format = newFormat;
}
}
if (hasDict) localeObj.dictionary = newDict;
if (hasFormat) localeObj.format = newFormat;
}
function findArrayRegexps(_module) {
if (_module.layoutAttributes) {
var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps;
if (arrayAttrRegexps) {
for (var i = 0; i < arrayAttrRegexps.length; i++) {
pushUnique(exports.layoutArrayRegexes, arrayAttrRegexps[i]);
}
}
}
}
function mergeComponentAttrsToTrace(componentName, traceType) {
var componentSchema = exports.componentsRegistry[componentName].schema;
if (!componentSchema || !componentSchema.traces) return;
var traceAttrs = componentSchema.traces[traceType];
if (traceAttrs) {
extendDeepAll(exports.modules[traceType]._module.attributes, traceAttrs);
}
}
function mergeComponentAttrsToTransform(componentName, transformType) {
var componentSchema = exports.componentsRegistry[componentName].schema;
if (!componentSchema || !componentSchema.transforms) return;
var transformAttrs = componentSchema.transforms[transformType];
if (transformAttrs) {
extendDeepAll(exports.transformsRegistry[transformType].attributes, transformAttrs);
}
}
function mergeComponentAttrsToSubplot(componentName, subplotName) {
var componentSchema = exports.componentsRegistry[componentName].schema;
if (!componentSchema || !componentSchema.subplots) return;
var subplotModule = exports.subplotsRegistry[subplotName];
var subplotAttrs = subplotModule.layoutAttributes;
var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr;
if (Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0];
var componentLayoutAttrs = componentSchema.subplots[subplotAttr];
if (subplotAttrs && componentLayoutAttrs) {
extendDeepAll(subplotAttrs, componentLayoutAttrs);
}
}
function getTraceType(traceType) {
if (typeof traceType === 'object') traceType = traceType.type;
return traceType;
}
/***/ }),
/***/ 91536:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var extendFlat = Lib.extendFlat;
var extendDeep = Lib.extendDeep;
// Put default plotTile layouts here
function cloneLayoutOverride(tileClass) {
var override;
switch (tileClass) {
case 'themes__thumb':
override = {
autosize: true,
width: 150,
height: 150,
title: {
text: ''
},
showlegend: false,
margin: {
l: 5,
r: 5,
t: 5,
b: 5,
pad: 0
},
annotations: []
};
break;
case 'thumbnail':
override = {
title: {
text: ''
},
hidesources: true,
showlegend: false,
borderwidth: 0,
bordercolor: '',
margin: {
l: 1,
r: 1,
t: 1,
b: 1,
pad: 0
},
annotations: []
};
break;
default:
override = {};
}
return override;
}
function keyIsAxis(keyName) {
var types = ['xaxis', 'yaxis', 'zaxis'];
return types.indexOf(keyName.slice(0, 5)) > -1;
}
module.exports = function clonePlot(graphObj, options) {
var i;
var oldData = graphObj.data;
var oldLayout = graphObj.layout;
var newData = extendDeep([], oldData);
var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass));
var context = graphObj._context || {};
if (options.width) newLayout.width = options.width;
if (options.height) newLayout.height = options.height;
if (options.tileClass === 'thumbnail' || options.tileClass === 'themes__thumb') {
// kill annotations
newLayout.annotations = [];
var keys = Object.keys(newLayout);
for (i = 0; i < keys.length; i++) {
if (keyIsAxis(keys[i])) {
newLayout[keys[i]].title = {
text: ''
};
}
}
// kill colorbar and pie labels
for (i = 0; i < newData.length; i++) {
var trace = newData[i];
trace.showscale = false;
if (trace.marker) trace.marker.showscale = false;
if (Registry.traceIs(trace, 'pie-like')) trace.textposition = 'none';
}
}
if (Array.isArray(options.annotations)) {
for (i = 0; i < options.annotations.length; i++) {
newLayout.annotations.push(options.annotations[i]);
}
}
// TODO: does this scene modification really belong here?
// If we still need it, can it move into the gl3d module?
var sceneIds = Object.keys(newLayout).filter(function (key) {
return key.match(/^scene\d*$/);
});
if (sceneIds.length) {
var axesImageOverride = {};
if (options.tileClass === 'thumbnail') {
axesImageOverride = {
title: {
text: ''
},
showaxeslabels: false,
showticklabels: false,
linetickenable: false
};
}
for (i = 0; i < sceneIds.length; i++) {
var scene = newLayout[sceneIds[i]];
if (!scene.xaxis) {
scene.xaxis = {};
}
if (!scene.yaxis) {
scene.yaxis = {};
}
if (!scene.zaxis) {
scene.zaxis = {};
}
extendFlat(scene.xaxis, axesImageOverride);
extendFlat(scene.yaxis, axesImageOverride);
extendFlat(scene.zaxis, axesImageOverride);
// TODO what does this do?
scene._scene = null;
}
}
var gd = document.createElement('div');
if (options.tileClass) gd.className = options.tileClass;
var plotTile = {
gd: gd,
td: gd,
// for external (image server) compatibility
layout: newLayout,
data: newData,
config: {
staticPlot: options.staticPlot === undefined ? true : options.staticPlot,
plotGlPixelRatio: options.plotGlPixelRatio === undefined ? 2 : options.plotGlPixelRatio,
displaylogo: options.displaylogo || false,
showLink: options.showLink || false,
showTips: options.showTips || false,
mapboxAccessToken: context.mapboxAccessToken
}
};
if (options.setBackground !== 'transparent') {
plotTile.config.setBackground = options.setBackground || 'opaque';
}
// attaching the default Layout the gd, so you can grab it later
plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass);
return plotTile;
};
/***/ }),
/***/ 39792:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var toImage = __webpack_require__(67024);
var fileSaver = __webpack_require__(48616);
var helpers = __webpack_require__(81792);
/**
* Plotly.downloadImage
*
* @param {object | string | HTML div} gd
* can either be a data/layout/config object
* or an existing graph
* or an id to an existing graph
* @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));
}
// Drop normal font-weight, font-style and font-variant to reduce the size
var fw = this.style.fontWeight;
if (fw && (fw === 'normal' || fw === '400')) {
// font-weight 400 is similar to normal
txt.style('font-weight', undefined);
}
var fs = this.style.fontStyle;
if (fs && fs === 'normal') {
txt.style('font-style', undefined);
}
var fv = this.style.fontVariant;
if (fv && fv === 'normal') {
txt.style('font-variant', undefined);
}
});
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,
weight: defaultFont.weight,
style: defaultFont.style,
variant: defaultFont.variant,
textcase: defaultFont.textcase,
lineposition: defaultFont.lineposition,
shadow: defaultFont.shadow
};
}
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);
var weightValue = helpers.getValue(attributeValue.weight, index);
var styleValue = helpers.getValue(attributeValue.style, index);
var variantValue = helpers.getValue(attributeValue.variant, index);
var textcaseValue = helpers.getValue(attributeValue.textcase, index);
var linepositionValue = helpers.getValue(attributeValue.lineposition, index);
var shadowValue = helpers.getValue(attributeValue.shadow, 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),
weight: helpers.coerceString(attributeDefinition.weight, weightValue, defaultValue.weight),
style: helpers.coerceString(attributeDefinition.style, styleValue, defaultValue.style),
variant: helpers.coerceString(attributeDefinition.variant, variantValue, defaultValue.variant),
textcase: helpers.coerceString(attributeDefinition.variant, textcaseValue, defaultValue.textcase),
lineposition: helpers.coerceString(attributeDefinition.variant, linepositionValue, defaultValue.lineposition),
shadow: helpers.coerceString(attributeDefinition.variant, shadowValue, defaultValue.shadow)
};
}
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
};
/***/ }),
/***/ 78100:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var extendFlat = (__webpack_require__(92880).extendFlat);
var scatterPolarAttrs = __webpack_require__(8319);
var barAttrs = __webpack_require__(20832);
module.exports = {
r: scatterPolarAttrs.r,
theta: scatterPolarAttrs.theta,
r0: scatterPolarAttrs.r0,
dr: scatterPolarAttrs.dr,
theta0: scatterPolarAttrs.theta0,
dtheta: scatterPolarAttrs.dtheta,
thetaunit: scatterPolarAttrs.thetaunit,
// orientation: {
// valType: 'enumerated',
// values: ['radial', 'angular'],
// editType: 'calc+clearAxisTypes',
//
// },
base: extendFlat({}, barAttrs.base, {}),
offset: extendFlat({}, barAttrs.offset, {}),
width: extendFlat({}, barAttrs.width, {}),
text: extendFlat({}, barAttrs.text, {}),
hovertext: extendFlat({}, barAttrs.hovertext, {}),
// textposition: {},
// textfont: {},
// insidetextfont: {},
// outsidetextfont: {},
// constraintext: {},
// cliponaxis: extendFlat({}, barAttrs.cliponaxis, {dflt: false}),
marker: barPolarMarker(),
hoverinfo: scatterPolarAttrs.hoverinfo,
hovertemplate: hovertemplateAttrs(),
selected: barAttrs.selected,
unselected: barAttrs.unselected
// error_x (error_r, error_theta)
// error_y
};
function barPolarMarker() {
var marker = extendFlat({}, barAttrs.marker);
delete marker.cornerradius;
return marker;
}
/***/ }),
/***/ 47056:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var colorscaleCalc = __webpack_require__(47128);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var arraysToCalcdata = __webpack_require__(84664);
var setGroupPositions = (__webpack_require__(96376).setGroupPositions);
var calcSelection = __webpack_require__(4500);
var traceIs = (__webpack_require__(24040).traceIs);
var extendFlat = (__webpack_require__(3400).extendFlat);
function calc(gd, trace) {
var fullLayout = gd._fullLayout;
var subplotId = trace.subplot;
var radialAxis = fullLayout[subplotId].radialaxis;
var angularAxis = fullLayout[subplotId].angularaxis;
var rArray = radialAxis.makeCalcdata(trace, 'r');
var thetaArray = angularAxis.makeCalcdata(trace, 'theta');
var len = trace._length;
var cd = new Array(len);
// 'size' axis variables
var sArray = rArray;
// 'pos' axis variables
var pArray = thetaArray;
for (var i = 0; i < len; i++) {
cd[i] = {
p: pArray[i],
s: sArray[i]
};
}
// convert width and offset in 'c' coordinate,
// set 'c' value(s) in trace._width and trace._offset,
// to make Bar.crossTraceCalc "just work"
function d2c(attr) {
var val = trace[attr];
if (val !== undefined) {
trace['_' + attr] = isArrayOrTypedArray(val) ? angularAxis.makeCalcdata(trace, attr) : angularAxis.d2c(val, trace.thetaunit);
}
}
if (angularAxis.type === 'linear') {
d2c('width');
d2c('offset');
}
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;
}
function crossTraceCalc(gd, polarLayout, subplotId) {
var calcdata = gd.calcdata;
var barPolarCd = [];
for (var i = 0; i < calcdata.length; i++) {
var cdi = calcdata[i];
var trace = cdi[0].trace;
if (trace.visible === true && traceIs(trace, 'bar') && trace.subplot === subplotId) {
barPolarCd.push(cdi);
}
}
// to make _extremes is filled in correctly so that
// polar._subplot.radialAxis can get auotrange'd
// TODO clean up!
// I think we want to call getAutorange on polar.radialaxis
// NOT on polar._subplot.radialAxis
var rAxis = extendFlat({}, polarLayout.radialaxis, {
_id: 'x'
});
var aAxis = polarLayout.angularaxis;
setGroupPositions(gd, aAxis, rAxis, barPolarCd, {
mode: polarLayout.barmode,
norm: polarLayout.barnorm,
gap: polarLayout.bargap,
groupgap: polarLayout.bargroupgap
});
}
module.exports = {
calc: calc,
crossTraceCalc: crossTraceCalc
};
/***/ }),
/***/ 70384:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleRThetaDefaults = (__webpack_require__(85968).handleRThetaDefaults);
var handleStyleDefaults = __webpack_require__(55592);
var attributes = __webpack_require__(78100);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
if (!len) {
traceOut.visible = false;
return;
}
// coerce('orientation', (traceOut.theta && !traceOut.r) ? 'angular' : 'radial');
coerce('thetaunit');
coerce('base');
coerce('offset');
coerce('width');
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
// var textPosition = coerce('textposition');
// var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
// var hasInside = hasBoth || textPosition === 'inside';
// var hasOutside = hasBoth || textPosition === 'outside';
// if(hasInside || hasOutside) {
// var textFont = coerceFont(coerce, 'textfont', layout.font);
// if(hasInside) coerceFont(coerce, 'insidetextfont', textFont);
// if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont);
// coerce('constraintext');
// coerce('selected.textfont.color');
// coerce('unselected.textfont.color');
// coerce('cliponaxis');
// }
handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
/***/ }),
/***/ 68896:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Fx = __webpack_require__(93024);
var Lib = __webpack_require__(3400);
var getTraceColor = (__webpack_require__(63400).getTraceColor);
var fillText = Lib.fillText;
var makeHoverPointText = (__webpack_require__(8504).makeHoverPointText);
var isPtInsidePolygon = (__webpack_require__(57384).isPtInsidePolygon);
module.exports = function hoverPoints(pointData, xval, yval) {
var cd = pointData.cd;
var trace = cd[0].trace;
var subplot = pointData.subplot;
var radialAxis = subplot.radialAxis;
var angularAxis = subplot.angularAxis;
var vangles = subplot.vangles;
var inboxFn = vangles ? isPtInsidePolygon : Lib.isPtInsideSector;
var maxHoverDistance = pointData.maxHoverDistance;
var period = angularAxis._period || 2 * Math.PI;
var rVal = Math.abs(radialAxis.g2p(Math.sqrt(xval * xval + yval * yval)));
var thetaVal = Math.atan2(yval, xval);
// polar.(x|y)axis.p2c doesn't get the reversed radial axis range case right
if (radialAxis.range[0] > radialAxis.range[1]) {
thetaVal += Math.PI;
}
var distFn = function (di) {
if (inboxFn(rVal, thetaVal, [di.rp0, di.rp1], [di.thetag0, di.thetag1], vangles)) {
return maxHoverDistance +
// 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.
Math.min(1, Math.abs(di.thetag1 - di.thetag0) / period) - 1 +
// add a gradient so hovering near the end of a
// bar makes it a little closer match
(di.rp1 - rVal) / (di.rp1 - di.rp0) - 1;
} else {
return Infinity;
}
};
Fx.getClosest(cd, distFn, pointData);
if (pointData.index === false) return;
var index = pointData.index;
var cdi = cd[index];
pointData.x0 = pointData.x1 = cdi.ct[0];
pointData.y0 = pointData.y1 = cdi.ct[1];
var _cdi = Lib.extendFlat({}, cdi, {
r: cdi.s,
theta: cdi.p
});
fillText(cdi, trace, pointData);
makeHoverPointText(_cdi, trace, subplot, pointData);
pointData.hovertemplate = trace.hovertemplate;
pointData.color = getTraceColor(trace, cdi);
pointData.xLabelVal = pointData.yLabelVal = undefined;
if (cdi.s < 0) {
pointData.idealAlign = 'left';
}
return [pointData];
};
/***/ }),
/***/ 94456:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'barpolar',
basePlotModule: __webpack_require__(40872),
categories: ['polar', 'bar', 'showLegend'],
attributes: __webpack_require__(78100),
layoutAttributes: __webpack_require__(9320),
supplyDefaults: __webpack_require__(70384),
supplyLayoutDefaults: __webpack_require__(89580),
calc: (__webpack_require__(47056).calc),
crossTraceCalc: (__webpack_require__(47056).crossTraceCalc),
plot: __webpack_require__(42040),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(22852),
style: (__webpack_require__(60100).style),
styleOnSelect: (__webpack_require__(60100).styleOnSelect),
hoverPoints: __webpack_require__(68896),
selectPoints: __webpack_require__(45784),
meta: {}
};
/***/ }),
/***/ 9320:
/***/ (function(module) {
"use strict";
module.exports = {
barmode: {
valType: 'enumerated',
values: ['stack', 'overlay'],
dflt: 'stack',
editType: 'calc'
},
bargap: {
valType: 'number',
dflt: 0.1,
min: 0,
max: 1,
editType: 'calc'
}
};
/***/ }),
/***/ 89580:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attrs = __webpack_require__(9320);
module.exports = function (layoutIn, layoutOut, fullData) {
var subplotsDone = {};
var sp;
function coerce(attr, dflt) {
return Lib.coerce(layoutIn[sp] || {}, layoutOut[sp], attrs, attr, dflt);
}
for (var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (trace.type === 'barpolar' && trace.visible === true) {
sp = trace.subplot;
if (!subplotsDone[sp]) {
coerce('barmode');
coerce('bargap');
subplotsDone[sp] = 1;
}
}
}
};
/***/ }),
/***/ 42040:
/***/ (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 Drawing = __webpack_require__(43616);
var helpers = __webpack_require__(57384);
module.exports = function plot(gd, subplot, cdbar) {
var isStatic = gd._context.staticPlot;
var xa = subplot.xaxis;
var ya = subplot.yaxis;
var radialAxis = subplot.radialAxis;
var angularAxis = subplot.angularAxis;
var pathFn = makePathFn(subplot);
var barLayer = subplot.layers.frontplot.select('g.barlayer');
Lib.makeTraceGroups(barLayer, cdbar, 'trace bars').each(function () {
var plotGroup = d3.select(this);
var pointGroup = Lib.ensureSingle(plotGroup, 'g', 'points');
var bars = pointGroup.selectAll('g.point').data(Lib.identity);
bars.enter().append('g').style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke').style('stroke-miterlimit', 2).classed('point', true);
bars.exit().remove();
bars.each(function (di) {
var bar = d3.select(this);
var rp0 = di.rp0 = radialAxis.c2p(di.s0);
var rp1 = di.rp1 = radialAxis.c2p(di.s1);
var thetag0 = di.thetag0 = angularAxis.c2g(di.p0);
var thetag1 = di.thetag1 = angularAxis.c2g(di.p1);
var dPath;
if (!isNumeric(rp0) || !isNumeric(rp1) || !isNumeric(thetag0) || !isNumeric(thetag1) || rp0 === rp1 || thetag0 === thetag1) {
// do not remove blank bars, to keep data-to-node
// mapping intact during radial drag, that we
// can skip calling _module.style during interactions
dPath = 'M0,0Z';
} else {
// this 'center' pt is used for selections and hover labels
var rg1 = radialAxis.c2g(di.s1);
var thetagMid = (thetag0 + thetag1) / 2;
di.ct = [xa.c2p(rg1 * Math.cos(thetagMid)), ya.c2p(rg1 * Math.sin(thetagMid))];
dPath = pathFn(rp0, rp1, thetag0, thetag1);
}
Lib.ensureSingle(bar, 'path').attr('d', dPath);
});
// clip plotGroup, when trace layer isn't clipped
Drawing.setClipUrl(plotGroup, subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null, gd);
});
};
function makePathFn(subplot) {
var cxx = subplot.cxx;
var cyy = subplot.cyy;
if (subplot.vangles) {
return function (r0, r1, _a0, _a1) {
var a0, a1;
if (Lib.angleDelta(_a0, _a1) > 0) {
a0 = _a0;
a1 = _a1;
} else {
a0 = _a1;
a1 = _a0;
}
var va0 = helpers.findEnclosingVertexAngles(a0, subplot.vangles)[0];
var va1 = helpers.findEnclosingVertexAngles(a1, subplot.vangles)[1];
var vaBar = [va0, (a0 + a1) / 2, va1];
return helpers.pathPolygonAnnulus(r0, r1, a0, a1, vaBar, cxx, cyy);
};
}
return function (r0, r1, a0, a1) {
return Lib.pathAnnulus(r0, r1, a0, a1, cxx, cyy);
};
}
/***/ }),
/***/ 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
};
/***/ }),
/***/ 64216:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var extendFlat = (__webpack_require__(3400).extendFlat);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var OHLCattrs = __webpack_require__(20279);
var boxAttrs = __webpack_require__(63188);
function directionAttrs(lineColorDefault) {
return {
line: {
color: extendFlat({}, boxAttrs.line.color, {
dflt: lineColorDefault
}),
width: boxAttrs.line.width,
editType: 'style'
},
fillcolor: boxAttrs.fillcolor,
editType: 'style'
};
}
module.exports = {
xperiod: OHLCattrs.xperiod,
xperiod0: OHLCattrs.xperiod0,
xperiodalignment: OHLCattrs.xperiodalignment,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
x: OHLCattrs.x,
open: OHLCattrs.open,
high: OHLCattrs.high,
low: OHLCattrs.low,
close: OHLCattrs.close,
line: {
width: extendFlat({}, boxAttrs.line.width, {}),
editType: 'style'
},
increasing: directionAttrs(OHLCattrs.increasing.line.color.dflt),
decreasing: directionAttrs(OHLCattrs.decreasing.line.color.dflt),
text: OHLCattrs.text,
hovertext: OHLCattrs.hovertext,
whiskerwidth: extendFlat({}, boxAttrs.whiskerwidth, {
dflt: 0
}),
hoverlabel: OHLCattrs.hoverlabel,
zorder: boxAttrs.zorder
};
/***/ }),
/***/ 46283:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var alignPeriod = __webpack_require__(1220);
var calcCommon = (__webpack_require__(42812).calcCommon);
module.exports = function (gd, trace) {
var fullLayout = gd._fullLayout;
var xa = Axes.getFromId(gd, trace.xaxis);
var ya = Axes.getFromId(gd, trace.yaxis);
var origX = xa.makeCalcdata(trace, 'x');
var x = alignPeriod(trace, xa, 'x', origX).vals;
var cd = calcCommon(gd, trace, origX, x, ya, ptFunc);
if (cd.length) {
Lib.extendFlat(cd[0].t, {
num: fullLayout._numBoxes,
dPos: Lib.distinctVals(x).minDiff / 2,
posLetter: 'x',
valLetter: 'y'
});
fullLayout._numBoxes++;
return cd;
} else {
return [{
t: {
empty: true
}
}];
}
};
function ptFunc(o, h, l, c) {
return {
min: l,
q1: Math.min(o, c),
med: c,
q3: Math.max(o, c),
max: h
};
}
/***/ }),
/***/ 64588:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var handleOHLC = __webpack_require__(52744);
var handlePeriodDefaults = __webpack_require__(31147);
var attributes = __webpack_require__(64216);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleOHLC(traceIn, traceOut, coerce, layout);
if (!len) {
traceOut.visible = false;
return;
}
handlePeriodDefaults(traceIn, traceOut, layout, coerce, {
x: true
});
coerce('xhoverformat');
coerce('yhoverformat');
coerce('line.width');
handleDirection(traceIn, traceOut, coerce, 'increasing');
handleDirection(traceIn, traceOut, coerce, 'decreasing');
coerce('text');
coerce('hovertext');
coerce('whiskerwidth');
layout._requestRangeslider[traceOut.xaxis] = true;
coerce('zorder');
};
function handleDirection(traceIn, traceOut, coerce, direction) {
var lineColor = coerce(direction + '.line.color');
coerce(direction + '.line.width', traceOut.line.width);
coerce(direction + '.fillcolor', Color.addOpacity(lineColor, 0.5));
}
/***/ }),
/***/ 61712:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'candlestick',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', 'showLegend', 'candlestick', 'boxLayout'],
meta: {},
attributes: __webpack_require__(64216),
layoutAttributes: __webpack_require__(16560),
supplyLayoutDefaults: (__webpack_require__(68832).supplyLayoutDefaults),
crossTraceCalc: (__webpack_require__(96404).crossTraceCalc),
supplyDefaults: __webpack_require__(64588),
calc: __webpack_require__(46283),
plot: (__webpack_require__(18728).plot),
layerName: 'boxlayer',
style: (__webpack_require__(25776).style),
hoverPoints: (__webpack_require__(18720).hoverPoints),
selectPoints: __webpack_require__(97384)
};
/***/ }),
/***/ 93504:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var handleAxisDefaults = __webpack_require__(63856);
var Template = __webpack_require__(31780);
module.exports = function handleABDefaults(traceIn, traceOut, fullLayout, coerce, dfltColor) {
var a = coerce('a');
if (!a) {
coerce('da');
coerce('a0');
}
var b = coerce('b');
if (!b) {
coerce('db');
coerce('b0');
}
mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor);
};
function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) {
var axesList = ['aaxis', 'baxis'];
axesList.forEach(function (axName) {
var axLetter = axName.charAt(0);
var axIn = traceIn[axName] || {};
var axOut = Template.newContainer(traceOut, axName);
var defaultOptions = {
noAutotickangles: true,
noTicklabelshift: true,
noTicklabelstandoff: true,
noTicklabelstep: true,
tickfont: 'x',
id: axLetter + 'axis',
letter: axLetter,
font: traceOut.font,
name: axName,
data: traceIn[axLetter],
calendar: traceOut.calendar,
dfltColor: dfltColor,
bgColor: fullLayout.paper_bgcolor,
autotypenumbersDflt: fullLayout.autotypenumbers,
fullLayout: fullLayout
};
handleAxisDefaults(axIn, axOut, defaultOptions);
axOut._categories = axOut._categories || [];
// so we don't have to repeat autotype unnecessarily,
// copy an autotype back to traceIn
if (!traceIn[axName] && axIn.type !== '-') {
traceIn[axName] = {
type: axIn.type
};
}
});
}
/***/ }),
/***/ 51676:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
module.exports = function (a) {
return minMax(a, 0);
};
function minMax(a, depth) {
// Limit to ten dimensional datasets. This seems *exceedingly* unlikely to
// ever cause problems or even be a concern. It's include strictly so that
// circular arrays could never cause this to loop.
if (!isArrayOrTypedArray(a) || depth >= 10) {
return null;
}
var min = Infinity;
var max = -Infinity;
var n = a.length;
for (var i = 0; i < n; i++) {
var datum = a[i];
if (isArrayOrTypedArray(datum)) {
var result = minMax(datum, depth + 1);
if (result) {
min = Math.min(result[0], min);
max = Math.max(result[1], max);
}
} else {
min = Math.min(datum, min);
max = Math.max(datum, max);
}
}
return [min, max];
}
/***/ }),
/***/ 85720:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var axisAttrs = __webpack_require__(98692);
var colorAttrs = __webpack_require__(22548);
var carpetFont = fontAttrs({
editType: 'calc'
});
var zorder = (__webpack_require__(52904).zorder);
// TODO: inherit from global font
carpetFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
carpetFont.size.dflt = 12;
carpetFont.color.dflt = colorAttrs.defaultLine;
module.exports = {
carpet: {
valType: 'string',
editType: 'calc'
},
x: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
y: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
a: {
valType: 'data_array',
editType: 'calc'
},
a0: {
valType: 'number',
dflt: 0,
editType: 'calc'
},
da: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
b: {
valType: 'data_array',
editType: 'calc'
},
b0: {
valType: 'number',
dflt: 0,
editType: 'calc'
},
db: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
cheaterslope: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
aaxis: axisAttrs,
baxis: axisAttrs,
font: carpetFont,
color: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'plot'
},
transforms: undefined,
zorder: zorder
};
/***/ }),
/***/ 77712:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
/* This function retrns a set of control points that define a curve aligned along
* either the a or b axis. Exactly one of a or b must be an array defining the range
* spanned.
*
* Honestly this is the most complicated function I've implemente here so far because
* of the way it handles knot insertion and direction/axis-agnostic slices.
*/
module.exports = function (carpet, carpetcd, a, b) {
var idx, tangent, tanIsoIdx, tanIsoPar, segment, refidx;
var p0, p1, v0, v1, start, end, range;
var axis = isArrayOrTypedArray(a) ? 'a' : 'b';
var ax = axis === 'a' ? carpet.aaxis : carpet.baxis;
var smoothing = ax.smoothing;
var toIdx = axis === 'a' ? carpet.a2i : carpet.b2j;
var pt = axis === 'a' ? a : b;
var iso = axis === 'a' ? b : a;
var n = axis === 'a' ? carpetcd.a.length : carpetcd.b.length;
var m = axis === 'a' ? carpetcd.b.length : carpetcd.a.length;
var isoIdx = Math.floor(axis === 'a' ? carpet.b2j(iso) : carpet.a2i(iso));
var xy = axis === 'a' ? function (value) {
return carpet.evalxy([], value, isoIdx);
} : function (value) {
return carpet.evalxy([], isoIdx, value);
};
if (smoothing) {
tanIsoIdx = Math.max(0, Math.min(m - 2, isoIdx));
tanIsoPar = isoIdx - tanIsoIdx;
tangent = axis === 'a' ? function (i, ti) {
return carpet.dxydi([], i, tanIsoIdx, ti, tanIsoPar);
} : function (j, tj) {
return carpet.dxydj([], tanIsoIdx, j, tanIsoPar, tj);
};
}
var vstart = toIdx(pt[0]);
var vend = toIdx(pt[1]);
// So that we can make this work in two directions, flip all of the
// math functions if the direction is from higher to lower indices:
//
// Note that the tolerance is directional!
var dir = vstart < vend ? 1 : -1;
var tol = (vend - vstart) * 1e-8;
var dirfloor = dir > 0 ? Math.floor : Math.ceil;
var dirceil = dir > 0 ? Math.ceil : Math.floor;
var dirmin = dir > 0 ? Math.min : Math.max;
var dirmax = dir > 0 ? Math.max : Math.min;
var idx0 = dirfloor(vstart + tol);
var idx1 = dirceil(vend - tol);
p0 = xy(vstart);
var segments = [[p0]];
for (idx = idx0; idx * dir < idx1 * dir; idx += dir) {
segment = [];
start = dirmax(vstart, idx);
end = dirmin(vend, idx + dir);
range = end - start;
// In order to figure out which cell we're in for the derivative (remember,
// the derivatives are *not* constant across grid lines), let's just average
// the start and end points. This cuts out just a tiny bit of logic and
// there's really no computational difference:
refidx = Math.max(0, Math.min(n - 2, Math.floor(0.5 * (start + end))));
p1 = xy(end);
if (smoothing) {
v0 = tangent(refidx, start - refidx);
v1 = tangent(refidx, end - refidx);
segment.push([p0[0] + v0[0] / 3 * range, p0[1] + v0[1] / 3 * range]);
segment.push([p1[0] - v1[0] / 3 * range, p1[1] - v1[1] / 3 * range]);
}
segment.push(p1);
segments.push(segment);
p0 = p1;
}
return segments;
};
/***/ }),
/***/ 98692:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var colorAttrs = __webpack_require__(22548);
var axesAttrs = __webpack_require__(94724);
var descriptionWithDates = (__webpack_require__(29736).descriptionWithDates);
var overrideAll = (__webpack_require__(67824).overrideAll);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = {
color: {
valType: 'color',
editType: 'calc'
},
smoothing: {
valType: 'number',
dflt: 1,
min: 0,
max: 1.3,
editType: 'calc'
},
title: {
text: {
valType: 'string',
dflt: '',
editType: 'calc'
},
font: fontAttrs({
editType: 'calc'
}),
// TODO how is this different than `title.standoff`
offset: {
valType: 'number',
dflt: 10,
editType: 'calc'
},
editType: 'calc'
},
type: {
valType: 'enumerated',
// '-' means we haven't yet run autotype or couldn't find any data
// it gets turned into linear in gd._fullLayout but not copied back
// to gd.data like the others are.
values: ['-', 'linear', 'date', 'category'],
dflt: '-',
editType: 'calc'
},
autotypenumbers: axesAttrs.autotypenumbers,
autorange: {
valType: 'enumerated',
values: [true, false, 'reversed'],
dflt: true,
editType: 'calc'
},
rangemode: {
valType: 'enumerated',
values: ['normal', 'tozero', 'nonnegative'],
dflt: 'normal',
editType: 'calc'
},
range: {
valType: 'info_array',
editType: 'calc',
items: [{
valType: 'any',
editType: 'calc'
}, {
valType: 'any',
editType: 'calc'
}]
},
fixedrange: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
cheatertype: {
valType: 'enumerated',
values: ['index', 'value'],
dflt: 'value',
editType: 'calc'
},
tickmode: {
valType: 'enumerated',
values: ['linear', 'array'],
dflt: 'array',
editType: 'calc'
},
nticks: {
valType: 'integer',
min: 0,
dflt: 0,
editType: 'calc'
},
tickvals: {
valType: 'data_array',
editType: 'calc'
},
ticktext: {
valType: 'data_array',
editType: 'calc'
},
showticklabels: {
valType: 'enumerated',
values: ['start', 'end', 'both', 'none'],
dflt: 'start',
editType: 'calc'
},
labelalias: extendFlat({}, axesAttrs.labelalias, {
editType: 'calc'
}),
tickfont: fontAttrs({
editType: 'calc'
}),
tickangle: {
valType: 'angle',
dflt: 'auto',
editType: 'calc'
},
tickprefix: {
valType: 'string',
dflt: '',
editType: 'calc'
},
showtickprefix: {
valType: 'enumerated',
values: ['all', 'first', 'last', 'none'],
dflt: 'all',
editType: 'calc'
},
ticksuffix: {
valType: 'string',
dflt: '',
editType: 'calc'
},
showticksuffix: {
valType: 'enumerated',
values: ['all', 'first', 'last', 'none'],
dflt: 'all',
editType: 'calc'
},
showexponent: {
valType: 'enumerated',
values: ['all', 'first', 'last', 'none'],
dflt: 'all',
editType: 'calc'
},
exponentformat: {
valType: 'enumerated',
values: ['none', 'e', 'E', 'power', 'SI', 'B'],
dflt: 'B',
editType: 'calc'
},
minexponent: {
valType: 'number',
dflt: 3,
min: 0,
editType: 'calc'
},
separatethousands: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
tickformat: {
valType: 'string',
dflt: '',
editType: 'calc',
description: descriptionWithDates('tick label')
},
tickformatstops: overrideAll(axesAttrs.tickformatstops, 'calc', 'from-root'),
categoryorder: {
valType: 'enumerated',
values: ['trace', 'category ascending', 'category descending', 'array'
/* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later
],
dflt: 'trace',
editType: 'calc'
},
categoryarray: {
valType: 'data_array',
editType: 'calc'
},
labelpadding: {
valType: 'integer',
dflt: 10,
editType: 'calc'
},
labelprefix: {
valType: 'string',
editType: 'calc'
},
labelsuffix: {
valType: 'string',
dflt: '',
editType: 'calc'
},
// lines and grids
showline: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
linecolor: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'calc'
},
linewidth: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'calc'
},
gridcolor: {
valType: 'color',
editType: 'calc'
},
gridwidth: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'calc'
},
griddash: extendFlat({}, dash, {
editType: 'calc'
}),
showgrid: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
minorgridcount: {
valType: 'integer',
min: 0,
dflt: 0,
editType: 'calc'
},
minorgridwidth: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'calc'
},
minorgriddash: extendFlat({}, dash, {
editType: 'calc'
}),
minorgridcolor: {
valType: 'color',
dflt: colorAttrs.lightLine,
editType: 'calc'
},
startline: {
valType: 'boolean',
editType: 'calc'
},
startlinecolor: {
valType: 'color',
editType: 'calc'
},
startlinewidth: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
endline: {
valType: 'boolean',
editType: 'calc'
},
endlinewidth: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
endlinecolor: {
valType: 'color',
editType: 'calc'
},
tick0: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'calc'
},
dtick: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'calc'
},
arraytick0: {
valType: 'integer',
min: 0,
dflt: 0,
editType: 'calc'
},
arraydtick: {
valType: 'integer',
min: 1,
dflt: 1,
editType: 'calc'
},
_deprecated: {
title: {
valType: 'string',
editType: 'calc'
},
titlefont: fontAttrs({
editType: 'calc'
}),
titleoffset: {
valType: 'number',
dflt: 10,
editType: 'calc'
}
},
editType: 'calc'
};
/***/ }),
/***/ 63856:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var carpetAttrs = __webpack_require__(85720);
var addOpacity = (__webpack_require__(76308).addOpacity);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var handleTickValueDefaults = __webpack_require__(26332);
var handleTickLabelDefaults = __webpack_require__(95936);
var handlePrefixSuffixDefaults = __webpack_require__(42568);
var handleCategoryOrderDefaults = __webpack_require__(22416);
var setConvert = __webpack_require__(78344);
var autoType = __webpack_require__(52976);
/**
* options: object containing:
*
* letter: 'a' or 'b'
* title: name of the axis (ie 'Colorbar') to go in default title
* name: axis object name (ie 'xaxis') if one should be stored
* font: the default font to inherit
* outerTicks: boolean, should ticks default to outside?
* showGrid: boolean, should gridlines be shown by default?
* data: the plot data to use in choosing auto type
* bgColor: the plot background color, to calculate default gridline colors
*/
module.exports = function handleAxisDefaults(containerIn, containerOut, options) {
var letter = options.letter;
var font = options.font || {};
var attributes = carpetAttrs[letter + 'axis'];
function coerce(attr, dflt) {
return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
}
function coerce2(attr, dflt) {
return Lib.coerce2(containerIn, containerOut, attributes, attr, dflt);
}
// set up some private properties
if (options.name) {
containerOut._name = options.name;
containerOut._id = options.name;
}
// now figure out type and do some more initialization
coerce('autotypenumbers', options.autotypenumbersDflt);
var axType = coerce('type');
if (axType === '-') {
if (options.data) setAutoType(containerOut, options.data);
if (containerOut.type === '-') {
containerOut.type = 'linear';
} else {
// copy autoType back to input axis
// note that if this object didn't exist
// in the input layout, we have to put it in
// this happens in the main supplyDefaults function
axType = containerIn.type = containerOut.type;
}
}
coerce('smoothing');
coerce('cheatertype');
coerce('showticklabels');
coerce('labelprefix', letter + ' = ');
coerce('labelsuffix');
coerce('showtickprefix');
coerce('showticksuffix');
coerce('separatethousands');
coerce('tickformat');
coerce('exponentformat');
coerce('minexponent');
coerce('showexponent');
coerce('categoryorder');
coerce('tickmode');
coerce('tickvals');
coerce('ticktext');
coerce('tick0');
coerce('dtick');
if (containerOut.tickmode === 'array') {
coerce('arraytick0');
coerce('arraydtick');
}
coerce('labelpadding');
containerOut._hovertitle = letter;
if (axType === 'date') {
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
}
// we need some of the other functions setConvert attaches, but for
// path finding, override pixel scaling to simple passthrough (identity)
setConvert(containerOut, options.fullLayout);
containerOut.c2p = Lib.identity;
var dfltColor = coerce('color', options.dfltColor);
// if axis.color was provided, use it for fonts too; otherwise,
// inherit from global font color in case that was provided.
var dfltFontColor = dfltColor === containerIn.color ? dfltColor : font.color;
var title = coerce('title.text');
if (title) {
Lib.coerceFont(coerce, 'title.font', font, {
overrideDflt: {
size: Lib.bigFont(font.size),
color: dfltFontColor
}
});
coerce('title.offset');
}
coerce('tickangle');
var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range));
if (autoRange) coerce('rangemode');
coerce('range');
containerOut.cleanRange();
coerce('fixedrange');
handleTickValueDefaults(containerIn, containerOut, coerce, axType);
handlePrefixSuffixDefaults(containerIn, containerOut, coerce, axType, options);
handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
handleCategoryOrderDefaults(containerIn, containerOut, coerce, {
data: options.data,
dataAttr: letter
});
var gridColor = coerce2('gridcolor', addOpacity(dfltColor, 0.3));
var gridWidth = coerce2('gridwidth');
var gridDash = coerce2('griddash');
var showGrid = coerce('showgrid');
if (!showGrid) {
delete containerOut.gridcolor;
delete containerOut.gridwidth;
delete containerOut.griddash;
}
var startLineColor = coerce2('startlinecolor', dfltColor);
var startLineWidth = coerce2('startlinewidth', gridWidth);
var showStartLine = coerce('startline', containerOut.showgrid || !!startLineColor || !!startLineWidth);
if (!showStartLine) {
delete containerOut.startlinecolor;
delete containerOut.startlinewidth;
}
var endLineColor = coerce2('endlinecolor', dfltColor);
var endLineWidth = coerce2('endlinewidth', gridWidth);
var showEndLine = coerce('endline', containerOut.showgrid || !!endLineColor || !!endLineWidth);
if (!showEndLine) {
delete containerOut.endlinecolor;
delete containerOut.endlinewidth;
}
if (!showGrid) {
delete containerOut.gridcolor;
delete containerOut.gridwidth;
delete containerOut.griddash;
} else {
coerce('minorgridcount');
coerce('minorgridwidth', gridWidth);
coerce('minorgriddash', gridDash);
coerce('minorgridcolor', addOpacity(gridColor, 0.06));
if (!containerOut.minorgridcount) {
delete containerOut.minorgridwidth;
delete containerOut.minorgriddash;
delete containerOut.minorgridcolor;
}
}
if (containerOut.showticklabels === 'none') {
delete containerOut.tickfont;
delete containerOut.tickangle;
delete containerOut.showexponent;
delete containerOut.exponentformat;
delete containerOut.minexponent;
delete containerOut.tickformat;
delete containerOut.showticksuffix;
delete containerOut.showtickprefix;
}
if (!containerOut.showticksuffix) {
delete containerOut.ticksuffix;
}
if (!containerOut.showtickprefix) {
delete containerOut.tickprefix;
}
// It needs to be coerced, then something above overrides this deep in the axis code,
// but no, we *actually* want to coerce this.
coerce('tickmode');
return containerOut;
};
function setAutoType(ax, data) {
// new logic: let people specify any type they want,
// only autotype if type is '-'
if (ax.type !== '-') return;
var id = ax._id;
var axLetter = id.charAt(0);
var calAttr = axLetter + 'calendar';
var calendar = ax[calAttr];
ax.type = autoType(data, calendar, {
autotypenumbers: ax.autotypenumbers
});
}
/***/ }),
/***/ 58744:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var isArray1D = (__webpack_require__(3400).isArray1D);
var cheaterBasis = __webpack_require__(60776);
var arrayMinmax = __webpack_require__(51676);
var calcGridlines = __webpack_require__(19216);
var calcLabels = __webpack_require__(14724);
var calcClipPath = __webpack_require__(24944);
var clean2dArray = __webpack_require__(26136);
var smoothFill2dArray = __webpack_require__(51512);
var convertColumnData = __webpack_require__(2872);
var setConvert = __webpack_require__(81000);
module.exports = function calc(gd, trace) {
var xa = Axes.getFromId(gd, trace.xaxis);
var ya = Axes.getFromId(gd, trace.yaxis);
var aax = trace.aaxis;
var bax = trace.baxis;
var x = trace.x;
var y = trace.y;
var cols = [];
if (x && isArray1D(x)) cols.push('x');
if (y && isArray1D(y)) cols.push('y');
if (cols.length) {
convertColumnData(trace, aax, bax, 'a', 'b', cols);
}
var a = trace._a = trace._a || trace.a;
var b = trace._b = trace._b || trace.b;
x = trace._x || trace.x;
y = trace._y || trace.y;
var t = {};
if (trace._cheater) {
var avals = aax.cheatertype === 'index' ? a.length : a;
var bvals = bax.cheatertype === 'index' ? b.length : b;
x = cheaterBasis(avals, bvals, trace.cheaterslope);
}
trace._x = x = clean2dArray(x);
trace._y = y = clean2dArray(y);
// Fill in any undefined values with elliptic smoothing. This doesn't take
// into account the spacing of the values. That is, the derivatives should
// be modified to use a and b values. It's not that hard, but this is already
// moderate overkill for just filling in missing values.
smoothFill2dArray(x, a, b);
smoothFill2dArray(y, a, b);
setConvert(trace);
// create conversion functions that depend on the data
trace.setScale();
// This is a rather expensive scan. Nothing guarantees monotonicity,
// so we need to scan through all data to get proper ranges:
var xrange = arrayMinmax(x);
var yrange = arrayMinmax(y);
var dx = 0.5 * (xrange[1] - xrange[0]);
var xc = 0.5 * (xrange[1] + xrange[0]);
var dy = 0.5 * (yrange[1] - yrange[0]);
var yc = 0.5 * (yrange[1] + yrange[0]);
// Expand the axes to fit the plot, except just grow it by a factor of 1.3
// because the labels should be taken into account except that's difficult
// hence 1.3.
var grow = 1.3;
xrange = [xc - dx * grow, xc + dx * grow];
yrange = [yc - dy * grow, yc + dy * grow];
trace._extremes[xa._id] = Axes.findExtremes(xa, xrange, {
padded: true
});
trace._extremes[ya._id] = Axes.findExtremes(ya, yrange, {
padded: true
});
// Enumerate the gridlines, both major and minor, and store them on the trace
// object:
calcGridlines(trace, 'a', 'b');
calcGridlines(trace, 'b', 'a');
// Calculate the text labels for each major gridline and store them on the
// trace object:
calcLabels(trace, aax);
calcLabels(trace, bax);
// Tabulate points for the four segments that bound the axes so that we can
// map to pixel coordinates in the plot function and create a clip rect:
t.clipsegments = calcClipPath(trace._xctrl, trace._yctrl, aax, bax);
t.x = x;
t.y = y;
t.a = a;
t.b = b;
return [t];
};
/***/ }),
/***/ 24944:
/***/ (function(module) {
"use strict";
module.exports = function makeClipPath(xctrl, yctrl, aax, bax) {
var i, x, y;
var segments = [];
var asmoothing = !!aax.smoothing;
var bsmoothing = !!bax.smoothing;
var nea1 = xctrl[0].length - 1;
var neb1 = xctrl.length - 1;
// Along the lower a axis:
for (i = 0, x = [], y = []; i <= nea1; i++) {
x[i] = xctrl[0][i];
y[i] = yctrl[0][i];
}
segments.push({
x: x,
y: y,
bicubic: asmoothing
});
// Along the upper b axis:
for (i = 0, x = [], y = []; i <= neb1; i++) {
x[i] = xctrl[i][nea1];
y[i] = yctrl[i][nea1];
}
segments.push({
x: x,
y: y,
bicubic: bsmoothing
});
// Backwards along the upper a axis:
for (i = nea1, x = [], y = []; i >= 0; i--) {
x[nea1 - i] = xctrl[neb1][i];
y[nea1 - i] = yctrl[neb1][i];
}
segments.push({
x: x,
y: y,
bicubic: asmoothing
});
// Backwards along the lower b axis:
for (i = neb1, x = [], y = []; i >= 0; i--) {
x[neb1 - i] = xctrl[i][0];
y[neb1 - i] = yctrl[i][0];
}
segments.push({
x: x,
y: y,
bicubic: bsmoothing
});
return segments;
};
/***/ }),
/***/ 19216:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = function calcGridlines(trace, axisLetter, crossAxisLetter) {
var i, j, j0;
var eps, bounds, n1, n2, n, value, v;
var j1, v0, v1, d;
var data = trace['_' + axisLetter];
var axis = trace[axisLetter + 'axis'];
var gridlines = axis._gridlines = [];
var minorgridlines = axis._minorgridlines = [];
var boundarylines = axis._boundarylines = [];
var crossData = trace['_' + crossAxisLetter];
var crossAxis = trace[crossAxisLetter + 'axis'];
if (axis.tickmode === 'array') {
axis.tickvals = data.slice();
}
var xcp = trace._xctrl;
var ycp = trace._yctrl;
var nea = xcp[0].length;
var neb = xcp.length;
var na = trace._a.length;
var nb = trace._b.length;
Axes.prepTicks(axis);
// don't leave tickvals in axis looking like an attribute
if (axis.tickmode === 'array') delete axis.tickvals;
// The default is an empty array that will cause the join to remove the gridline if
// it's just disappeared:
// axis._startline = axis._endline = [];
// If the cross axis uses bicubic interpolation, then the grid
// lines fall once every three expanded grid row/cols:
var stride = axis.smoothing ? 3 : 1;
function constructValueGridline(value) {
var i, j, j0, tj, pxy, i0, ti, xy, dxydi0, dxydi1, dxydj0, dxydj1;
var xpoints = [];
var ypoints = [];
var ret = {};
// Search for the fractional grid index giving this line:
if (axisLetter === 'b') {
// For the position we use just the i-j coordinates:
j = trace.b2j(value);
// The derivatives for catmull-rom splines are discontinuous across cell
// boundaries though, so we need to provide both the cell and the position
// within the cell separately:
j0 = Math.floor(Math.max(0, Math.min(nb - 2, j)));
tj = j - j0;
ret.length = nb;
ret.crossLength = na;
ret.xy = function (i) {
return trace.evalxy([], i, j);
};
ret.dxy = function (i0, ti) {
return trace.dxydi([], i0, j0, ti, tj);
};
for (i = 0; i < na; i++) {
i0 = Math.min(na - 2, i);
ti = i - i0;
xy = trace.evalxy([], i, j);
if (crossAxis.smoothing && i > 0) {
// First control point:
dxydi0 = trace.dxydi([], i - 1, j0, 0, tj);
xpoints.push(pxy[0] + dxydi0[0] / 3);
ypoints.push(pxy[1] + dxydi0[1] / 3);
// Second control point:
dxydi1 = trace.dxydi([], i - 1, j0, 1, tj);
xpoints.push(xy[0] - dxydi1[0] / 3);
ypoints.push(xy[1] - dxydi1[1] / 3);
}
xpoints.push(xy[0]);
ypoints.push(xy[1]);
pxy = xy;
}
} else {
i = trace.a2i(value);
i0 = Math.floor(Math.max(0, Math.min(na - 2, i)));
ti = i - i0;
ret.length = na;
ret.crossLength = nb;
ret.xy = function (j) {
return trace.evalxy([], i, j);
};
ret.dxy = function (j0, tj) {
return trace.dxydj([], i0, j0, ti, tj);
};
for (j = 0; j < nb; j++) {
j0 = Math.min(nb - 2, j);
tj = j - j0;
xy = trace.evalxy([], i, j);
if (crossAxis.smoothing && j > 0) {
// First control point:
dxydj0 = trace.dxydj([], i0, j - 1, ti, 0);
xpoints.push(pxy[0] + dxydj0[0] / 3);
ypoints.push(pxy[1] + dxydj0[1] / 3);
// Second control point:
dxydj1 = trace.dxydj([], i0, j - 1, ti, 1);
xpoints.push(xy[0] - dxydj1[0] / 3);
ypoints.push(xy[1] - dxydj1[1] / 3);
}
xpoints.push(xy[0]);
ypoints.push(xy[1]);
pxy = xy;
}
}
ret.axisLetter = axisLetter;
ret.axis = axis;
ret.crossAxis = crossAxis;
ret.value = value;
ret.constvar = crossAxisLetter;
ret.index = n;
ret.x = xpoints;
ret.y = ypoints;
ret.smoothing = crossAxis.smoothing;
return ret;
}
function constructArrayGridline(idx) {
var j, i0, j0, ti, tj;
var xpoints = [];
var ypoints = [];
var ret = {};
ret.length = data.length;
ret.crossLength = crossData.length;
if (axisLetter === 'b') {
j0 = Math.max(0, Math.min(nb - 2, idx));
tj = Math.min(1, Math.max(0, idx - j0));
ret.xy = function (i) {
return trace.evalxy([], i, idx);
};
ret.dxy = function (i0, ti) {
return trace.dxydi([], i0, j0, ti, tj);
};
// In the tickmode: array case, this operation is a simple
// transfer of data:
for (j = 0; j < nea; j++) {
xpoints[j] = xcp[idx * stride][j];
ypoints[j] = ycp[idx * stride][j];
}
} else {
i0 = Math.max(0, Math.min(na - 2, idx));
ti = Math.min(1, Math.max(0, idx - i0));
ret.xy = function (j) {
return trace.evalxy([], idx, j);
};
ret.dxy = function (j0, tj) {
return trace.dxydj([], i0, j0, ti, tj);
};
// In the tickmode: array case, this operation is a simple
// transfer of data:
for (j = 0; j < neb; j++) {
xpoints[j] = xcp[j][idx * stride];
ypoints[j] = ycp[j][idx * stride];
}
}
ret.axisLetter = axisLetter;
ret.axis = axis;
ret.crossAxis = crossAxis;
ret.value = data[idx];
ret.constvar = crossAxisLetter;
ret.index = idx;
ret.x = xpoints;
ret.y = ypoints;
ret.smoothing = crossAxis.smoothing;
return ret;
}
if (axis.tickmode === 'array') {
// var j0 = axis.startline ? 1 : 0;
// var j1 = data.length - (axis.endline ? 1 : 0);
eps = 5e-15;
bounds = [Math.floor((data.length - 1 - axis.arraytick0) / axis.arraydtick * (1 + eps)), Math.ceil(-axis.arraytick0 / axis.arraydtick / (1 + eps))].sort(function (a, b) {
return a - b;
});
// Unpack sorted values so we can be sure to avoid infinite loops if something
// is backwards:
n1 = bounds[0] - 1;
n2 = bounds[1] + 1;
// If the axes fall along array lines, then this is a much simpler process since
// we already have all the control points we need
for (n = n1; n < n2; n++) {
j = axis.arraytick0 + axis.arraydtick * n;
if (j < 0 || j > data.length - 1) continue;
gridlines.push(extendFlat(constructArrayGridline(j), {
color: axis.gridcolor,
width: axis.gridwidth,
dash: axis.griddash
}));
}
for (n = n1; n < n2; n++) {
j0 = axis.arraytick0 + axis.arraydtick * n;
j1 = Math.min(j0 + axis.arraydtick, data.length - 1);
// TODO: fix the bounds computation so we don't have to do a large range and then throw
// out unneeded numbers
if (j0 < 0 || j0 > data.length - 1) continue;
if (j1 < 0 || j1 > data.length - 1) continue;
v0 = data[j0];
v1 = data[j1];
for (i = 0; i < axis.minorgridcount; i++) {
d = j1 - j0;
// TODO: fix the bounds computation so we don't have to do a large range and then throw
// out unneeded numbers
if (d <= 0) continue;
// XXX: This calculation isn't quite right. Off by one somewhere?
v = v0 + (v1 - v0) * (i + 1) / (axis.minorgridcount + 1) * (axis.arraydtick / d);
// TODO: fix the bounds computation so we don't have to do a large range and then throw
// out unneeded numbers
if (v < data[0] || v > data[data.length - 1]) continue;
minorgridlines.push(extendFlat(constructValueGridline(v), {
color: axis.minorgridcolor,
width: axis.minorgridwidth,
dash: axis.minorgriddash
}));
}
}
if (axis.startline) {
boundarylines.push(extendFlat(constructArrayGridline(0), {
color: axis.startlinecolor,
width: axis.startlinewidth
}));
}
if (axis.endline) {
boundarylines.push(extendFlat(constructArrayGridline(data.length - 1), {
color: axis.endlinecolor,
width: axis.endlinewidth
}));
}
} else {
// If the lines do not fall along the axes, then we have to interpolate
// the contro points and so some math to figure out where the lines are
// in the first place.
// Compute the integer boudns of tick0 + n * dtick that fall within the range
// (roughly speaking):
// Give this a nice generous epsilon. We use at as * (1 + eps) in order to make
// inequalities a little tolerant in a more or less correct manner:
eps = 5e-15;
bounds = [Math.floor((data[data.length - 1] - axis.tick0) / axis.dtick * (1 + eps)), Math.ceil((data[0] - axis.tick0) / axis.dtick / (1 + eps))].sort(function (a, b) {
return a - b;
});
// Unpack sorted values so we can be sure to avoid infinite loops if something
// is backwards:
n1 = bounds[0];
n2 = bounds[1];
for (n = n1; n <= n2; n++) {
value = axis.tick0 + axis.dtick * n;
gridlines.push(extendFlat(constructValueGridline(value), {
color: axis.gridcolor,
width: axis.gridwidth,
dash: axis.griddash
}));
}
for (n = n1 - 1; n < n2 + 1; n++) {
value = axis.tick0 + axis.dtick * n;
for (i = 0; i < axis.minorgridcount; i++) {
v = value + axis.dtick * (i + 1) / (axis.minorgridcount + 1);
if (v < data[0] || v > data[data.length - 1]) continue;
minorgridlines.push(extendFlat(constructValueGridline(v), {
color: axis.minorgridcolor,
width: axis.minorgridwidth,
dash: axis.minorgriddash
}));
}
}
if (axis.startline) {
boundarylines.push(extendFlat(constructValueGridline(data[0]), {
color: axis.startlinecolor,
width: axis.startlinewidth
}));
}
if (axis.endline) {
boundarylines.push(extendFlat(constructValueGridline(data[data.length - 1]), {
color: axis.endlinecolor,
width: axis.endlinewidth
}));
}
}
};
/***/ }),
/***/ 14724:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = function calcLabels(trace, axis) {
var i, tobj, prefix, suffix, gridline;
var labels = axis._labels = [];
var gridlines = axis._gridlines;
for (i = 0; i < gridlines.length; i++) {
gridline = gridlines[i];
if (['start', 'both'].indexOf(axis.showticklabels) !== -1) {
tobj = Axes.tickText(axis, gridline.value);
extendFlat(tobj, {
prefix: prefix,
suffix: suffix,
endAnchor: true,
xy: gridline.xy(0),
dxy: gridline.dxy(0, 0),
axis: gridline.axis,
length: gridline.crossAxis.length,
font: gridline.axis.tickfont,
isFirst: i === 0,
isLast: i === gridlines.length - 1
});
labels.push(tobj);
}
if (['end', 'both'].indexOf(axis.showticklabels) !== -1) {
tobj = Axes.tickText(axis, gridline.value);
extendFlat(tobj, {
endAnchor: false,
xy: gridline.xy(gridline.crossLength - 1),
dxy: gridline.dxy(gridline.crossLength - 2, 1),
axis: gridline.axis,
length: gridline.crossAxis.length,
font: gridline.axis.tickfont,
isFirst: i === 0,
isLast: i === gridlines.length - 1
});
labels.push(tobj);
}
}
};
/***/ }),
/***/ 62284:
/***/ (function(module) {
"use strict";
/*
* Compute the tangent vector according to catmull-rom cubic splines (centripetal,
* I think). That differs from the control point in two ways:
* 1. It is a vector, not a position relative to the point
* 2. the vector is longer than the position relative to p1 by a factor of 3
*
* Close to the boundaries, we'll use these as *quadratic control points, so that
* to make a nice grid, we'll need to divide the tangent by 2 instead of 3. (The
* math works out this way if you work through the bezier derivatives)
*/
var CatmullRomExp = 0.5;
module.exports = function makeControlPoints(p0, p1, p2, smoothness) {
var d1x = p0[0] - p1[0];
var d1y = p0[1] - p1[1];
var d2x = p2[0] - p1[0];
var d2y = p2[1] - p1[1];
var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
var denom1 = d2a * (d1a + d2a) * 3;
var denom2 = d1a * (d1a + d2a) * 3;
return [[p1[0] + (denom1 && numx / denom1), p1[1] + (denom1 && numy / denom1)], [p1[0] - (denom2 && numx / denom2), p1[1] - (denom2 && numy / denom2)]];
};
/***/ }),
/***/ 60776:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
/*
* Construct a 2D array of cheater values given a, b, and a slope.
* If
*/
module.exports = function (a, b, cheaterslope) {
var i, j, ascal, bscal, aval, bval;
var data = [];
var na = isArrayOrTypedArray(a) ? a.length : a;
var nb = isArrayOrTypedArray(b) ? b.length : b;
var adata = isArrayOrTypedArray(a) ? a : null;
var bdata = isArrayOrTypedArray(b) ? b : null;
// If we're using data, scale it so that for data that's just barely
// not evenly spaced, the switch to value-based indexing is continuous.
// This means evenly spaced data should look the same whether value
// or index cheatertype.
if (adata) {
ascal = (adata.length - 1) / (adata[adata.length - 1] - adata[0]) / (na - 1);
}
if (bdata) {
bscal = (bdata.length - 1) / (bdata[bdata.length - 1] - bdata[0]) / (nb - 1);
}
var xval;
var xmin = Infinity;
var xmax = -Infinity;
for (j = 0; j < nb; j++) {
data[j] = [];
bval = bdata ? (bdata[j] - bdata[0]) * bscal : j / (nb - 1);
for (i = 0; i < na; i++) {
aval = adata ? (adata[i] - adata[0]) * ascal : i / (na - 1);
xval = aval - bval * cheaterslope;
xmin = Math.min(xval, xmin);
xmax = Math.max(xval, xmax);
data[j][i] = xval;
}
}
// Normalize cheater values to the 0-1 range. This comes into play when you have
// multiple cheater plots. After careful consideration, it seems better if cheater
// values are normalized to a consistent range. Otherwise one cheater affects the
// layout of other cheaters on the same axis.
var slope = 1.0 / (xmax - xmin);
var offset = -xmin * slope;
for (j = 0; j < nb; j++) {
for (i = 0; i < na; i++) {
data[j][i] = slope * data[j][i] + offset;
}
}
return data;
};
/***/ }),
/***/ 30180:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var makeControlPoints = __webpack_require__(62284);
var ensureArray = (__webpack_require__(3400).ensureArray);
/*
* Turns a coarse grid into a fine grid with control points.
*
* Here's an ASCII representation:
*
* o ----- o ----- o ----- o
* | | | |
* | | | |
* | | | |
* o ----- o ----- o ----- o
* | | | |
* | | | |
* ^ | | | |
* | o ----- o ----- o ----- o
* b | | | | |
* | | | | |
* | | | | |
* o ----- o ----- o ----- o
* ------>
* a
*
* First of all, note that we want to do this in *cartesian* space. This means
* we might run into problems when there are extreme differences in x/y scaling,
* but the alternative is that the topology of the contours might actually be
* view-dependent, which seems worse. As a fallback, the only parameter that
* actually affects the result is the *aspect ratio*, so that we can at least
* improve the situation a bit without going all the way to screen coordinates.
*
* This function flattens the points + tangents into a slightly denser grid of
* *control points*. The resulting grid looks like this:
*
* 9 +--o-o--+ -o-o--+--o-o--+
* 8 o o o o o o o o o o
* | | | |
* 7 o o o o o o o o o o
* 6 +--o-o--+ -o-o--+--o-o--+
* 5 o o o o o o o o o o
* | | | |
* ^ 4 o o o o o o o o o o
* | 3 +--o-o--+ -o-o--+--o-o--+
* b | 2 o o o o o o o o o o
* | | | | |
* | 1 o o o o o o o o o o
* 0 +--o-o--+ -o-o--+--o-o--+
* 0 1 2 3 4 5 6 7 8 9
* ------>
* a
*
* where `o`s represent newly-computed control points. the resulting dimension is
*
* (m - 1) * 3 + 1
* = 3 * m - 2
*
* We could simply store the tangents separately, but that's a nightmare to organize
* in two dimensions since we'll be slicing grid lines in both directions and since
* that basically requires very nearly just as much storage as just storing the dense
* grid.
*
* Wow!
*/
/*
* Catmull-rom is biased at the boundaries toward the interior and we actually
* can't use catmull-rom to compute the control point closest to (but inside)
* the boundary.
*
* A note on plotly's spline interpolation. It uses the catmull rom control point
* closest to the boundary *as* a quadratic control point. This seems incorrect,
* so I've elected not to follow that. Given control points 0 and 1, regular plotly
* splines give *equivalent* cubic control points:
*
* Input:
*
* boundary
* | |
* p0 p2 p3 --> interior
* 0.0 0.667 1.0
* | |
*
* Cubic-equivalent of what plotly splines draw::
*
* boundary
* | |
* p0 p1 p2 p3 --> interior
* 0.0 0.4444 0.8888 1.0
* | |
*
* What this function fills in:
*
* boundary
* | |
* p0 p1 p2 p3 --> interior
* 0.0 0.333 0.667 1.0
* | |
*
* Parameters:
* p0: boundary point
* p2: catmull rom point based on computation at p3
* p3: first grid point
*
* Of course it works whichever way it's oriented; you just need to interpret the
* input/output accordingly.
*/
function inferCubicControlPoint(p0, p2, p3) {
// Extend p1 away from p0 by 50%. This is the equivalent quadratic point that
// would give the same slope as catmull rom at p0.
var p2e0 = -0.5 * p3[0] + 1.5 * p2[0];
var p2e1 = -0.5 * p3[1] + 1.5 * p2[1];
return [(2 * p2e0 + p0[0]) / 3, (2 * p2e1 + p0[1]) / 3];
}
module.exports = function computeControlPoints(xe, ye, x, y, asmoothing, bsmoothing) {
var i, j, ie, je, xej, yej, xj, yj, cp, p1;
// At this point, we know these dimensions are correct and representative of
// the whole 2D arrays:
var na = x[0].length;
var nb = x.length;
// (n)umber of (e)xpanded points:
var nea = asmoothing ? 3 * na - 2 : na;
var neb = bsmoothing ? 3 * nb - 2 : nb;
xe = ensureArray(xe, neb);
ye = ensureArray(ye, neb);
for (ie = 0; ie < neb; ie++) {
xe[ie] = ensureArray(xe[ie], nea);
ye[ie] = ensureArray(ye[ie], nea);
}
// This loop fills in the X'd points:
//
// . . . .
// . . . .
// | | | |
// | | | |
// X ----- X ----- X ----- X
// | | | |
// | | | |
// | | | |
// X ----- X ----- X ----- X
//
//
// ie = (i) (e)xpanded:
for (j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) {
xej = xe[je];
yej = ye[je];
xj = x[j];
yj = y[j];
// je = (j) (e)xpanded:
for (i = 0, ie = 0; i < na; i++, ie += asmoothing ? 3 : 1) {
xej[ie] = xj[i];
yej[ie] = yj[i];
}
}
if (asmoothing) {
// If there's a-smoothing, this loop fills in the X'd points with catmull-rom
// control points computed along the a-axis:
// . . . .
// . . . .
// | | | |
// | | | |
// o -Y-X- o -X-X- o -X-Y- o
// | | | |
// | | | |
// | | | |
// o -Y-X- o -X-X- o -X-Y- o
//
// i: 0 1 2 3
// ie: 0 1 3 3 4 5 6 7 8 9
//
// ------>
// a
//
for (j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) {
// Fill in the points marked X for this a-row:
for (i = 1, ie = 3; i < na - 1; i++, ie += 3) {
cp = makeControlPoints([x[j][i - 1], y[j][i - 1]], [x[j][i], y[j][i]], [x[j][i + 1], y[j][i + 1]], asmoothing);
xe[je][ie - 1] = cp[0][0];
ye[je][ie - 1] = cp[0][1];
xe[je][ie + 1] = cp[1][0];
ye[je][ie + 1] = cp[1][1];
}
// The very first cubic interpolation point (to the left for i = 1 above) is
// used as a *quadratic* interpolation point by the spline drawing function
// which isn't really correct. But for the sake of consistency, we'll use it
// as such. Since we're using cubic splines, that means we need to shorten the
// tangent by 1/3 and also construct a new cubic spline control point 1/3 from
// the original to the i = 0 point.
p1 = inferCubicControlPoint([xe[je][0], ye[je][0]], [xe[je][2], ye[je][2]], [xe[je][3], ye[je][3]]);
xe[je][1] = p1[0];
ye[je][1] = p1[1];
// Ditto last points, sans explanation:
p1 = inferCubicControlPoint([xe[je][nea - 1], ye[je][nea - 1]], [xe[je][nea - 3], ye[je][nea - 3]], [xe[je][nea - 4], ye[je][nea - 4]]);
xe[je][nea - 2] = p1[0];
ye[je][nea - 2] = p1[1];
}
}
if (bsmoothing) {
// If there's a-smoothing, this loop fills in the X'd points with catmull-rom
// control points computed along the b-axis:
// . . . .
// X X X X X X X X X X
// | | | |
// X X X X X X X X X X
// o -o-o- o -o-o- o -o-o- o
// X X X X X X X X X X
// | | | |
// Y Y Y Y Y Y Y Y Y Y
// o -o-o- o -o-o- o -o-o- o
//
// i: 0 1 2 3
// ie: 0 1 3 3 4 5 6 7 8 9
//
// ------>
// a
//
for (ie = 0; ie < nea; ie++) {
for (je = 3; je < neb - 3; je += 3) {
cp = makeControlPoints([xe[je - 3][ie], ye[je - 3][ie]], [xe[je][ie], ye[je][ie]], [xe[je + 3][ie], ye[je + 3][ie]], bsmoothing);
xe[je - 1][ie] = cp[0][0];
ye[je - 1][ie] = cp[0][1];
xe[je + 1][ie] = cp[1][0];
ye[je + 1][ie] = cp[1][1];
}
// Do the same boundary condition magic for these control points marked Y above:
p1 = inferCubicControlPoint([xe[0][ie], ye[0][ie]], [xe[2][ie], ye[2][ie]], [xe[3][ie], ye[3][ie]]);
xe[1][ie] = p1[0];
ye[1][ie] = p1[1];
p1 = inferCubicControlPoint([xe[neb - 1][ie], ye[neb - 1][ie]], [xe[neb - 3][ie], ye[neb - 3][ie]], [xe[neb - 4][ie], ye[neb - 4][ie]]);
xe[neb - 2][ie] = p1[0];
ye[neb - 2][ie] = p1[1];
}
}
if (asmoothing && bsmoothing) {
// Do one more pass, this time recomputing exactly what we just computed.
// It's overdetermined since we're peforming catmull-rom in two directions,
// so we'll just average the overdetermined. These points don't lie along the
// grid lines, so note that only grid lines will follow normal plotly spline
// interpolation.
//
// Unless of course there was no b smoothing. Then these intermediate points
// don't actually exist and this section is bypassed.
// . . . .
// o X X o X X o X X o
// | | | |
// o X X o X X o X X o
// o -o-o- o -o-o- o -o-o- o
// o X X o X X o X X o
// | | | |
// o Y Y o Y Y o Y Y o
// o -o-o- o -o-o- o -o-o- o
//
// i: 0 1 2 3
// ie: 0 1 3 3 4 5 6 7 8 9
//
// ------>
// a
//
for (je = 1; je < neb; je += (je + 1) % 3 === 0 ? 2 : 1) {
// Fill in the points marked X for this a-row:
for (ie = 3; ie < nea - 3; ie += 3) {
cp = makeControlPoints([xe[je][ie - 3], ye[je][ie - 3]], [xe[je][ie], ye[je][ie]], [xe[je][ie + 3], ye[je][ie + 3]], asmoothing);
xe[je][ie - 1] = 0.5 * (xe[je][ie - 1] + cp[0][0]);
ye[je][ie - 1] = 0.5 * (ye[je][ie - 1] + cp[0][1]);
xe[je][ie + 1] = 0.5 * (xe[je][ie + 1] + cp[1][0]);
ye[je][ie + 1] = 0.5 * (ye[je][ie + 1] + cp[1][1]);
}
// This case is just slightly different. The computation is the same,
// but having computed this, we'll average with the existing result.
p1 = inferCubicControlPoint([xe[je][0], ye[je][0]], [xe[je][2], ye[je][2]], [xe[je][3], ye[je][3]]);
xe[je][1] = 0.5 * (xe[je][1] + p1[0]);
ye[je][1] = 0.5 * (ye[je][1] + p1[1]);
p1 = inferCubicControlPoint([xe[je][nea - 1], ye[je][nea - 1]], [xe[je][nea - 3], ye[je][nea - 3]], [xe[je][nea - 4], ye[je][nea - 4]]);
xe[je][nea - 2] = 0.5 * (xe[je][nea - 2] + p1[0]);
ye[je][nea - 2] = 0.5 * (ye[je][nea - 2] + p1[1]);
}
}
return [xe, ye];
};
/***/ }),
/***/ 24588:
/***/ (function(module) {
"use strict";
module.exports = {
RELATIVE_CULL_TOLERANCE: 1e-6
};
/***/ }),
/***/ 26435:
/***/ (function(module) {
"use strict";
/*
* Evaluates the derivative of a list of control point arrays. That is, it expects an array or arrays
* that are expanded relative to the raw data to include the bicubic control points, if applicable. If
* only linear interpolation is desired, then the data points correspond 1-1 along that axis to the
* data itself. Since it's catmull-rom splines in either direction note in particular that the
* derivatives are discontinuous across cell boundaries. That's the reason you need both the *cell*
* and the *point within the cell*.
*
* Also note that the discontinuity of the derivative is in magnitude only. The direction *is*
* continuous across cell boundaries.
*
* For example, to compute the derivative of the xcoordinate halfway between the 7 and 8th i-gridpoints
* and the 10th and 11th j-gridpoints given bicubic smoothing in both dimensions, you'd write:
*
* var deriv = createIDerivativeEvaluator([x], 1, 1);
*
* var dxdi = deriv([], 7, 10, 0.5, 0.5);
* // => [0.12345]
*
* Since there'd be a bunch of duplicate computation to compute multiple derivatives, you can double
* this up by providing more arrays:
*
* var deriv = createIDerivativeEvaluator([x, y], 1, 1);
*
* var dxdi = deriv([], 7, 10, 0.5, 0.5);
* // => [0.12345, 0.78910]
*
* NB: It's presumed that at this point all data has been sanitized and is valid numerical data arrays
* of the correct dimension.
*/
module.exports = function (arrays, asmoothing, bsmoothing) {
if (asmoothing && bsmoothing) {
return function (out, i0, j0, u, v) {
if (!out) out = [];
var f0, f1, f2, f3, ak, k;
// Since it's a grid of control points, the actual indices are * 3:
i0 *= 3;
j0 *= 3;
// Precompute some numbers:
var u2 = u * u;
var ou = 1 - u;
var ou2 = ou * ou;
var ouu2 = ou * u * 2;
var a = -3 * ou2;
var b = 3 * (ou2 - ouu2);
var c = 3 * (ouu2 - u2);
var d = 3 * u2;
var v2 = v * v;
var v3 = v2 * v;
var ov = 1 - v;
var ov2 = ov * ov;
var ov3 = ov2 * ov;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
// Compute the derivatives in the u-direction:
f0 = a * ak[j0][i0] + b * ak[j0][i0 + 1] + c * ak[j0][i0 + 2] + d * ak[j0][i0 + 3];
f1 = a * ak[j0 + 1][i0] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 1][i0 + 2] + d * ak[j0 + 1][i0 + 3];
f2 = a * ak[j0 + 2][i0] + b * ak[j0 + 2][i0 + 1] + c * ak[j0 + 2][i0 + 2] + d * ak[j0 + 2][i0 + 3];
f3 = a * ak[j0 + 3][i0] + b * ak[j0 + 3][i0 + 1] + c * ak[j0 + 3][i0 + 2] + d * ak[j0 + 3][i0 + 3];
// Now just interpolate in the v-direction since it's all separable:
out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
}
return out;
};
} else if (asmoothing) {
// Handle smooth in the a-direction but linear in the b-direction by performing four
// linear interpolations followed by one cubic interpolation of the result
return function (out, i0, j0, u, v) {
if (!out) out = [];
var f0, f1, k, ak;
i0 *= 3;
var u2 = u * u;
var ou = 1 - u;
var ou2 = ou * ou;
var ouu2 = ou * u * 2;
var a = -3 * ou2;
var b = 3 * (ou2 - ouu2);
var c = 3 * (ouu2 - u2);
var d = 3 * u2;
var ov = 1 - v;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = a * ak[j0][i0] + b * ak[j0][i0 + 1] + c * ak[j0][i0 + 2] + d * ak[j0][i0 + 3];
f1 = a * ak[j0 + 1][i0] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 1][i0 + 2] + d * ak[j0 + 1][i0 + 3];
out[k] = ov * f0 + v * f1;
}
return out;
};
} else if (bsmoothing) {
// Same as the above case, except reversed. I've disabled the no-unused vars rule
// so that this function is fully interpolation-agnostic. Otherwise it would need
// to be called differently in different cases. Which wouldn't be the worst, but
/* eslint-disable no-unused-vars */
return function (out, i0, j0, u, v) {
/* eslint-enable no-unused-vars */
if (!out) out = [];
var f0, f1, f2, f3, k, ak;
j0 *= 3;
var v2 = v * v;
var v3 = v2 * v;
var ov = 1 - v;
var ov2 = ov * ov;
var ov3 = ov2 * ov;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = ak[j0][i0 + 1] - ak[j0][i0];
f1 = ak[j0 + 1][i0 + 1] - ak[j0 + 1][i0];
f2 = ak[j0 + 2][i0 + 1] - ak[j0 + 2][i0];
f3 = ak[j0 + 3][i0 + 1] - ak[j0 + 3][i0];
out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
}
return out;
};
} else {
// Finally, both directions are linear:
/* eslint-disable no-unused-vars */
return function (out, i0, j0, u, v) {
/* eslint-enable no-unused-vars */
if (!out) out = [];
var f0, f1, k, ak;
var ov = 1 - v;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = ak[j0][i0 + 1] - ak[j0][i0];
f1 = ak[j0 + 1][i0 + 1] - ak[j0 + 1][i0];
out[k] = ov * f0 + v * f1;
}
return out;
};
}
};
/***/ }),
/***/ 24464:
/***/ (function(module) {
"use strict";
module.exports = function (arrays, asmoothing, bsmoothing) {
if (asmoothing && bsmoothing) {
return function (out, i0, j0, u, v) {
if (!out) out = [];
var f0, f1, f2, f3, ak, k;
// Since it's a grid of control points, the actual indices are * 3:
i0 *= 3;
j0 *= 3;
// Precompute some numbers:
var u2 = u * u;
var u3 = u2 * u;
var ou = 1 - u;
var ou2 = ou * ou;
var ou3 = ou2 * ou;
var v2 = v * v;
var ov = 1 - v;
var ov2 = ov * ov;
var ovv2 = ov * v * 2;
var a = -3 * ov2;
var b = 3 * (ov2 - ovv2);
var c = 3 * (ovv2 - v2);
var d = 3 * v2;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
// Compute the derivatives in the v-direction:
f0 = a * ak[j0][i0] + b * ak[j0 + 1][i0] + c * ak[j0 + 2][i0] + d * ak[j0 + 3][i0];
f1 = a * ak[j0][i0 + 1] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 2][i0 + 1] + d * ak[j0 + 3][i0 + 1];
f2 = a * ak[j0][i0 + 2] + b * ak[j0 + 1][i0 + 2] + c * ak[j0 + 2][i0 + 2] + d * ak[j0 + 3][i0 + 2];
f3 = a * ak[j0][i0 + 3] + b * ak[j0 + 1][i0 + 3] + c * ak[j0 + 2][i0 + 3] + d * ak[j0 + 3][i0 + 3];
// Now just interpolate in the v-direction since it's all separable:
out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
}
return out;
};
} else if (asmoothing) {
// Handle smooth in the a-direction but linear in the b-direction by performing four
// linear interpolations followed by one cubic interpolation of the result
return function (out, i0, j0, v, u) {
if (!out) out = [];
var f0, f1, f2, f3, k, ak;
i0 *= 3;
var u2 = u * u;
var u3 = u2 * u;
var ou = 1 - u;
var ou2 = ou * ou;
var ou3 = ou2 * ou;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = ak[j0 + 1][i0] - ak[j0][i0];
f1 = ak[j0 + 1][i0 + 1] - ak[j0][i0 + 1];
f2 = ak[j0 + 1][i0 + 2] - ak[j0][i0 + 2];
f3 = ak[j0 + 1][i0 + 3] - ak[j0][i0 + 3];
out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
// mathematically equivalent:
// f0 = ou3 * ak[j0 ][i0] + 3 * (ou2 * u * ak[j0 ][i0 + 1] + ou * u2 * ak[j0 ][i0 + 2]) + u3 * ak[j0 ][i0 + 3];
// f1 = ou3 * ak[j0 + 1][i0] + 3 * (ou2 * u * ak[j0 + 1][i0 + 1] + ou * u2 * ak[j0 + 1][i0 + 2]) + u3 * ak[j0 + 1][i0 + 3];
// out[k] = f1 - f0;
}
return out;
};
} else if (bsmoothing) {
// Same as the above case, except reversed:
/* eslint-disable no-unused-vars */
return function (out, i0, j0, u, v) {
/* eslint-enable no-unused-vars */
if (!out) out = [];
var f0, f1, k, ak;
j0 *= 3;
var ou = 1 - u;
var v2 = v * v;
var ov = 1 - v;
var ov2 = ov * ov;
var ovv2 = ov * v * 2;
var a = -3 * ov2;
var b = 3 * (ov2 - ovv2);
var c = 3 * (ovv2 - v2);
var d = 3 * v2;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = a * ak[j0][i0] + b * ak[j0 + 1][i0] + c * ak[j0 + 2][i0] + d * ak[j0 + 3][i0];
f1 = a * ak[j0][i0 + 1] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 2][i0 + 1] + d * ak[j0 + 3][i0 + 1];
out[k] = ou * f0 + u * f1;
}
return out;
};
} else {
// Finally, both directions are linear:
/* eslint-disable no-unused-vars */
return function (out, i0, j0, v, u) {
/* eslint-enable no-unused-vars */
if (!out) out = [];
var f0, f1, k, ak;
var ov = 1 - v;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = ak[j0 + 1][i0] - ak[j0][i0];
f1 = ak[j0 + 1][i0 + 1] - ak[j0][i0 + 1];
out[k] = ov * f0 + v * f1;
}
return out;
};
}
};
/***/ }),
/***/ 29056:
/***/ (function(module) {
"use strict";
/*
* Return a function that evaluates a set of linear or bicubic control points.
* This will get evaluated a lot, so we'll at least do a bit of extra work to
* flatten some of the choices. In particular, we'll unroll the linear/bicubic
* combinations and we'll allow computing results in parallel to cut down
* on repeated arithmetic.
*
* Take note that we don't search for the correct range in this function. The
* reason is for consistency due to the corrresponding derivative function. In
* particular, the derivatives aren't continuous across cells, so it's important
* to be able control whether the derivative at a cell boundary is approached
* from one side or the other.
*/
module.exports = function (arrays, na, nb, asmoothing, bsmoothing) {
var imax = na - 2;
var jmax = nb - 2;
if (asmoothing && bsmoothing) {
return function (out, i, j) {
if (!out) out = [];
var f0, f1, f2, f3, ak, k;
var i0 = Math.max(0, Math.min(Math.floor(i), imax));
var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
var u = Math.max(0, Math.min(1, i - i0));
var v = Math.max(0, Math.min(1, j - j0));
// Since it's a grid of control points, the actual indices are * 3:
i0 *= 3;
j0 *= 3;
// Precompute some numbers:
var u2 = u * u;
var u3 = u2 * u;
var ou = 1 - u;
var ou2 = ou * ou;
var ou3 = ou2 * ou;
var v2 = v * v;
var v3 = v2 * v;
var ov = 1 - v;
var ov2 = ov * ov;
var ov3 = ov2 * ov;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = ou3 * ak[j0][i0] + 3 * (ou2 * u * ak[j0][i0 + 1] + ou * u2 * ak[j0][i0 + 2]) + u3 * ak[j0][i0 + 3];
f1 = ou3 * ak[j0 + 1][i0] + 3 * (ou2 * u * ak[j0 + 1][i0 + 1] + ou * u2 * ak[j0 + 1][i0 + 2]) + u3 * ak[j0 + 1][i0 + 3];
f2 = ou3 * ak[j0 + 2][i0] + 3 * (ou2 * u * ak[j0 + 2][i0 + 1] + ou * u2 * ak[j0 + 2][i0 + 2]) + u3 * ak[j0 + 2][i0 + 3];
f3 = ou3 * ak[j0 + 3][i0] + 3 * (ou2 * u * ak[j0 + 3][i0 + 1] + ou * u2 * ak[j0 + 3][i0 + 2]) + u3 * ak[j0 + 3][i0 + 3];
out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
}
return out;
};
} else if (asmoothing) {
// Handle smooth in the a-direction but linear in the b-direction by performing four
// linear interpolations followed by one cubic interpolation of the result
return function (out, i, j) {
if (!out) out = [];
var i0 = Math.max(0, Math.min(Math.floor(i), imax));
var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
var u = Math.max(0, Math.min(1, i - i0));
var v = Math.max(0, Math.min(1, j - j0));
var f0, f1, f2, f3, k, ak;
i0 *= 3;
var u2 = u * u;
var u3 = u2 * u;
var ou = 1 - u;
var ou2 = ou * ou;
var ou3 = ou2 * ou;
var ov = 1 - v;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = ov * ak[j0][i0] + v * ak[j0 + 1][i0];
f1 = ov * ak[j0][i0 + 1] + v * ak[j0 + 1][i0 + 1];
f2 = ov * ak[j0][i0 + 2] + v * ak[j0 + 1][i0 + 1];
f3 = ov * ak[j0][i0 + 3] + v * ak[j0 + 1][i0 + 1];
out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
}
return out;
};
} else if (bsmoothing) {
// Same as the above case, except reversed:
return function (out, i, j) {
if (!out) out = [];
var i0 = Math.max(0, Math.min(Math.floor(i), imax));
var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
var u = Math.max(0, Math.min(1, i - i0));
var v = Math.max(0, Math.min(1, j - j0));
var f0, f1, f2, f3, k, ak;
j0 *= 3;
var v2 = v * v;
var v3 = v2 * v;
var ov = 1 - v;
var ov2 = ov * ov;
var ov3 = ov2 * ov;
var ou = 1 - u;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = ou * ak[j0][i0] + u * ak[j0][i0 + 1];
f1 = ou * ak[j0 + 1][i0] + u * ak[j0 + 1][i0 + 1];
f2 = ou * ak[j0 + 2][i0] + u * ak[j0 + 2][i0 + 1];
f3 = ou * ak[j0 + 3][i0] + u * ak[j0 + 3][i0 + 1];
out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
}
return out;
};
} else {
// Finally, both directions are linear:
return function (out, i, j) {
if (!out) out = [];
var i0 = Math.max(0, Math.min(Math.floor(i), imax));
var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
var u = Math.max(0, Math.min(1, i - i0));
var v = Math.max(0, Math.min(1, j - j0));
var f0, f1, k, ak;
var ov = 1 - v;
var ou = 1 - u;
for (k = 0; k < arrays.length; k++) {
ak = arrays[k];
f0 = ou * ak[j0][i0] + u * ak[j0][i0 + 1];
f1 = ou * ak[j0 + 1][i0] + u * ak[j0 + 1][i0 + 1];
out[k] = ov * f0 + v * f1;
}
return out;
};
}
};
/***/ }),
/***/ 38356:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleXYDefaults = __webpack_require__(86411);
var handleABDefaults = __webpack_require__(93504);
var attributes = __webpack_require__(85720);
var colorAttrs = __webpack_require__(22548);
module.exports = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
traceOut._clipPathId = 'clip' + traceOut.uid + 'carpet';
var defaultColor = coerce('color', colorAttrs.defaultLine);
Lib.coerceFont(coerce, 'font', fullLayout.font);
coerce('carpet');
handleABDefaults(traceIn, traceOut, fullLayout, coerce, defaultColor);
if (!traceOut.a || !traceOut.b) {
traceOut.visible = false;
return;
}
if (traceOut.a.length < 3) {
traceOut.aaxis.smoothing = 0;
}
if (traceOut.b.length < 3) {
traceOut.baxis.smoothing = 0;
}
// NB: the input is x/y arrays. You should know that the *first* dimension of x and y
// corresponds to b and the second to a. This sounds backwards but ends up making sense
// the important part to know is that when you write y[j][i], j goes from 0 to b.length - 1
// and i goes from 0 to a.length - 1.
var validData = handleXYDefaults(traceIn, traceOut, coerce);
if (!validData) {
traceOut.visible = false;
}
if (traceOut._cheater) {
coerce('cheaterslope');
}
coerce('zorder');
};
/***/ }),
/***/ 95856:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(85720),
supplyDefaults: __webpack_require__(38356),
plot: __webpack_require__(164),
calc: __webpack_require__(58744),
animatable: true,
isContainer: true,
// so carpet traces get `calc` before other traces
moduleType: 'trace',
name: 'carpet',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', 'carpet', 'carpetAxis', 'notLegendIsolatable', 'noMultiCategory', 'noHover', 'noSortingByValue'],
meta: {}
};
/***/ }),
/***/ 50948:
/***/ (function(module) {
"use strict";
/*
* Given a trace, look up the carpet axis by carpet.
*/
module.exports = function (gd, trace) {
var n = gd._fullData.length;
var firstAxis;
for (var i = 0; i < n; i++) {
var maybeCarpet = gd._fullData[i];
if (maybeCarpet.index === trace.index) continue;
if (maybeCarpet.type === 'carpet') {
if (!firstAxis) {
firstAxis = maybeCarpet;
}
if (maybeCarpet.carpet === trace.carpet) {
return maybeCarpet;
}
}
}
return firstAxis;
};
/***/ }),
/***/ 53416:
/***/ (function(module) {
"use strict";
module.exports = function makePath(xp, yp, isBicubic) {
// Prevent d3 errors that would result otherwise:
if (xp.length === 0) return '';
var i;
var path = [];
var stride = isBicubic ? 3 : 1;
for (i = 0; i < xp.length; i += stride) {
path.push(xp[i] + ',' + yp[i]);
if (isBicubic && i < xp.length - stride) {
path.push('C');
path.push([xp[i + 1] + ',' + yp[i + 1], xp[i + 2] + ',' + yp[i + 2] + ' '].join(' '));
}
}
return path.join(isBicubic ? '' : 'L');
};
/***/ }),
/***/ 87072:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
/*
* Map an array of x or y coordinates (c) to screen-space pixel coordinates (p).
* The output array is optional, but if provided, it will be reused without
* reallocation to the extent possible.
*/
module.exports = function mapArray(out, data, func) {
var i;
if (!isArrayOrTypedArray(out)) {
// If not an array, make it an array:
out = [];
} else if (out.length > data.length) {
// If too long, truncate. (If too short, it will grow
// automatically so we don't care about that case)
out = out.slice(0, data.length);
}
for (i = 0; i < data.length; i++) {
out[i] = func(data[i]);
}
return out;
};
/***/ }),
/***/ 15584:
/***/ (function(module) {
"use strict";
module.exports = function orientText(trace, xaxis, yaxis, xy, dxy, refDxy) {
var dx = dxy[0] * trace.dpdx(xaxis);
var dy = dxy[1] * trace.dpdy(yaxis);
var flip = 1;
var offsetMultiplier = 1.0;
if (refDxy) {
var l1 = Math.sqrt(dxy[0] * dxy[0] + dxy[1] * dxy[1]);
var l2 = Math.sqrt(refDxy[0] * refDxy[0] + refDxy[1] * refDxy[1]);
var dot = (dxy[0] * refDxy[0] + dxy[1] * refDxy[1]) / l1 / l2;
offsetMultiplier = Math.max(0.0, dot);
}
var angle = Math.atan2(dy, dx) * 180 / Math.PI;
if (angle < -90) {
angle += 180;
flip = -flip;
} else if (angle > 90) {
angle -= 180;
flip = -flip;
}
return {
angle: angle,
flip: flip,
p: trace.c2p(xy, xaxis, yaxis),
offsetMultplier: offsetMultiplier
};
};
/***/ }),
/***/ 164:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var map1dArray = __webpack_require__(87072);
var makepath = __webpack_require__(53416);
var orientText = __webpack_require__(15584);
var svgTextUtils = __webpack_require__(72736);
var Lib = __webpack_require__(3400);
var strRotate = Lib.strRotate;
var strTranslate = Lib.strTranslate;
var alignmentConstants = __webpack_require__(84284);
module.exports = function plot(gd, plotinfo, cdcarpet, carpetLayer) {
var isStatic = gd._context.staticPlot;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var fullLayout = gd._fullLayout;
var clipLayer = fullLayout._clips;
Lib.makeTraceGroups(carpetLayer, cdcarpet, 'trace').each(function (cd) {
var axisLayer = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
var aax = trace.aaxis;
var bax = trace.baxis;
var minorLayer = Lib.ensureSingle(axisLayer, 'g', 'minorlayer');
var majorLayer = Lib.ensureSingle(axisLayer, 'g', 'majorlayer');
var boundaryLayer = Lib.ensureSingle(axisLayer, 'g', 'boundarylayer');
var labelLayer = Lib.ensureSingle(axisLayer, 'g', 'labellayer');
axisLayer.style('opacity', trace.opacity);
drawGridLines(xa, ya, majorLayer, aax, 'a', aax._gridlines, true, isStatic);
drawGridLines(xa, ya, majorLayer, bax, 'b', bax._gridlines, true, isStatic);
drawGridLines(xa, ya, minorLayer, aax, 'a', aax._minorgridlines, true, isStatic);
drawGridLines(xa, ya, minorLayer, bax, 'b', bax._minorgridlines, true, isStatic);
// NB: These are not omitted if the lines are not active. The joins must be executed
// in order for them to get cleaned up without a full redraw
drawGridLines(xa, ya, boundaryLayer, aax, 'a-boundary', aax._boundarylines, isStatic);
drawGridLines(xa, ya, boundaryLayer, bax, 'b-boundary', bax._boundarylines, isStatic);
var labelOrientationA = drawAxisLabels(gd, xa, ya, trace, cd0, labelLayer, aax._labels, 'a-label');
var labelOrientationB = drawAxisLabels(gd, xa, ya, trace, cd0, labelLayer, bax._labels, 'b-label');
drawAxisTitles(gd, labelLayer, trace, cd0, xa, ya, labelOrientationA, labelOrientationB);
drawClipPath(trace, cd0, clipLayer, xa, ya);
});
};
function drawClipPath(trace, t, layer, xaxis, yaxis) {
var seg, xp, yp, i;
var clip = layer.select('#' + trace._clipPathId);
if (!clip.size()) {
clip = layer.append('clipPath').classed('carpetclip', true);
}
var path = Lib.ensureSingle(clip, 'path', 'carpetboundary');
var segments = t.clipsegments;
var segs = [];
for (i = 0; i < segments.length; i++) {
seg = segments[i];
xp = map1dArray([], seg.x, xaxis.c2p);
yp = map1dArray([], seg.y, yaxis.c2p);
segs.push(makepath(xp, yp, seg.bicubic));
}
// This could be optimized ever so slightly to avoid no-op L segments
// at the corners, but it's so negligible that I don't think it's worth
// the extra complexity
var clipPathData = 'M' + segs.join('L') + 'Z';
clip.attr('id', trace._clipPathId);
path.attr('d', clipPathData);
}
function drawGridLines(xaxis, yaxis, layer, axis, axisLetter, gridlines, isStatic) {
var lineClass = 'const-' + axisLetter + '-lines';
var gridJoin = layer.selectAll('.' + lineClass).data(gridlines);
gridJoin.enter().append('path').classed(lineClass, true).style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke');
gridJoin.each(function (d) {
var gridline = d;
var x = gridline.x;
var y = gridline.y;
var xp = map1dArray([], x, xaxis.c2p);
var yp = map1dArray([], y, yaxis.c2p);
var path = 'M' + makepath(xp, yp, gridline.smoothing);
var el = d3.select(this);
el.attr('d', path).style('stroke-width', gridline.width).style('stroke', gridline.color).style('stroke-dasharray', Drawing.dashStyle(gridline.dash, gridline.width)).style('fill', 'none');
});
gridJoin.exit().remove();
}
function drawAxisLabels(gd, xaxis, yaxis, trace, t, layer, labels, labelClass) {
var labelJoin = layer.selectAll('text.' + labelClass).data(labels);
labelJoin.enter().append('text').classed(labelClass, true);
var maxExtent = 0;
var labelOrientation = {};
labelJoin.each(function (label, i) {
// Most of the positioning is done in calc_labels. Only the parts that depend upon
// the screen space representation of the x and y axes are here:
var orientation;
if (label.axis.tickangle === 'auto') {
orientation = orientText(trace, xaxis, yaxis, label.xy, label.dxy);
} else {
var angle = (label.axis.tickangle + 180.0) * Math.PI / 180.0;
orientation = orientText(trace, xaxis, yaxis, label.xy, [Math.cos(angle), Math.sin(angle)]);
}
if (!i) {
// TODO: offsetMultiplier? Not currently used anywhere...
labelOrientation = {
angle: orientation.angle,
flip: orientation.flip
};
}
var direction = (label.endAnchor ? -1 : 1) * orientation.flip;
var labelEl = d3.select(this).attr({
'text-anchor': direction > 0 ? 'start' : 'end',
'data-notex': 1
}).call(Drawing.font, label.font).text(label.text).call(svgTextUtils.convertToTspans, gd);
var bbox = Drawing.bBox(this);
labelEl.attr('transform',
// Translate to the correct point:
strTranslate(orientation.p[0], orientation.p[1]) +
// Rotate to line up with grid line tangent:
strRotate(orientation.angle) +
// Adjust the baseline and indentation:
strTranslate(label.axis.labelpadding * direction, bbox.height * 0.3));
maxExtent = Math.max(maxExtent, bbox.width + label.axis.labelpadding);
});
labelJoin.exit().remove();
labelOrientation.maxExtent = maxExtent;
return labelOrientation;
}
function drawAxisTitles(gd, layer, trace, t, xa, ya, labelOrientationA, labelOrientationB) {
var a, b, xy, dxy;
var aMin = Lib.aggNums(Math.min, null, trace.a);
var aMax = Lib.aggNums(Math.max, null, trace.a);
var bMin = Lib.aggNums(Math.min, null, trace.b);
var bMax = Lib.aggNums(Math.max, null, trace.b);
a = 0.5 * (aMin + aMax);
b = bMin;
xy = trace.ab2xy(a, b, true);
dxy = trace.dxyda_rough(a, b);
if (labelOrientationA.angle === undefined) {
Lib.extendFlat(labelOrientationA, orientText(trace, xa, ya, xy, trace.dxydb_rough(a, b)));
}
drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.aaxis, xa, ya, labelOrientationA, 'a-title');
a = aMin;
b = 0.5 * (bMin + bMax);
xy = trace.ab2xy(a, b, true);
dxy = trace.dxydb_rough(a, b);
if (labelOrientationB.angle === undefined) {
Lib.extendFlat(labelOrientationB, orientText(trace, xa, ya, xy, trace.dxyda_rough(a, b)));
}
drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.baxis, xa, ya, labelOrientationB, 'b-title');
}
var lineSpacing = alignmentConstants.LINE_SPACING;
var midShift = (1 - alignmentConstants.MID_SHIFT) / lineSpacing + 1;
function drawAxisTitle(gd, layer, trace, t, xy, dxy, axis, xa, ya, labelOrientation, labelClass) {
var data = [];
if (axis.title.text) data.push(axis.title.text);
var titleJoin = layer.selectAll('text.' + labelClass).data(data);
var offset = labelOrientation.maxExtent;
titleJoin.enter().append('text').classed(labelClass, true);
// There's only one, but we'll do it as a join so it's updated nicely:
titleJoin.each(function () {
var orientation = orientText(trace, xa, ya, xy, dxy);
if (['start', 'both'].indexOf(axis.showticklabels) === -1) {
offset = 0;
}
// In addition to the size of the labels, add on some extra padding:
var titleSize = axis.title.font.size;
offset += titleSize + axis.title.offset;
var labelNorm = labelOrientation.angle + (labelOrientation.flip < 0 ? 180 : 0);
var angleDiff = (labelNorm - orientation.angle + 450) % 360;
var reverseTitle = angleDiff > 90 && angleDiff < 270;
var el = d3.select(this);
el.text(axis.title.text).call(svgTextUtils.convertToTspans, gd);
if (reverseTitle) {
offset = (-svgTextUtils.lineCount(el) + midShift) * lineSpacing * titleSize - offset;
}
el.attr('transform', strTranslate(orientation.p[0], orientation.p[1]) + strRotate(orientation.angle) + strTranslate(0, offset)).attr('text-anchor', 'middle').call(Drawing.font, axis.title.font);
});
titleJoin.exit().remove();
}
/***/ }),
/***/ 81000:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(24588);
var search = (__webpack_require__(14952).findBin);
var computeControlPoints = __webpack_require__(30180);
var createSplineEvaluator = __webpack_require__(29056);
var createIDerivativeEvaluator = __webpack_require__(26435);
var createJDerivativeEvaluator = __webpack_require__(24464);
/*
* Create conversion functions to go from one basis to another. In particular the letter
* abbreviations are:
*
* i: i/j coordinates along the grid. Integer values correspond to data points
* a: real-valued coordinates along the a/b axes
* c: cartesian x-y coordinates
* p: screen-space pixel coordinates
*/
module.exports = function setConvert(trace) {
var a = trace._a;
var b = trace._b;
var na = a.length;
var nb = b.length;
var aax = trace.aaxis;
var bax = trace.baxis;
// Grab the limits once rather than recomputing the bounds for every point
// independently:
var amin = a[0];
var amax = a[na - 1];
var bmin = b[0];
var bmax = b[nb - 1];
var arange = a[a.length - 1] - a[0];
var brange = b[b.length - 1] - b[0];
// Compute the tolerance so that points are visible slightly outside the
// defined carpet axis:
var atol = arange * constants.RELATIVE_CULL_TOLERANCE;
var btol = brange * constants.RELATIVE_CULL_TOLERANCE;
// Expand the limits to include the relative tolerance:
amin -= atol;
amax += atol;
bmin -= btol;
bmax += btol;
trace.isVisible = function (a, b) {
return a > amin && a < amax && b > bmin && b < bmax;
};
trace.isOccluded = function (a, b) {
return a < amin || a > amax || b < bmin || b > bmax;
};
trace.setScale = function () {
var x = trace._x;
var y = trace._y;
// This is potentially a very expensive step! It does the bulk of the work of constructing
// an expanded basis of control points. Note in particular that it overwrites the existing
// basis without creating a new array since that would potentially thrash the garbage
// collector.
var result = computeControlPoints(trace._xctrl, trace._yctrl, x, y, aax.smoothing, bax.smoothing);
trace._xctrl = result[0];
trace._yctrl = result[1];
// This step is the second step in the process, but it's somewhat simpler. It just unrolls
// some logic since it would be unnecessarily expensive to compute both interpolations
// nearly identically but separately and to include a bunch of linear vs. bicubic logic in
// every single call.
trace.evalxy = createSplineEvaluator([trace._xctrl, trace._yctrl], na, nb, aax.smoothing, bax.smoothing);
trace.dxydi = createIDerivativeEvaluator([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing);
trace.dxydj = createJDerivativeEvaluator([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing);
};
/*
* Convert from i/j data grid coordinates to a/b values. Note in particular that this
* is *linear* interpolation, even if the data is interpolated bicubically.
*/
trace.i2a = function (i) {
var i0 = Math.max(0, Math.floor(i[0]), na - 2);
var ti = i[0] - i0;
return (1 - ti) * a[i0] + ti * a[i0 + 1];
};
trace.j2b = function (j) {
var j0 = Math.max(0, Math.floor(j[1]), na - 2);
var tj = j[1] - j0;
return (1 - tj) * b[j0] + tj * b[j0 + 1];
};
trace.ij2ab = function (ij) {
return [trace.i2a(ij[0]), trace.j2b(ij[1])];
};
/*
* Convert from a/b coordinates to i/j grid-numbered coordinates. This requires searching
* through the a/b data arrays and assumes they are monotonic, which is presumed to have
* been enforced already.
*/
trace.a2i = function (aval) {
var i0 = Math.max(0, Math.min(search(aval, a), na - 2));
var a0 = a[i0];
var a1 = a[i0 + 1];
return Math.max(0, Math.min(na - 1, i0 + (aval - a0) / (a1 - a0)));
};
trace.b2j = function (bval) {
var j0 = Math.max(0, Math.min(search(bval, b), nb - 2));
var b0 = b[j0];
var b1 = b[j0 + 1];
return Math.max(0, Math.min(nb - 1, j0 + (bval - b0) / (b1 - b0)));
};
trace.ab2ij = function (ab) {
return [trace.a2i(ab[0]), trace.b2j(ab[1])];
};
/*
* Convert from i/j coordinates to x/y caretesian coordinates. This means either bilinear
* or bicubic spline evaluation, but the hard part is already done at this point.
*/
trace.i2c = function (i, j) {
return trace.evalxy([], i, j);
};
trace.ab2xy = function (aval, bval, extrapolate) {
if (!extrapolate && (aval < a[0] || aval > a[na - 1] | bval < b[0] || bval > b[nb - 1])) {
return [false, false];
}
var i = trace.a2i(aval);
var j = trace.b2j(bval);
var pt = trace.evalxy([], i, j);
if (extrapolate) {
// This section uses the boundary derivatives to extrapolate linearly outside
// the defined range. Consider a scatter line with one point inside the carpet
// axis and one point outside. If we don't extrapolate, we can't draw the line
// at all.
var iex = 0;
var jex = 0;
var der = [];
var i0, ti, j0, tj;
if (aval < a[0]) {
i0 = 0;
ti = 0;
iex = (aval - a[0]) / (a[1] - a[0]);
} else if (aval > a[na - 1]) {
i0 = na - 2;
ti = 1;
iex = (aval - a[na - 1]) / (a[na - 1] - a[na - 2]);
} else {
i0 = Math.max(0, Math.min(na - 2, Math.floor(i)));
ti = i - i0;
}
if (bval < b[0]) {
j0 = 0;
tj = 0;
jex = (bval - b[0]) / (b[1] - b[0]);
} else if (bval > b[nb - 1]) {
j0 = nb - 2;
tj = 1;
jex = (bval - b[nb - 1]) / (b[nb - 1] - b[nb - 2]);
} else {
j0 = Math.max(0, Math.min(nb - 2, Math.floor(j)));
tj = j - j0;
}
if (iex) {
trace.dxydi(der, i0, j0, ti, tj);
pt[0] += der[0] * iex;
pt[1] += der[1] * iex;
}
if (jex) {
trace.dxydj(der, i0, j0, ti, tj);
pt[0] += der[0] * jex;
pt[1] += der[1] * jex;
}
}
return pt;
};
trace.c2p = function (xy, xa, ya) {
return [xa.c2p(xy[0]), ya.c2p(xy[1])];
};
trace.p2x = function (p, xa, ya) {
return [xa.p2c(p[0]), ya.p2c(p[1])];
};
trace.dadi = function (i /* , u*/) {
// Right now only a piecewise linear a or b basis is permitted since smoother interpolation
// would cause monotonicity problems. As a retult, u is entirely disregarded in this
// computation, though we'll specify it as a parameter for the sake of completeness and
// future-proofing. It would be possible to use monotonic cubic interpolation, for example.
//
// See: https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
// u = u || 0;
var i0 = Math.max(0, Math.min(a.length - 2, i));
// The step (denominator) is implicitly 1 since that's the grid spacing.
return a[i0 + 1] - a[i0];
};
trace.dbdj = function (j /* , v*/) {
// See above caveats for dadi which also apply here
var j0 = Math.max(0, Math.min(b.length - 2, j));
// The step (denominator) is implicitly 1 since that's the grid spacing.
return b[j0 + 1] - b[j0];
};
// Takes: grid cell coordinate (i, j) and fractional grid cell coordinates (u, v)
// Returns: (dx/da, dy/db)
//
// NB: separate grid cell + fractional grid cell coordinate format is due to the discontinuous
// derivative, as described better in create_i_derivative_evaluator.js
trace.dxyda = function (i0, j0, u, v) {
var dxydi = trace.dxydi(null, i0, j0, u, v);
var dadi = trace.dadi(i0, u);
return [dxydi[0] / dadi, dxydi[1] / dadi];
};
trace.dxydb = function (i0, j0, u, v) {
var dxydj = trace.dxydj(null, i0, j0, u, v);
var dbdj = trace.dbdj(j0, v);
return [dxydj[0] / dbdj, dxydj[1] / dbdj];
};
// Sometimes we don't care about precision and all we really want is decent rough
// directions (as is the case with labels). In that case, we can do a very rough finite
// difference and spare having to worry about precise grid coordinates:
trace.dxyda_rough = function (a, b, reldiff) {
var h = arange * (reldiff || 0.1);
var plus = trace.ab2xy(a + h, b, true);
var minus = trace.ab2xy(a - h, b, true);
return [(plus[0] - minus[0]) * 0.5 / h, (plus[1] - minus[1]) * 0.5 / h];
};
trace.dxydb_rough = function (a, b, reldiff) {
var h = brange * (reldiff || 0.1);
var plus = trace.ab2xy(a, b + h, true);
var minus = trace.ab2xy(a, b - h, true);
return [(plus[0] - minus[0]) * 0.5 / h, (plus[1] - minus[1]) * 0.5 / h];
};
trace.dpdx = function (xa) {
return xa._m;
};
trace.dpdy = function (ya) {
return ya._m;
};
};
/***/ }),
/***/ 51512:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
/*
* Given a 2D array as well as a basis in either direction, this function fills in the
* 2D array using a combination of smoothing and extrapolation. This is rather important
* for carpet plots since it's used for layout so that we can't simply omit or blank out
* points. We need a reasonable guess so that the interpolation puts points somewhere
* even if we were to somehow represent that the data was missing later on.
*
* input:
* - data: 2D array of arrays
* - a: array such that a.length === data[0].length
* - b: array such that b.length === data.length
*/
module.exports = function smoothFill2dArray(data, a, b) {
var i, j, k;
var ip = [];
var jp = [];
// var neighborCnts = [];
var ni = data[0].length;
var nj = data.length;
function avgSurrounding(i, j) {
// As a low-quality start, we can simply average surrounding points (in a not
// non-uniform grid aware manner):
var sum = 0.0;
var val;
var cnt = 0;
if (i > 0 && (val = data[j][i - 1]) !== undefined) {
cnt++;
sum += val;
}
if (i < ni - 1 && (val = data[j][i + 1]) !== undefined) {
cnt++;
sum += val;
}
if (j > 0 && (val = data[j - 1][i]) !== undefined) {
cnt++;
sum += val;
}
if (j < nj - 1 && (val = data[j + 1][i]) !== undefined) {
cnt++;
sum += val;
}
return sum / Math.max(1, cnt);
}
// This loop iterates over all cells. Any cells that are null will be noted and those
// are the only points we will loop over and update via laplace's equation. Points with
// any neighbors will receive the average. If there are no neighboring points, then they
// will be set to zero. Also as we go, track the maximum magnitude so that we can scale
// our tolerance accordingly.
var dmax = 0.0;
for (i = 0; i < ni; i++) {
for (j = 0; j < nj; j++) {
if (data[j][i] === undefined) {
ip.push(i);
jp.push(j);
data[j][i] = avgSurrounding(i, j);
// neighborCnts.push(result.neighbors);
}
dmax = Math.max(dmax, Math.abs(data[j][i]));
}
}
if (!ip.length) return data;
// The tolerance doesn't need to be excessive. It's just for display positioning
var dxp, dxm, dap, dam, dbp, dbm, c, d, diff, reldiff, overrelaxation;
var tol = 1e-5;
var resid = 0;
var itermax = 100;
var iter = 0;
var n = ip.length;
do {
resid = 0;
// Normally we'd loop in two dimensions, but not all points are blank and need
// an update, so we instead loop only over the points that were tabulated above
for (k = 0; k < n; k++) {
i = ip[k];
j = jp[k];
// neighborCnt = neighborCnts[k];
// Track a counter for how many contributions there are. We'll use this counter
// to average at the end, which reduces to laplace's equation with neumann boundary
// conditions on the first derivative (second derivative is zero so that we get
// a nice linear extrapolation at the boundaries).
var boundaryCnt = 0;
var newVal = 0;
var d0, d1, x0, x1, i0, j0;
if (i === 0) {
// If this lies along the i = 0 boundary, extrapolate from the two points
// to the right of this point. Note that the finite differences take into
// account non-uniform grid spacing:
i0 = Math.min(ni - 1, 2);
x0 = a[i0];
x1 = a[1];
d0 = data[j][i0];
d1 = data[j][1];
newVal += d1 + (d1 - d0) * (a[0] - x1) / (x1 - x0);
boundaryCnt++;
} else if (i === ni - 1) {
// If along the high i boundary, extrapolate from the two points to the
// left of this point
i0 = Math.max(0, ni - 3);
x0 = a[i0];
x1 = a[ni - 2];
d0 = data[j][i0];
d1 = data[j][ni - 2];
newVal += d1 + (d1 - d0) * (a[ni - 1] - x1) / (x1 - x0);
boundaryCnt++;
}
if ((i === 0 || i === ni - 1) && j > 0 && j < nj - 1) {
// If along the min(i) or max(i) boundaries, also smooth vertically as long
// as we're not in a corner. Note that the finite differences used here
// are also aware of nonuniform grid spacing:
dxp = b[j + 1] - b[j];
dxm = b[j] - b[j - 1];
newVal += (dxm * data[j + 1][i] + dxp * data[j - 1][i]) / (dxm + dxp);
boundaryCnt++;
}
if (j === 0) {
// If along the j = 0 boundary, extrpolate this point from the two points
// above it
j0 = Math.min(nj - 1, 2);
x0 = b[j0];
x1 = b[1];
d0 = data[j0][i];
d1 = data[1][i];
newVal += d1 + (d1 - d0) * (b[0] - x1) / (x1 - x0);
boundaryCnt++;
} else if (j === nj - 1) {
// Same for the max j boundary from the cells below it:
j0 = Math.max(0, nj - 3);
x0 = b[j0];
x1 = b[nj - 2];
d0 = data[j0][i];
d1 = data[nj - 2][i];
newVal += d1 + (d1 - d0) * (b[nj - 1] - x1) / (x1 - x0);
boundaryCnt++;
}
if ((j === 0 || j === nj - 1) && i > 0 && i < ni - 1) {
// Now average points to the left/right as long as not in a corner:
dxp = a[i + 1] - a[i];
dxm = a[i] - a[i - 1];
newVal += (dxm * data[j][i + 1] + dxp * data[j][i - 1]) / (dxm + dxp);
boundaryCnt++;
}
if (!boundaryCnt) {
// If none of the above conditions were triggered, then this is an interior
// point and we can just do a laplace equation update. As above, these differences
// are aware of nonuniform grid spacing:
dap = a[i + 1] - a[i];
dam = a[i] - a[i - 1];
dbp = b[j + 1] - b[j];
dbm = b[j] - b[j - 1];
// These are just some useful constants for the iteration, which is perfectly
// straightforward but a little long to derive from f_xx + f_yy = 0.
c = dap * dam * (dap + dam);
d = dbp * dbm * (dbp + dbm);
newVal = (c * (dbm * data[j + 1][i] + dbp * data[j - 1][i]) + d * (dam * data[j][i + 1] + dap * data[j][i - 1])) / (d * (dam + dap) + c * (dbm + dbp));
} else {
// If we did have contributions from the boundary conditions, then average
// the result from the various contributions:
newVal /= boundaryCnt;
}
// Jacobi updates are ridiculously slow to converge, so this approach uses a
// Gauss-seidel iteration which is dramatically faster.
diff = newVal - data[j][i];
reldiff = diff / dmax;
resid += reldiff * reldiff;
// Gauss-Seidel-ish iteration, omega chosen based on heuristics and some
// quick tests.
//
// NB: Don't overrelax the boundarie. Otherwise set an overrelaxation factor
// which is a little low but safely optimal-ish:
overrelaxation = boundaryCnt ? 0 : 0.85;
// If there are four non-null neighbors, then we want a simple average without
// overrelaxation. If all the surrounding points are null, then we want the full
// overrelaxation
//
// Based on experiments, this actually seems to slow down convergence just a bit.
// I'll leave it here for reference in case this needs to be revisited, but
// it seems to work just fine without this.
// if (overrelaxation) overrelaxation *= (4 - neighborCnt) / 4;
data[j][i] += diff * (1 + overrelaxation);
}
resid = Math.sqrt(resid);
} while (iter++ < itermax && resid > tol);
Lib.log('Smoother converged to', resid, 'after', iter, 'iterations');
return data;
};
/***/ }),
/***/ 86411:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isArray1D = (__webpack_require__(3400).isArray1D);
module.exports = function handleXYDefaults(traceIn, traceOut, coerce) {
var x = coerce('x');
var hasX = x && x.length;
var y = coerce('y');
var hasY = y && y.length;
if (!hasX && !hasY) return false;
traceOut._cheater = !x;
if ((!hasX || isArray1D(x)) && (!hasY || isArray1D(y))) {
var len = hasX ? x.length : Infinity;
if (hasY) len = Math.min(len, y.length);
if (traceOut.a && traceOut.a.length) len = Math.min(len, traceOut.a.length);
if (traceOut.b && traceOut.b.length) len = Math.min(len, traceOut.b.length);
traceOut._length = len;
} else traceOut._length = null;
return true;
};
/***/ }),
/***/ 83372:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var scatterGeoAttrs = __webpack_require__(6096);
var colorScaleAttrs = __webpack_require__(49084);
var baseAttrs = __webpack_require__(45464);
var defaultLine = (__webpack_require__(22548).defaultLine);
var extendFlat = (__webpack_require__(92880).extendFlat);
var scatterGeoMarkerLineAttrs = scatterGeoAttrs.marker.line;
module.exports = extendFlat({
locations: {
valType: 'data_array',
editType: 'calc'
},
locationmode: scatterGeoAttrs.locationmode,
z: {
valType: 'data_array',
editType: 'calc'
},
geojson: extendFlat({}, scatterGeoAttrs.geojson, {}),
featureidkey: scatterGeoAttrs.featureidkey,
text: extendFlat({}, scatterGeoAttrs.text, {}),
hovertext: extendFlat({}, scatterGeoAttrs.hovertext, {}),
marker: {
line: {
color: extendFlat({}, scatterGeoMarkerLineAttrs.color, {
dflt: defaultLine
}),
width: extendFlat({}, scatterGeoMarkerLineAttrs.width, {
dflt: 1
}),
editType: 'calc'
},
opacity: {
valType: 'number',
arrayOk: true,
min: 0,
max: 1,
dflt: 1,
editType: 'style'
},
editType: 'calc'
},
selected: {
marker: {
opacity: scatterGeoAttrs.selected.marker.opacity,
editType: 'plot'
},
editType: 'plot'
},
unselected: {
marker: {
opacity: scatterGeoAttrs.unselected.marker.opacity,
editType: 'plot'
},
editType: 'plot'
},
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
editType: 'calc',
flags: ['location', 'z', 'text', 'name']
}),
hovertemplate: hovertemplateAttrs(),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
}, colorScaleAttrs('', {
cLetter: 'z',
editTypeOverride: 'calc'
}));
/***/ }),
/***/ 7924:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var BADNUM = (__webpack_require__(39032).BADNUM);
var colorscaleCalc = __webpack_require__(47128);
var arraysToCalcdata = __webpack_require__(20148);
var calcSelection = __webpack_require__(4500);
function isNonBlankString(v) {
return v && typeof v === 'string';
}
module.exports = function calc(gd, trace) {
var len = trace._length;
var calcTrace = new Array(len);
var isValidLoc;
if (trace.geojson) {
isValidLoc = function (v) {
return isNonBlankString(v) || isNumeric(v);
};
} else {
isValidLoc = isNonBlankString;
}
for (var i = 0; i < len; i++) {
var calcPt = calcTrace[i] = {};
var loc = trace.locations[i];
var z = trace.z[i];
if (isValidLoc(loc) && isNumeric(z)) {
calcPt.loc = loc;
calcPt.z = z;
} else {
calcPt.loc = null;
calcPt.z = BADNUM;
}
calcPt.index = i;
}
arraysToCalcdata(calcTrace, trace);
colorscaleCalc(gd, trace, {
vals: trace.z,
containerStr: '',
cLetter: 'z'
});
calcSelection(calcTrace, trace);
return calcTrace;
};
/***/ }),
/***/ 30972:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(83372);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var locations = coerce('locations');
var z = coerce('z');
if (!(locations && locations.length && Lib.isArrayOrTypedArray(z) && z.length)) {
traceOut.visible = false;
return;
}
traceOut._length = Math.min(locations.length, z.length);
var geojson = coerce('geojson');
var locationmodeDflt;
if (typeof geojson === 'string' && geojson !== '' || Lib.isPlainObject(geojson)) {
locationmodeDflt = 'geojson-id';
}
var locationMode = coerce('locationmode', locationmodeDflt);
if (locationMode === 'geojson-id') {
coerce('featureidkey');
}
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
var mlw = coerce('marker.line.width');
if (mlw) coerce('marker.line.color');
coerce('marker.opacity');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'z'
});
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
/***/ }),
/***/ 52428:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt, trace, cd, pointNumber) {
out.location = pt.location;
out.z = pt.z;
// include feature properties from input geojson
var cdi = cd[pointNumber];
if (cdi.fIn && cdi.fIn.properties) {
out.properties = cdi.fIn.properties;
}
out.ct = cdi.ct;
return out;
};
/***/ }),
/***/ 69224:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var attributes = __webpack_require__(83372);
var fillText = (__webpack_require__(3400).fillText);
module.exports = function hoverPoints(pointData, xval, yval) {
var cd = pointData.cd;
var trace = cd[0].trace;
var geo = pointData.subplot;
var pt, i, j, isInside;
var xy = [xval, yval];
var altXy = [xval + 360, yval];
for (i = 0; i < cd.length; i++) {
pt = cd[i];
isInside = false;
if (pt._polygons) {
for (j = 0; j < pt._polygons.length; j++) {
if (pt._polygons[j].contains(xy)) {
isInside = !isInside;
}
// for polygons that cross antimeridian as xval is in [-180, 180]
if (pt._polygons[j].contains(altXy)) {
isInside = !isInside;
}
}
if (isInside) break;
}
}
if (!isInside || !pt) return;
pointData.x0 = pointData.x1 = pointData.xa.c2p(pt.ct);
pointData.y0 = pointData.y1 = pointData.ya.c2p(pt.ct);
pointData.index = pt.index;
pointData.location = pt.loc;
pointData.z = pt.z;
pointData.zLabel = Axes.tickText(geo.mockAxis, geo.mockAxis.c2l(pt.z), 'hover').text;
pointData.hovertemplate = pt.hovertemplate;
makeHoverInfo(pointData, trace, pt);
return [pointData];
};
function makeHoverInfo(pointData, trace, pt) {
if (trace.hovertemplate) return;
var hoverinfo = pt.hi || trace.hoverinfo;
var loc = String(pt.loc);
var parts = hoverinfo === 'all' ? attributes.hoverinfo.flags : hoverinfo.split('+');
var hasName = parts.indexOf('name') !== -1;
var hasLocation = parts.indexOf('location') !== -1;
var hasZ = parts.indexOf('z') !== -1;
var hasText = parts.indexOf('text') !== -1;
var hasIdAsNameLabel = !hasName && hasLocation;
var text = [];
if (hasIdAsNameLabel) {
pointData.nameOverride = loc;
} else {
if (hasName) pointData.nameOverride = trace.name;
if (hasLocation) text.push(loc);
}
if (hasZ) {
text.push(pointData.zLabel);
}
if (hasText) {
fillText(pt, trace, text);
}
pointData.extraText = text.join('
');
}
/***/ }),
/***/ 54272:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(83372),
supplyDefaults: __webpack_require__(30972),
colorbar: __webpack_require__(96288),
calc: __webpack_require__(7924),
calcGeoJSON: (__webpack_require__(88364).calcGeoJSON),
plot: (__webpack_require__(88364).plot),
style: (__webpack_require__(7947).style),
styleOnSelect: (__webpack_require__(7947).styleOnSelect),
hoverPoints: __webpack_require__(69224),
eventData: __webpack_require__(52428),
selectPoints: __webpack_require__(17328),
moduleType: 'trace',
name: 'choropleth',
basePlotModule: __webpack_require__(10816),
categories: ['geo', 'noOpacity', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 88364:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var geoUtils = __webpack_require__(27144);
var getTopojsonFeatures = (__webpack_require__(59972).getTopojsonFeatures);
var findExtremes = (__webpack_require__(19280).findExtremes);
var style = (__webpack_require__(7947).style);
function plot(gd, geo, calcData) {
var choroplethLayer = geo.layers.backplot.select('.choroplethlayer');
Lib.makeTraceGroups(choroplethLayer, calcData, 'trace choropleth').each(function (calcTrace) {
var sel = d3.select(this);
var paths = sel.selectAll('path.choroplethlocation').data(Lib.identity);
paths.enter().append('path').classed('choroplethlocation', true);
paths.exit().remove();
// call style here within topojson request callback
style(gd, calcTrace);
});
}
function calcGeoJSON(calcTrace, fullLayout) {
var trace = calcTrace[0].trace;
var geoLayout = fullLayout[trace.geo];
var geo = geoLayout._subplot;
var locationmode = trace.locationmode;
var len = trace._length;
var features = locationmode === 'geojson-id' ? geoUtils.extractTraceFeature(calcTrace) : getTopojsonFeatures(trace, geo.topojson);
var lonArray = [];
var latArray = [];
for (var i = 0; i < len; i++) {
var calcPt = calcTrace[i];
var feature = locationmode === 'geojson-id' ? calcPt.fOut : geoUtils.locationToFeature(locationmode, calcPt.loc, features);
if (feature) {
calcPt.geojson = feature;
calcPt.ct = feature.properties.ct;
calcPt._polygons = geoUtils.feature2polygons(feature);
var bboxFeature = geoUtils.computeBbox(feature);
lonArray.push(bboxFeature[0], bboxFeature[2]);
latArray.push(bboxFeature[1], bboxFeature[3]);
} else {
calcPt.geojson = null;
}
}
if (geoLayout.fitbounds === 'geojson' && locationmode === 'geojson-id') {
var bboxGeojson = geoUtils.computeBbox(geoUtils.getTraceGeojson(trace));
lonArray = [bboxGeojson[0], bboxGeojson[2]];
latArray = [bboxGeojson[1], bboxGeojson[3]];
}
var opts = {
padded: true
};
trace._extremes.lon = findExtremes(geoLayout.lonaxis._ax, lonArray, opts);
trace._extremes.lat = findExtremes(geoLayout.lataxis._ax, latArray, opts);
}
module.exports = {
calcGeoJSON: calcGeoJSON,
plot: plot
};
/***/ }),
/***/ 17328:
/***/ (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, di, ct, x, y;
if (selectionTester === false) {
for (i = 0; i < cd.length; i++) {
cd[i].selected = 0;
}
} else {
for (i = 0; i < cd.length; i++) {
di = cd[i];
ct = di.ct;
if (!ct) continue;
x = xa.c2p(ct);
y = ya.c2p(ct);
if (selectionTester.contains([x, y], null, i, searchInfo)) {
selection.push({
pointNumber: i,
lon: ct[0],
lat: ct[1]
});
di.selected = 1;
} else {
di.selected = 0;
}
}
}
return selection;
};
/***/ }),
/***/ 7947:
/***/ (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 Colorscale = __webpack_require__(8932);
function style(gd, calcTrace) {
if (calcTrace) styleTrace(gd, calcTrace);
}
function styleTrace(gd, calcTrace) {
var trace = calcTrace[0].trace;
var s = calcTrace[0].node3;
var locs = s.selectAll('.choroplethlocation');
var marker = trace.marker || {};
var markerLine = marker.line || {};
var sclFunc = Colorscale.makeColorScaleFuncFromTrace(trace);
locs.each(function (d) {
d3.select(this).attr('fill', sclFunc(d.z)).call(Color.stroke, d.mlc || markerLine.color).call(Drawing.dashLine, '', d.mlw || markerLine.width || 0).style('opacity', marker.opacity);
});
Drawing.selectedPointStyle(locs, trace);
}
function styleOnSelect(gd, calcTrace) {
var s = calcTrace[0].node3;
var trace = calcTrace[0].trace;
if (trace.selectedpoints) {
Drawing.selectedPointStyle(s.selectAll('.choroplethlocation'), trace);
} else {
styleTrace(gd, calcTrace);
}
}
module.exports = {
style: style,
styleOnSelect: styleOnSelect
};
/***/ }),
/***/ 45608:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var choroplethAttrs = __webpack_require__(83372);
var colorScaleAttrs = __webpack_require__(49084);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var baseAttrs = __webpack_require__(45464);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = extendFlat({
locations: {
valType: 'data_array',
editType: 'calc'
},
// TODO
// Maybe start with only one value (that we could name e.g. 'geojson-id'),
// but eventually:
// - we could also support for our own dist/topojson/*
// .. and locationmode: choroplethAttrs.locationmode,
z: {
valType: 'data_array',
editType: 'calc'
},
// TODO maybe we could also set a "key" to dig out values out of the
// GeoJSON feature `properties` fields?
geojson: {
valType: 'any',
editType: 'calc'
},
featureidkey: extendFlat({}, choroplethAttrs.featureidkey, {}),
// TODO agree on name / behaviour
//
// 'below' is used currently for layout.mapbox.layers,
// even though it's not very plotly-esque.
//
// Note also, that the mapbox-gl style don't all have the same layers,
// see https://codepen.io/etpinard/pen/ydVMwM for full list
below: {
valType: 'string',
editType: 'plot'
},
text: choroplethAttrs.text,
hovertext: choroplethAttrs.hovertext,
marker: {
line: {
color: extendFlat({}, choroplethAttrs.marker.line.color, {
editType: 'plot'
}),
width: extendFlat({}, choroplethAttrs.marker.line.width, {
editType: 'plot'
}),
editType: 'calc'
},
// TODO maybe having a dflt less than 1, together with `below:''` would be better?
opacity: extendFlat({}, choroplethAttrs.marker.opacity, {
editType: 'plot'
}),
editType: 'calc'
},
selected: {
marker: {
opacity: extendFlat({}, choroplethAttrs.selected.marker.opacity, {
editType: 'plot'
}),
editType: 'plot'
},
editType: 'plot'
},
unselected: {
marker: {
opacity: extendFlat({}, choroplethAttrs.unselected.marker.opacity, {
editType: 'plot'
}),
editType: 'plot'
},
editType: 'plot'
},
hoverinfo: choroplethAttrs.hoverinfo,
hovertemplate: hovertemplateAttrs({}, {
keys: ['properties']
}),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
}, colorScaleAttrs('', {
cLetter: 'z',
editTypeOverride: 'calc'
}));
/***/ }),
/***/ 13504:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var Colorscale = __webpack_require__(8932);
var Drawing = __webpack_require__(43616);
var makeBlank = (__webpack_require__(44808).makeBlank);
var geoUtils = __webpack_require__(27144);
/* N.B.
*
* We fetch the GeoJSON files "ourselves" (during
* mapbox.prototype.fetchMapData) where they are stored in a global object
* named `PlotlyGeoAssets` (same as for topojson files in `geo` subplots).
*
* Mapbox does allow using URLs as geojson sources, but does NOT allow filtering
* features by feature `id` that are not numbers (more info in:
* https://github.com/mapbox/mapbox-gl-js/issues/8088).
*/
function convert(calcTrace) {
var trace = calcTrace[0].trace;
var isVisible = trace.visible === true && trace._length !== 0;
var fill = {
layout: {
visibility: 'none'
},
paint: {}
};
var line = {
layout: {
visibility: 'none'
},
paint: {}
};
var opts = trace._opts = {
fill: fill,
line: line,
geojson: makeBlank()
};
if (!isVisible) return opts;
var features = geoUtils.extractTraceFeature(calcTrace);
if (!features) return opts;
var sclFunc = Colorscale.makeColorScaleFuncFromTrace(trace);
var marker = trace.marker;
var markerLine = marker.line || {};
var opacityFn;
if (Lib.isArrayOrTypedArray(marker.opacity)) {
opacityFn = function (d) {
var mo = d.mo;
return isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
};
}
var lineColorFn;
if (Lib.isArrayOrTypedArray(markerLine.color)) {
lineColorFn = function (d) {
return d.mlc;
};
}
var lineWidthFn;
if (Lib.isArrayOrTypedArray(markerLine.width)) {
lineWidthFn = function (d) {
return d.mlw;
};
}
for (var i = 0; i < calcTrace.length; i++) {
var cdi = calcTrace[i];
var fOut = cdi.fOut;
if (fOut) {
var props = fOut.properties;
props.fc = sclFunc(cdi.z);
if (opacityFn) props.mo = opacityFn(cdi);
if (lineColorFn) props.mlc = lineColorFn(cdi);
if (lineWidthFn) props.mlw = lineWidthFn(cdi);
cdi.ct = props.ct;
cdi._polygons = geoUtils.feature2polygons(fOut);
}
}
var opacitySetting = opacityFn ? {
type: 'identity',
property: 'mo'
} : marker.opacity;
Lib.extendFlat(fill.paint, {
'fill-color': {
type: 'identity',
property: 'fc'
},
'fill-opacity': opacitySetting
});
Lib.extendFlat(line.paint, {
'line-color': lineColorFn ? {
type: 'identity',
property: 'mlc'
} : markerLine.color,
'line-width': lineWidthFn ? {
type: 'identity',
property: 'mlw'
} : markerLine.width,
'line-opacity': opacitySetting
});
fill.layout.visibility = 'visible';
line.layout.visibility = 'visible';
opts.geojson = {
type: 'FeatureCollection',
features: features
};
convertOnSelect(calcTrace);
return opts;
}
function convertOnSelect(calcTrace) {
var trace = calcTrace[0].trace;
var opts = trace._opts;
var opacitySetting;
if (trace.selectedpoints) {
var fns = Drawing.makeSelectedPointStyleFns(trace);
for (var i = 0; i < calcTrace.length; i++) {
var cdi = calcTrace[i];
if (cdi.fOut) {
cdi.fOut.properties.mo2 = fns.selectedOpacityFn(cdi);
}
}
opacitySetting = {
type: 'identity',
property: 'mo2'
};
} else {
opacitySetting = Lib.isArrayOrTypedArray(trace.marker.opacity) ? {
type: 'identity',
property: 'mo'
} : trace.marker.opacity;
}
Lib.extendFlat(opts.fill.paint, {
'fill-opacity': opacitySetting
});
Lib.extendFlat(opts.line.paint, {
'line-opacity': opacitySetting
});
return opts;
}
module.exports = {
convert: convert,
convertOnSelect: convertOnSelect
};
/***/ }),
/***/ 9352:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(45608);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var locations = coerce('locations');
var z = coerce('z');
var geojson = coerce('geojson');
if (!Lib.isArrayOrTypedArray(locations) || !locations.length || !Lib.isArrayOrTypedArray(z) || !z.length || !(typeof geojson === 'string' && geojson !== '' || Lib.isPlainObject(geojson))) {
traceOut.visible = false;
return;
}
coerce('featureidkey');
traceOut._length = Math.min(locations.length, z.length);
coerce('below');
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
var mlw = coerce('marker.line.width');
if (mlw) coerce('marker.line.color');
coerce('marker.opacity');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'z'
});
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
/***/ }),
/***/ 85404:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(45608),
supplyDefaults: __webpack_require__(9352),
colorbar: __webpack_require__(96288),
calc: __webpack_require__(7924),
plot: __webpack_require__(61288),
hoverPoints: __webpack_require__(69224),
eventData: __webpack_require__(52428),
selectPoints: __webpack_require__(17328),
styleOnSelect: function (_, cd) {
if (cd) {
var trace = cd[0].trace;
trace._glTrace.updateOnSelect(cd);
}
},
getBelow: function (trace, subplot) {
var mapLayers = subplot.getMapLayers();
// find layer just above top-most "water" layer
// that is not a plotly layer
for (var i = mapLayers.length - 2; i >= 0; i--) {
var layerId = mapLayers[i].id;
if (typeof layerId === 'string' && layerId.indexOf('water') === 0) {
for (var j = i + 1; j < mapLayers.length; j++) {
layerId = mapLayers[j].id;
if (typeof layerId === 'string' && layerId.indexOf('plotly-') === -1) {
return layerId;
}
}
}
}
},
moduleType: 'trace',
name: 'choroplethmapbox',
basePlotModule: __webpack_require__(33688),
categories: ['mapbox', 'gl', 'noOpacity', 'showLegend'],
meta: {
hr_name: 'choropleth_mapbox'
}
};
/***/ }),
/***/ 61288:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var convert = (__webpack_require__(13504).convert);
var convertOnSelect = (__webpack_require__(13504).convertOnSelect);
var LAYER_PREFIX = (__webpack_require__(47552).traceLayerPrefix);
function ChoroplethMapbox(subplot, uid) {
this.type = 'choroplethmapbox';
this.subplot = subplot;
this.uid = uid;
// N.B. fill and line layers share same source
this.sourceId = 'source-' + uid;
this.layerList = [['fill', LAYER_PREFIX + uid + '-fill'], ['line', LAYER_PREFIX + uid + '-line']];
// previous 'below' value,
// need this to update it properly
this.below = null;
}
var proto = ChoroplethMapbox.prototype;
proto.update = function (calcTrace) {
this._update(convert(calcTrace));
// link ref for quick update during selections
calcTrace[0].trace._glTrace = this;
};
proto.updateOnSelect = function (calcTrace) {
this._update(convertOnSelect(calcTrace));
};
proto._update = function (optsAll) {
var subplot = this.subplot;
var layerList = this.layerList;
var below = subplot.belowLookup['trace-' + this.uid];
subplot.map.getSource(this.sourceId).setData(optsAll.geojson);
if (below !== this.below) {
this._removeLayers();
this._addLayers(optsAll, below);
this.below = below;
}
for (var i = 0; i < layerList.length; i++) {
var item = layerList[i];
var k = item[0];
var id = item[1];
var opts = optsAll[k];
subplot.setOptions(id, 'setLayoutProperty', opts.layout);
if (opts.layout.visibility === 'visible') {
subplot.setOptions(id, 'setPaintProperty', opts.paint);
}
}
};
proto._addLayers = function (optsAll, below) {
var subplot = this.subplot;
var layerList = this.layerList;
var sourceId = this.sourceId;
for (var i = 0; i < layerList.length; i++) {
var item = layerList[i];
var k = item[0];
var opts = optsAll[k];
subplot.addLayer({
type: k,
id: item[1],
source: sourceId,
layout: opts.layout,
paint: opts.paint
}, below);
}
};
proto._removeLayers = function () {
var map = this.subplot.map;
var layerList = this.layerList;
for (var i = layerList.length - 1; i >= 0; i--) {
map.removeLayer(layerList[i][1]);
}
};
proto.dispose = function () {
var map = this.subplot.map;
this._removeLayers();
map.removeSource(this.sourceId);
};
module.exports = function createChoroplethMapbox(subplot, calcTrace) {
var trace = calcTrace[0].trace;
var choroplethMapbox = new ChoroplethMapbox(subplot, trace.uid);
var sourceId = choroplethMapbox.sourceId;
var optsAll = convert(calcTrace);
var below = choroplethMapbox.below = subplot.belowLookup['trace-' + trace.uid];
subplot.map.addSource(sourceId, {
type: 'geojson',
data: optsAll.geojson
});
choroplethMapbox._addLayers(optsAll, below);
// link ref for quick update during selections
calcTrace[0].trace._glTrace = choroplethMapbox;
return choroplethMapbox;
};
/***/ }),
/***/ 86040:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorScaleAttrs = __webpack_require__(49084);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var mesh3dAttrs = __webpack_require__(52948);
var baseAttrs = __webpack_require__(45464);
var extendFlat = (__webpack_require__(92880).extendFlat);
var attrs = {
x: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
y: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
z: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
u: {
valType: 'data_array',
editType: 'calc'
},
v: {
valType: 'data_array',
editType: 'calc'
},
w: {
valType: 'data_array',
editType: 'calc'
},
// TODO add way to specify cone positions independently of the vector field
// provided, similar to MATLAB's coneplot Cx/Cy/Cz meshgrids,
// see https://www.mathworks.com/help/matlab/ref/coneplot.html
//
// Alternatively, if our goal is only to 'fill in gaps' in the vector data,
// we could try to extend the heatmap 'connectgaps' algorithm to 3D.
// From AJ: this particular algorithm which amounts to a Poisson equation,
// both for interpolation and extrapolation - is the right one to use for
// cones too. It makes a field with zero divergence, which is a good
// baseline assumption for vector fields.
//
// cones: {
// // potential attributes to add:
// //
// // - meshmode: 'cartesian-product', 'pts', 'grid'
// //
// // under `meshmode: 'grid'`
// // - (x|y|z)grid.start
// // - (x|y|z)grid.end
// // - (x|y|z)grid.size
//
// x: {
// valType: 'data_array',
// editType: 'calc',
//
// },
// y: {
// valType: 'data_array',
// editType: 'calc',
//
// },
// z: {
// valType: 'data_array',
// editType: 'calc',
//
// },
//
// editType: 'calc',
//
// },
sizemode: {
valType: 'enumerated',
values: ['scaled', 'absolute', 'raw'],
editType: 'calc',
dflt: 'scaled'
},
sizeref: {
valType: 'number',
editType: 'calc',
min: 0
},
anchor: {
valType: 'enumerated',
editType: 'calc',
values: ['tip', 'tail', 'cm', 'center'],
dflt: 'cm'
},
text: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'calc'
},
hovertext: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'calc'
},
hovertemplate: hovertemplateAttrs({
editType: 'calc'
}, {
keys: ['norm']
}),
uhoverformat: axisHoverFormat('u', 1),
vhoverformat: axisHoverFormat('v', 1),
whoverformat: axisHoverFormat('w', 1),
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z'),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
};
extendFlat(attrs, colorScaleAttrs('', {
colorAttr: 'u/v/w norm',
showScaleDflt: true,
editTypeOverride: 'calc'
}));
var fromMesh3d = ['opacity', 'lightposition', 'lighting'];
fromMesh3d.forEach(function (k) {
attrs[k] = mesh3dAttrs[k];
});
attrs.hoverinfo = extendFlat({}, baseAttrs.hoverinfo, {
editType: 'calc',
flags: ['x', 'y', 'z', 'u', 'v', 'w', 'norm', 'text', 'name'],
dflt: 'x+y+z+norm+text+name'
});
attrs.transforms = undefined;
module.exports = attrs;
/***/ }),
/***/ 83344:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorscaleCalc = __webpack_require__(47128);
module.exports = function calc(gd, trace) {
var u = trace.u;
var v = trace.v;
var w = trace.w;
var len = Math.min(trace.x.length, trace.y.length, trace.z.length, u.length, v.length, w.length);
var normMax = -Infinity;
var normMin = Infinity;
for (var i = 0; i < len; i++) {
var uu = u[i];
var vv = v[i];
var ww = w[i];
var norm = Math.sqrt(uu * uu + vv * vv + ww * ww);
normMax = Math.max(normMax, norm);
normMin = Math.min(normMin, norm);
}
trace._len = len;
trace._normMax = normMax;
colorscaleCalc(gd, trace, {
vals: [normMin, normMax],
containerStr: '',
cLetter: 'c'
});
};
/***/ }),
/***/ 6648:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var conePlot = (__webpack_require__(67792).gl_cone3d);
var createConeMesh = (__webpack_require__(67792).gl_cone3d).createConeMesh;
var simpleMap = (__webpack_require__(3400).simpleMap);
var parseColorScale = (__webpack_require__(33040).parseColorScale);
var extractOpts = (__webpack_require__(8932).extractOpts);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var zip3 = __webpack_require__(52094);
function Cone(scene, uid) {
this.scene = scene;
this.uid = uid;
this.mesh = null;
this.data = null;
}
var proto = Cone.prototype;
proto.handlePick = function (selection) {
if (selection.object === this.mesh) {
var selectIndex = selection.index = selection.data.index;
var xx = this.data.x[selectIndex];
var yy = this.data.y[selectIndex];
var zz = this.data.z[selectIndex];
var uu = this.data.u[selectIndex];
var vv = this.data.v[selectIndex];
var ww = this.data.w[selectIndex];
selection.traceCoordinate = [xx, yy, zz, uu, vv, ww, Math.sqrt(uu * uu + vv * vv + ww * ww)];
var text = this.data.hovertext || this.data.text;
if (isArrayOrTypedArray(text) && text[selectIndex] !== undefined) {
selection.textLabel = text[selectIndex];
} else if (text) {
selection.textLabel = text;
}
return true;
}
};
var axisName2scaleIndex = {
xaxis: 0,
yaxis: 1,
zaxis: 2
};
var anchor2coneOffset = {
tip: 1,
tail: 0,
cm: 0.25,
center: 0.5
};
var anchor2coneSpan = {
tip: 1,
tail: 1,
cm: 0.75,
center: 0.5
};
function convert(scene, trace) {
var sceneLayout = scene.fullSceneLayout;
var dataScale = scene.dataScale;
var coneOpts = {};
function toDataCoords(arr, axisName) {
var ax = sceneLayout[axisName];
var scale = dataScale[axisName2scaleIndex[axisName]];
return simpleMap(arr, function (v) {
return ax.d2l(v) * scale;
});
}
coneOpts.vectors = zip3(toDataCoords(trace.u, 'xaxis'), toDataCoords(trace.v, 'yaxis'), toDataCoords(trace.w, 'zaxis'), trace._len);
coneOpts.positions = zip3(toDataCoords(trace.x, 'xaxis'), toDataCoords(trace.y, 'yaxis'), toDataCoords(trace.z, 'zaxis'), trace._len);
var cOpts = extractOpts(trace);
coneOpts.colormap = parseColorScale(trace);
coneOpts.vertexIntensityBounds = [cOpts.min / trace._normMax, cOpts.max / trace._normMax];
coneOpts.coneOffset = anchor2coneOffset[trace.anchor];
var sizemode = trace.sizemode;
if (sizemode === 'scaled') {
// unitless sizeref
coneOpts.coneSize = trace.sizeref || 0.5;
} else if (sizemode === 'absolute') {
// sizeref here has unit of velocity
coneOpts.coneSize = trace.sizeref && trace._normMax ? trace.sizeref / trace._normMax : 0.5;
} else if (sizemode === 'raw') {
coneOpts.coneSize = trace.sizeref;
}
coneOpts.coneSizemode = sizemode;
var meshData = conePlot(coneOpts);
// pass gl-mesh3d lighting attributes
var lp = trace.lightposition;
meshData.lightPosition = [lp.x, lp.y, lp.z];
meshData.ambient = trace.lighting.ambient;
meshData.diffuse = trace.lighting.diffuse;
meshData.specular = trace.lighting.specular;
meshData.roughness = trace.lighting.roughness;
meshData.fresnel = trace.lighting.fresnel;
meshData.opacity = trace.opacity;
// stash autorange pad value
trace._pad = anchor2coneSpan[trace.anchor] * meshData.vectorScale * meshData.coneScale * trace._normMax;
return meshData;
}
proto.update = function (data) {
this.data = data;
var meshData = convert(this.scene, data);
this.mesh.update(meshData);
};
proto.dispose = function () {
this.scene.glplot.remove(this.mesh);
this.mesh.dispose();
};
function createConeTrace(scene, data) {
var gl = scene.glplot.gl;
var meshData = convert(scene, data);
var mesh = createConeMesh(gl, meshData);
var cone = new Cone(scene, data.uid);
cone.mesh = mesh;
cone.data = data;
mesh._trace = cone;
scene.glplot.add(mesh);
return cone;
}
module.exports = createConeTrace;
/***/ }),
/***/ 86096:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(86040);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var u = coerce('u');
var v = coerce('v');
var w = coerce('w');
var x = coerce('x');
var y = coerce('y');
var z = coerce('z');
if (!u || !u.length || !v || !v.length || !w || !w.length || !x || !x.length || !y || !y.length || !z || !z.length) {
traceOut.visible = false;
return;
}
var sizemode = coerce('sizemode');
coerce('sizeref', sizemode === 'raw' ? 1 : 0.5);
coerce('anchor');
coerce('lighting.ambient');
coerce('lighting.diffuse');
coerce('lighting.specular');
coerce('lighting.roughness');
coerce('lighting.fresnel');
coerce('lightposition.x');
coerce('lightposition.y');
coerce('lightposition.z');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'c'
});
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
coerce('uhoverformat');
coerce('vhoverformat');
coerce('whoverformat');
coerce('xhoverformat');
coerce('yhoverformat');
coerce('zhoverformat');
// disable 1D transforms (for now)
traceOut._length = null;
};
/***/ }),
/***/ 26048:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'cone',
basePlotModule: __webpack_require__(12536),
categories: ['gl3d', 'showLegend'],
attributes: __webpack_require__(86040),
supplyDefaults: __webpack_require__(86096),
colorbar: {
min: 'cmin',
max: 'cmax'
},
calc: __webpack_require__(83344),
plot: __webpack_require__(6648),
eventData: function (out, pt) {
out.norm = pt.traceCoordinate[6];
return out;
},
meta: {}
};
/***/ }),
/***/ 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', globalFont, {
overrideDflt: {
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), {
weight: labelFont.weight,
style: labelFont.style,
variant: labelFont.variant,
textcase: labelFont.textcase,
lineposition: labelFont.lineposition,
shadow: labelFont.shadow,
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);
};
/***/ }),
/***/ 37960:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var heatmapAttrs = __webpack_require__(83328);
var contourAttrs = __webpack_require__(67104);
var colorScaleAttrs = __webpack_require__(49084);
var extendFlat = (__webpack_require__(92880).extendFlat);
var contourContourAttrs = contourAttrs.contours;
module.exports = extendFlat({
carpet: {
valType: 'string',
editType: 'calc'
},
z: heatmapAttrs.z,
a: heatmapAttrs.x,
a0: heatmapAttrs.x0,
da: heatmapAttrs.dx,
b: heatmapAttrs.y,
b0: heatmapAttrs.y0,
db: heatmapAttrs.dy,
text: heatmapAttrs.text,
hovertext: heatmapAttrs.hovertext,
transpose: heatmapAttrs.transpose,
atype: heatmapAttrs.xtype,
btype: heatmapAttrs.ytype,
fillcolor: contourAttrs.fillcolor,
autocontour: contourAttrs.autocontour,
ncontours: contourAttrs.ncontours,
contours: {
type: contourContourAttrs.type,
start: contourContourAttrs.start,
end: contourContourAttrs.end,
size: contourContourAttrs.size,
coloring: {
// from contourAttrs.contours.coloring but no 'heatmap' option
valType: 'enumerated',
values: ['fill', 'lines', 'none'],
dflt: 'fill',
editType: 'calc'
},
showlines: contourContourAttrs.showlines,
showlabels: contourContourAttrs.showlabels,
labelfont: contourContourAttrs.labelfont,
labelformat: contourContourAttrs.labelformat,
operation: contourContourAttrs.operation,
value: contourContourAttrs.value,
editType: 'calc',
impliedEdits: {
autocontour: false
}
},
line: {
color: contourAttrs.line.color,
width: contourAttrs.line.width,
dash: contourAttrs.line.dash,
smoothing: contourAttrs.line.smoothing,
editType: 'plot'
},
zorder: contourAttrs.zorder,
transforms: undefined
}, colorScaleAttrs('', {
cLetter: 'z',
autoColorDflt: false
}));
/***/ }),
/***/ 30572:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorscaleCalc = __webpack_require__(47128);
var Lib = __webpack_require__(3400);
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 supplyDefaults = __webpack_require__(3252);
var lookupCarpet = __webpack_require__(50948);
var setContours = __webpack_require__(54444);
// 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 carpet = trace._carpetTrace = lookupCarpet(gd, trace);
if (!carpet || !carpet.visible || carpet.visible === 'legendonly') return;
if (!trace.a || !trace.b) {
// Look up the original incoming carpet data:
var carpetdata = gd.data[carpet.index];
// Look up the incoming trace data, *except* perform a shallow
// copy so that we're not actually modifying it when we use it
// to supply defaults:
var tracedata = gd.data[trace.index];
// var tracedata = extendFlat({}, gd.data[trace.index]);
// If the data is not specified
if (!tracedata.a) tracedata.a = carpetdata.a;
if (!tracedata.b) tracedata.b = carpetdata.b;
supplyDefaults(tracedata, trace, trace._defaultColor, gd._fullLayout);
}
var cd = heatmappishCalc(gd, trace);
setContours(trace, trace._z);
return cd;
};
function heatmappishCalc(gd, trace) {
// prepare the raw data
// run makeCalcdata on x and y even for heatmaps, in case of category mappings
var carpet = trace._carpetTrace;
var aax = carpet.aaxis;
var bax = carpet.baxis;
var a, a0, da, b, b0, db, z;
// cancel minimum tick spacings (only applies to bars and boxes)
aax._minDtick = 0;
bax._minDtick = 0;
if (Lib.isArray1D(trace.z)) convertColumnData(trace, aax, bax, 'a', 'b', ['z']);
a = trace._a = trace._a || trace.a;
b = trace._b = trace._b || trace.b;
a = a ? aax.makeCalcdata(trace, '_a') : [];
b = b ? bax.makeCalcdata(trace, '_b') : [];
a0 = trace.a0 || 0;
da = trace.da || 1;
b0 = trace.b0 || 0;
db = trace.db || 1;
z = trace._z = clean2dArray(trace._z || trace.z, trace.transpose);
trace._emptypoints = findEmpties(z);
interp2d(z, trace._emptypoints);
// create arrays of brick boundaries, to be used by autorange and heatmap.plot
var xlen = Lib.maxRowLength(z);
var xIn = trace.xtype === 'scaled' ? '' : a;
var xArray = makeBoundArray(trace, xIn, a0, da, xlen, aax);
var yIn = trace.ytype === 'scaled' ? '' : b;
var yArray = makeBoundArray(trace, yIn, b0, db, z.length, bax);
var cd0 = {
a: xArray,
b: yArray,
z: z
};
if (trace.contours.type === 'levels' && trace.contours.coloring !== 'none') {
// auto-z and autocolorscale if applicable
colorscaleCalc(gd, trace, {
vals: z,
containerStr: '',
cLetter: 'z'
});
}
return [cd0];
}
/***/ }),
/***/ 3252:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleXYZDefaults = __webpack_require__(51264);
var attributes = __webpack_require__(37960);
var handleConstraintDefaults = __webpack_require__(95536);
var handleContoursDefaults = __webpack_require__(84952);
var handleStyleDefaults = __webpack_require__(97680);
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);
}
coerce('carpet');
// If either a or b is not present, then it's not a valid trace *unless* the carpet
// axis has the a or b values we're looking for. So if these are not found, just defer
// that decision until the calc step.
//
// NB: the calc step will modify the original data input by assigning whichever of
// a or b are missing. This is necessary because panning goes right from supplyDefaults
// to plot (skipping calc). That means on subsequent updates, this *will* need to be
// able to find a and b.
//
// The long-term proper fix is that this should perhaps use underscored attributes to
// at least modify the user input to a slightly lesser extent. Fully removing the
// input mutation is challenging. The underscore approach is not currently taken since
// it requires modification to all of the functions below that expect the coerced
// attribute name to match the property name -- except '_a' !== 'a' so that is not
// straightforward.
if (traceIn.a && traceIn.b) {
var len = handleXYZDefaults(traceIn, traceOut, coerce, layout, 'a', 'b');
if (!len) {
traceOut.visible = false;
return;
}
coerce('text');
var isConstraint = coerce('contours.type') === 'constraint';
if (isConstraint) {
handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, {
hasHover: false
});
} else {
handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
handleStyleDefaults(traceIn, traceOut, coerce, layout, {
hasHover: false
});
}
} else {
traceOut._defaultColor = defaultColor;
traceOut._length = null;
}
coerce('zorder');
};
/***/ }),
/***/ 40448:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(37960),
supplyDefaults: __webpack_require__(3252),
colorbar: __webpack_require__(55296),
calc: __webpack_require__(30572),
plot: __webpack_require__(94440),
style: __webpack_require__(52440),
moduleType: 'trace',
name: 'contourcarpet',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', 'carpet', 'contour', 'symbols', 'showLegend', 'hasLines', 'carpetDependent', 'noHover', 'noSortingByValue'],
meta: {}
};
/***/ }),
/***/ 94440:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var map1dArray = __webpack_require__(87072);
var makepath = __webpack_require__(53416);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var makeCrossings = __webpack_require__(72424);
var findAllPaths = __webpack_require__(88748);
var contourPlot = __webpack_require__(23676);
var constants = __webpack_require__(93252);
var convertToConstraints = __webpack_require__(82172);
var emptyPathinfo = __webpack_require__(61512);
var closeBoundaries = __webpack_require__(56008);
var lookupCarpet = __webpack_require__(50948);
var axisAlignedLine = __webpack_require__(77712);
module.exports = function plot(gd, plotinfo, cdcontours, contourcarpetLayer) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
Lib.makeTraceGroups(contourcarpetLayer, cdcontours, 'contour').each(function (cd) {
var plotGroup = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
var carpetcd = gd.calcdata[carpet.index][0];
if (!carpet.visible || carpet.visible === 'legendonly') return;
var a = cd0.a;
var b = cd0.b;
var contours = trace.contours;
var pathinfo = emptyPathinfo(contours, plotinfo, cd0);
var isConstraint = contours.type === 'constraint';
var operation = contours._operation;
var coloring = isConstraint ? operation === '=' ? 'lines' : 'fill' : contours.coloring;
// Map [a, b] (data) --> [i, j] (pixels)
function ab2p(ab) {
var pt = carpet.ab2xy(ab[0], ab[1], true);
return [xa.c2p(pt[0]), ya.c2p(pt[1])];
}
// Define the perimeter in a/b coordinates:
var perimeter = [[a[0], b[b.length - 1]], [a[a.length - 1], b[b.length - 1]], [a[a.length - 1], b[0]], [a[0], b[0]]];
// Extract the contour levels:
makeCrossings(pathinfo);
var atol = (a[a.length - 1] - a[0]) * 1e-8;
var btol = (b[b.length - 1] - b[0]) * 1e-8;
findAllPaths(pathinfo, atol, btol);
// Constraints might need to be draw inverted, which is not something contours
// handle by default since they're assumed fully opaque so that they can be
// drawn overlapping. This function flips the paths as necessary so that they're
// drawn correctly.
//
// TODO: Perhaps this should be generalized and *all* paths should be drawn as
// closed regions so that translucent contour levels would be valid.
// See: https://github.com/plotly/plotly.js/issues/1356
var fillPathinfo = pathinfo;
if (contours.type === 'constraint') {
fillPathinfo = convertToConstraints(pathinfo, operation);
}
// Map the paths in a/b coordinates to pixel coordinates:
mapPathinfo(pathinfo, ab2p);
// draw everything
// Compute the boundary path
var seg, xp, yp, i;
var segs = [];
for (i = carpetcd.clipsegments.length - 1; i >= 0; i--) {
seg = carpetcd.clipsegments[i];
xp = map1dArray([], seg.x, xa.c2p);
yp = map1dArray([], seg.y, ya.c2p);
xp.reverse();
yp.reverse();
segs.push(makepath(xp, yp, seg.bicubic));
}
var boundaryPath = 'M' + segs.join('L') + 'Z';
// Draw the baseline background fill that fills in the space behind any other
// contour levels:
makeBackground(plotGroup, carpetcd.clipsegments, xa, ya, isConstraint, coloring);
// Draw the specific contour fills. As a simplification, they're assumed to be
// fully opaque so that it's easy to draw them simply overlapping. The alternative
// would be to flip adjacent paths and draw closed paths for each level instead.
makeFills(trace, plotGroup, xa, ya, fillPathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath);
// Draw contour lines:
makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours, plotinfo, carpet);
// Clip the boundary of the plot
Drawing.setClipUrl(plotGroup, carpet._clipPathId, gd);
});
};
function mapPathinfo(pathinfo, map) {
var i, j, k, pi, pedgepaths, ppaths, pedgepath, ppath, path;
for (i = 0; i < pathinfo.length; i++) {
pi = pathinfo[i];
pedgepaths = pi.pedgepaths = [];
ppaths = pi.ppaths = [];
for (j = 0; j < pi.edgepaths.length; j++) {
path = pi.edgepaths[j];
pedgepath = [];
for (k = 0; k < path.length; k++) {
pedgepath[k] = map(path[k]);
}
pedgepaths.push(pedgepath);
}
for (j = 0; j < pi.paths.length; j++) {
path = pi.paths[j];
ppath = [];
for (k = 0; k < path.length; k++) {
ppath[k] = map(path[k]);
}
ppaths.push(ppath);
}
}
}
function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, plotinfo, carpet) {
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 = contourPlot.createLines(lineContainer, showLines || showLabels, pathinfo, isStatic);
var lineClip = contourPlot.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 xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var xLen = xa._length;
var yLen = ya._length;
// for simplicity use the xy box for label clipping outline.
var labelClipPathData = [[[0, 0], [xLen, 0], [xLen, yLen], [0, yLen]]];
var labelData = [];
// invalidate the getTextLocation cache in case paths changed
Lib.clearLocationCache();
var contourFormat = contourPlot.labelFormatter(gd, cd0);
var dummyText = Drawing.tester.append('text').attr('data-notex', 1).call(Drawing.font, contours.labelfont);
// use `bounds` only to keep labels away from the x/y boundaries
// `constrainToCarpet` below ensures labels don't go off the
// carpet edges
var bounds = {
left: 0,
right: xLen,
center: xLen / 2,
top: 0,
bottom: yLen,
middle: yLen / 2
};
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 = contourPlot.calcTextOpts(d.level, contourFormat, dummyText, gd);
d3.select(this).selectAll('path').each(function (pathData) {
var path = this;
var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
if (!pathBounds) return;
constrainToCarpet(path, pathData, d, pathBounds, carpet, textOpts.height);
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 = contourPlot.findBestTextLocation(path, pathBounds, textOpts, labelData, bounds);
if (!loc) break;
contourPlot.addLabelData(loc, textOpts, labelData, labelClipPathData);
}
});
});
dummyText.remove();
contourPlot.drawLabels(labelGroup, labelData, gd, lineClip, clipLinesForLabels ? labelClipPathData : null);
}
if (showLabels && !showLines) linegroup.remove();
}
// figure out if this path goes off the edge of the carpet
// and shorten the part we call visible to keep labels away from the edge
function constrainToCarpet(path, pathData, levelData, pathBounds, carpet, textHeight) {
var pathABData;
for (var i = 0; i < levelData.pedgepaths.length; i++) {
if (pathData === levelData.pedgepaths[i]) {
pathABData = levelData.edgepaths[i];
}
}
if (!pathABData) return;
var aMin = carpet.a[0];
var aMax = carpet.a[carpet.a.length - 1];
var bMin = carpet.b[0];
var bMax = carpet.b[carpet.b.length - 1];
function getOffset(abPt, pathVector) {
var offset = 0;
var edgeVector;
var dAB = 0.1;
if (Math.abs(abPt[0] - aMin) < dAB || Math.abs(abPt[0] - aMax) < dAB) {
edgeVector = normalizeVector(carpet.dxydb_rough(abPt[0], abPt[1], dAB));
offset = Math.max(offset, textHeight * vectorTan(pathVector, edgeVector) / 2);
}
if (Math.abs(abPt[1] - bMin) < dAB || Math.abs(abPt[1] - bMax) < dAB) {
edgeVector = normalizeVector(carpet.dxyda_rough(abPt[0], abPt[1], dAB));
offset = Math.max(offset, textHeight * vectorTan(pathVector, edgeVector) / 2);
}
return offset;
}
var startVector = getUnitVector(path, 0, 1);
var endVector = getUnitVector(path, pathBounds.total, pathBounds.total - 1);
var minStart = getOffset(pathABData[0], startVector);
var maxEnd = pathBounds.total - getOffset(pathABData[pathABData.length - 1], endVector);
if (pathBounds.min < minStart) pathBounds.min = minStart;
if (pathBounds.max > maxEnd) pathBounds.max = maxEnd;
pathBounds.len = pathBounds.max - pathBounds.min;
}
function getUnitVector(path, p0, p1) {
var pt0 = path.getPointAtLength(p0);
var pt1 = path.getPointAtLength(p1);
var dx = pt1.x - pt0.x;
var dy = pt1.y - pt0.y;
var len = Math.sqrt(dx * dx + dy * dy);
return [dx / len, dy / len];
}
function normalizeVector(v) {
var len = Math.sqrt(v[0] * v[0] + v[1] * v[1]);
return [v[0] / len, v[1] / len];
}
function vectorTan(v0, v1) {
var cos = Math.abs(v0[0] * v1[0] + v0[1] * v1[1]);
var sin = Math.sqrt(1 - cos * cos);
return sin / cos;
}
function makeBackground(plotgroup, clipsegments, xaxis, yaxis, isConstraint, coloring) {
var seg, xp, yp, i;
var bggroup = Lib.ensureSingle(plotgroup, 'g', 'contourbg');
var bgfill = bggroup.selectAll('path').data(coloring === 'fill' && !isConstraint ? [0] : []);
bgfill.enter().append('path');
bgfill.exit().remove();
var segs = [];
for (i = 0; i < clipsegments.length; i++) {
seg = clipsegments[i];
xp = map1dArray([], seg.x, xaxis.c2p);
yp = map1dArray([], seg.y, yaxis.c2p);
segs.push(makepath(xp, yp, seg.bicubic));
}
bgfill.attr('d', 'M' + segs.join('L') + 'Z').style('stroke', 'none');
}
function makeFills(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath) {
var hasFills = coloring === 'fill';
// fills prefixBoundary in pathinfo items
if (hasFills) {
closeBoundaries(pathinfo, trace.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(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya);
if (!fullpath) {
d3.select(this).remove();
} else {
d3.select(this).attr('d', fullpath).style('stroke', 'none');
}
});
}
function joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya) {
var i;
var fullpath = '';
var startsleft = pi.edgepaths.map(function (v, i) {
return i;
});
var newloop = true;
var endpt, newendpt, cnt, nexti, possiblei, addpath;
var atol = Math.abs(perimeter[0][0] - perimeter[2][0]) * 1e-4;
var btol = Math.abs(perimeter[0][1] - perimeter[2][1]) * 1e-4;
function istop(pt) {
return Math.abs(pt[1] - perimeter[0][1]) < btol;
}
function isbottom(pt) {
return Math.abs(pt[1] - perimeter[2][1]) < btol;
}
function isleft(pt) {
return Math.abs(pt[0] - perimeter[0][0]) < atol;
}
function isright(pt) {
return Math.abs(pt[0] - perimeter[2][0]) < atol;
}
function pathto(pt0, pt1) {
var i, j, segments, axis;
var path = '';
if (istop(pt0) && !isright(pt0) || isbottom(pt0) && !isleft(pt0)) {
axis = carpet.aaxis;
segments = axisAlignedLine(carpet, carpetcd, [pt0[0], pt1[0]], 0.5 * (pt0[1] + pt1[1]));
} else {
axis = carpet.baxis;
segments = axisAlignedLine(carpet, carpetcd, 0.5 * (pt0[0] + pt1[0]), [pt0[1], pt1[1]]);
}
for (i = 1; i < segments.length; i++) {
path += axis.smoothing ? 'C' : 'L';
for (j = 0; j < segments[i].length; j++) {
var pt = segments[i][j];
path += [xa.c2p(pt[0]), ya.c2p(pt[1])] + ' ';
}
}
return path;
}
i = 0;
endpt = null;
while (startsleft.length) {
var startpt = pi.edgepaths[i][0];
if (endpt) {
fullpath += pathto(endpt, startpt);
}
addpath = Drawing.smoothopen(pi.edgepaths[i].map(ab2p), 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]; // left top ---> right top
} else if (isleft(endpt)) {
newendpt = perimeter[0]; // left bottom ---> 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]) < atol) {
if (Math.abs(endpt[0] - ptNew[0]) < atol && (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
newendpt = ptNew;
nexti = possiblei;
}
} else if (Math.abs(endpt[1] - newendpt[1]) < btol) {
if (Math.abs(endpt[1] - ptNew[1]) < btol && (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);
}
}
if (nexti >= 0) break;
fullpath += pathto(endpt, newendpt);
endpt = 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 += pathto(endpt, newendpt) + 'Z';
endpt = null;
}
}
// finally add the interior paths
for (i = 0; i < pi.paths.length; i++) {
fullpath += Drawing.smoothclosed(pi.paths[i].map(ab2p), pi.smoothing);
}
return fullpath;
}
/***/ }),
/***/ 33928:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorScaleAttrs = __webpack_require__(49084);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var baseAttrs = __webpack_require__(45464);
var scatterMapboxAttrs = __webpack_require__(31512);
var extendFlat = (__webpack_require__(92880).extendFlat);
/*
* - https://docs.mapbox.com/help/tutorials/make-a-heatmap-with-mapbox-gl-js/
* - https://docs.mapbox.com/mapbox-gl-js/example/heatmap-layer/
* - https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers-heatmap
* - https://blog.mapbox.com/introducing-heatmaps-in-mapbox-gl-js-71355ada9e6c
*
* Gotchas:
* - https://github.com/mapbox/mapbox-gl-js/issues/6463
* - https://github.com/mapbox/mapbox-gl-js/issues/6112
*/
/*
*
* In mathematical terms, Mapbox GL heatmaps are a bivariate (2D) kernel density
* estimation with a Gaussian kernel. It means that each data point has an area
* of “influence” around it (called a kernel) where the numerical value of
* influence (which we call density) decreases as you go further from the point.
* If we sum density values of all points in every pixel of the screen, we get a
* combined density value which we then map to a heatmap color.
*
*/
module.exports = extendFlat({
lon: scatterMapboxAttrs.lon,
lat: scatterMapboxAttrs.lat,
z: {
valType: 'data_array',
editType: 'calc'
},
radius: {
valType: 'number',
editType: 'plot',
arrayOk: true,
min: 1,
dflt: 30
},
below: {
valType: 'string',
editType: 'plot'
},
text: scatterMapboxAttrs.text,
hovertext: scatterMapboxAttrs.hovertext,
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['lon', 'lat', 'z', 'text', 'name']
}),
hovertemplate: hovertemplateAttrs(),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
}, colorScaleAttrs('', {
cLetter: 'z',
editTypeOverride: 'calc'
}));
/***/ }),
/***/ 90876:
/***/ (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 colorscaleCalc = __webpack_require__(47128);
var _ = (__webpack_require__(3400)._);
module.exports = function calc(gd, trace) {
var len = trace._length;
var calcTrace = new Array(len);
var z = trace.z;
var hasZ = isArrayOrTypedArray(z) && z.length;
for (var i = 0; i < len; i++) {
var cdi = calcTrace[i] = {};
var lon = trace.lon[i];
var lat = trace.lat[i];
cdi.lonlat = isNumeric(lon) && isNumeric(lat) ? [+lon, +lat] : [BADNUM, BADNUM];
if (hasZ) {
var zi = z[i];
cdi.z = isNumeric(zi) ? zi : BADNUM;
}
}
colorscaleCalc(gd, trace, {
vals: hasZ ? z : [0, 1],
containerStr: '',
cLetter: 'z'
});
if (len) {
calcTrace[0].t = {
labels: {
lat: _(gd, 'lat:') + ' ',
lon: _(gd, 'lon:') + ' '
}
};
}
return calcTrace;
};
/***/ }),
/***/ 4629:
/***/ (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 Colorscale = __webpack_require__(8932);
var BADNUM = (__webpack_require__(39032).BADNUM);
var makeBlank = (__webpack_require__(44808).makeBlank);
module.exports = function convert(calcTrace) {
var trace = calcTrace[0].trace;
var isVisible = trace.visible === true && trace._length !== 0;
var heatmap = {
layout: {
visibility: 'none'
},
paint: {}
};
var opts = trace._opts = {
heatmap: heatmap,
geojson: makeBlank()
};
// early return if not visible or placeholder
if (!isVisible) return opts;
var features = [];
var i;
var z = trace.z;
var radius = trace.radius;
var hasZ = Lib.isArrayOrTypedArray(z) && z.length;
var hasArrayRadius = Lib.isArrayOrTypedArray(radius);
for (i = 0; i < calcTrace.length; i++) {
var cdi = calcTrace[i];
var lonlat = cdi.lonlat;
if (lonlat[0] !== BADNUM) {
var props = {};
if (hasZ) {
var zi = cdi.z;
props.z = zi !== BADNUM ? zi : 0;
}
if (hasArrayRadius) {
props.r = isNumeric(radius[i]) && radius[i] > 0 ? +radius[i] : 0;
}
features.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: lonlat
},
properties: props
});
}
}
var cOpts = Colorscale.extractOpts(trace);
var scl = cOpts.reversescale ? Colorscale.flipScale(cOpts.colorscale) : cOpts.colorscale;
// Add alpha channel to first colorscale step.
// If not, we would essentially color the entire map.
// See https://docs.mapbox.com/mapbox-gl-js/example/heatmap-layer/
var scl01 = scl[0][1];
var color0 = Color.opacity(scl01) < 1 ? scl01 : Color.addOpacity(scl01, 0);
var heatmapColor = ['interpolate', ['linear'], ['heatmap-density'], 0, color0];
for (i = 1; i < scl.length; i++) {
heatmapColor.push(scl[i][0], scl[i][1]);
}
// Those "weights" have to be in [0, 1], we can do this either:
// - as here using a mapbox-gl expression
// - or, scale the 'z' property in the feature loop
var zExp = ['interpolate', ['linear'], ['get', 'z'], cOpts.min, 0, cOpts.max, 1];
Lib.extendFlat(opts.heatmap.paint, {
'heatmap-weight': hasZ ? zExp : 1 / (cOpts.max - cOpts.min),
'heatmap-color': heatmapColor,
'heatmap-radius': hasArrayRadius ? {
type: 'identity',
property: 'r'
} : trace.radius,
'heatmap-opacity': trace.opacity
});
opts.geojson = {
type: 'FeatureCollection',
features: features
};
opts.heatmap.layout.visibility = 'visible';
return opts;
};
/***/ }),
/***/ 97664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(33928);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var lon = coerce('lon') || [];
var lat = coerce('lat') || [];
var len = Math.min(lon.length, lat.length);
if (!len) {
traceOut.visible = false;
return;
}
traceOut._length = len;
coerce('z');
coerce('radius');
coerce('below');
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'z'
});
};
/***/ }),
/***/ 96176:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt) {
out.lon = pt.lon;
out.lat = pt.lat;
out.z = pt.z;
return out;
};
/***/ }),
/***/ 25336:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var scatterMapboxHoverPoints = (__webpack_require__(63312).hoverPoints);
var getExtraText = (__webpack_require__(63312).getExtraText);
module.exports = function hoverPoints(pointData, xval, yval) {
var pts = scatterMapboxHoverPoints(pointData, xval, yval);
if (!pts) return;
var newPointData = pts[0];
var cd = newPointData.cd;
var trace = cd[0].trace;
var di = cd[newPointData.index];
// let Fx.hover pick the color
delete newPointData.color;
if ('z' in di) {
var ax = newPointData.subplot.mockAxis;
newPointData.z = di.z;
newPointData.zLabel = Axes.tickText(ax, ax.c2l(di.z), 'hover').text;
}
newPointData.extraText = getExtraText(trace, di, cd[0].t.labels);
return [newPointData];
};
/***/ }),
/***/ 15088:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(33928),
supplyDefaults: __webpack_require__(97664),
colorbar: __webpack_require__(96288),
formatLabels: __webpack_require__(11960),
calc: __webpack_require__(90876),
plot: __webpack_require__(35256),
hoverPoints: __webpack_require__(25336),
eventData: __webpack_require__(96176),
getBelow: function (trace, subplot) {
var mapLayers = subplot.getMapLayers();
// find first layer with `type: 'symbol'`,
// that is not a plotly layer
for (var i = 0; i < mapLayers.length; i++) {
var layer = mapLayers[i];
var layerId = layer.id;
if (layer.type === 'symbol' && typeof layerId === 'string' && layerId.indexOf('plotly-') === -1) {
return layerId;
}
}
},
moduleType: 'trace',
name: 'densitymapbox',
basePlotModule: __webpack_require__(33688),
categories: ['mapbox', 'gl', 'showLegend'],
meta: {
hr_name: 'density_mapbox'
}
};
/***/ }),
/***/ 35256:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var convert = __webpack_require__(4629);
var LAYER_PREFIX = (__webpack_require__(47552).traceLayerPrefix);
function DensityMapbox(subplot, uid) {
this.type = 'densitymapbox';
this.subplot = subplot;
this.uid = uid;
this.sourceId = 'source-' + uid;
this.layerList = [['heatmap', LAYER_PREFIX + uid + '-heatmap']];
// previous 'below' value,
// need this to update it properly
this.below = null;
}
var proto = DensityMapbox.prototype;
proto.update = function (calcTrace) {
var subplot = this.subplot;
var layerList = this.layerList;
var optsAll = convert(calcTrace);
var below = subplot.belowLookup['trace-' + this.uid];
subplot.map.getSource(this.sourceId).setData(optsAll.geojson);
if (below !== this.below) {
this._removeLayers();
this._addLayers(optsAll, below);
this.below = below;
}
for (var i = 0; i < layerList.length; i++) {
var item = layerList[i];
var k = item[0];
var id = item[1];
var opts = optsAll[k];
subplot.setOptions(id, 'setLayoutProperty', opts.layout);
if (opts.layout.visibility === 'visible') {
subplot.setOptions(id, 'setPaintProperty', opts.paint);
}
}
};
proto._addLayers = function (optsAll, below) {
var subplot = this.subplot;
var layerList = this.layerList;
var sourceId = this.sourceId;
for (var i = 0; i < layerList.length; i++) {
var item = layerList[i];
var k = item[0];
var opts = optsAll[k];
subplot.addLayer({
type: k,
id: item[1],
source: sourceId,
layout: opts.layout,
paint: opts.paint
}, below);
}
};
proto._removeLayers = function () {
var map = this.subplot.map;
var layerList = this.layerList;
for (var i = layerList.length - 1; i >= 0; i--) {
map.removeLayer(layerList[i][1]);
}
};
proto.dispose = function () {
var map = this.subplot.map;
this._removeLayers();
map.removeSource(this.sourceId);
};
module.exports = function createDensityMapbox(subplot, calcTrace) {
var trace = calcTrace[0].trace;
var densityMapbox = new DensityMapbox(subplot, trace.uid);
var sourceId = densityMapbox.sourceId;
var optsAll = convert(calcTrace);
var below = densityMapbox.below = subplot.belowLookup['trace-' + trace.uid];
subplot.map.addSource(sourceId, {
type: 'geojson',
data: optsAll.geojson
});
densityMapbox._addLayers(optsAll, below);
return densityMapbox;
};
/***/ }),
/***/ 74248:
/***/ (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');
Lib.mergeArray(marker.color, cd, 'mc');
var markerLine = marker.line;
if (markerLine) {
Lib.mergeArray(markerLine.color, cd, 'mlc');
Lib.mergeArrayCastPositive(markerLine.width, cd, 'mlw');
}
}
};
/***/ }),
/***/ 20088:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var barAttrs = __webpack_require__(20832);
var lineAttrs = (__webpack_require__(52904).line);
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 constants = __webpack_require__(74732);
var extendFlat = (__webpack_require__(92880).extendFlat);
var Color = __webpack_require__(76308);
module.exports = {
x: barAttrs.x,
x0: barAttrs.x0,
dx: barAttrs.dx,
y: barAttrs.y,
y0: barAttrs.y0,
dy: barAttrs.dy,
xperiod: barAttrs.xperiod,
yperiod: barAttrs.yperiod,
xperiod0: barAttrs.xperiod0,
yperiod0: barAttrs.yperiod0,
xperiodalignment: barAttrs.xperiodalignment,
yperiodalignment: barAttrs.yperiodalignment,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
hovertext: barAttrs.hovertext,
hovertemplate: hovertemplateAttrs({}, {
keys: constants.eventDataKeys
}),
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['name', 'x', 'y', 'text', 'percent initial', 'percent previous', 'percent total']
}),
textinfo: {
valType: 'flaglist',
flags: ['label', 'text', 'percent initial', 'percent previous', 'percent total', 'value'],
extras: ['none'],
editType: 'plot',
arrayOk: false
},
// TODO: incorporate `label` and `value` in the eventData
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: constants.eventDataKeys.concat(['label', 'value'])
}),
text: barAttrs.text,
textposition: barAttrs.textposition,
insidetextanchor: extendFlat({}, barAttrs.insidetextanchor, {
dflt: 'middle'
}),
textangle: extendFlat({}, barAttrs.textangle, {
dflt: 0
}),
textfont: barAttrs.textfont,
insidetextfont: barAttrs.insidetextfont,
outsidetextfont: barAttrs.outsidetextfont,
constraintext: barAttrs.constraintext,
cliponaxis: barAttrs.cliponaxis,
orientation: extendFlat({}, barAttrs.orientation, {}),
offset: extendFlat({}, barAttrs.offset, {
arrayOk: false
}),
width: extendFlat({}, barAttrs.width, {
arrayOk: false
}),
marker: funnelMarker(),
connector: {
fillcolor: {
valType: 'color',
editType: 'style'
},
line: {
color: extendFlat({}, lineAttrs.color, {
dflt: Color.defaultLine
}),
width: extendFlat({}, lineAttrs.width, {
dflt: 0,
editType: 'plot'
}),
dash: lineAttrs.dash,
editType: 'style'
},
visible: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
editType: 'plot'
},
offsetgroup: barAttrs.offsetgroup,
alignmentgroup: barAttrs.alignmentgroup,
zorder: barAttrs.zorder
};
function funnelMarker() {
var marker = extendFlat({}, barAttrs.marker);
delete marker.pattern;
delete marker.cornerradius;
return marker;
}
/***/ }),
/***/ 23096:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var alignPeriod = __webpack_require__(1220);
var arraysToCalcdata = __webpack_require__(74248);
var calcSelection = __webpack_require__(4500);
var BADNUM = (__webpack_require__(39032).BADNUM);
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, i, cdi;
if (trace.orientation === 'h') {
size = xa.makeCalcdata(trace, 'x');
origPos = ya.makeCalcdata(trace, 'y');
pObj = alignPeriod(trace, ya, 'y', origPos);
hasPeriod = !!trace.yperiodalignment;
pLetter = 'y';
} else {
size = ya.makeCalcdata(trace, 'y');
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);
// Unlike other bar-like traces funnels do not support base attribute.
// bases for funnels are computed internally in a way that
// the mid-point of each bar are located on the axis line.
trace._base = [];
// set position and size
for (i = 0; i < serieslen; i++) {
// treat negative values as bad numbers
if (size[i] < 0) size[i] = BADNUM;
var connectToNext = false;
if (size[i] !== BADNUM) {
if (i + 1 < serieslen && size[i + 1] !== BADNUM) {
connectToNext = true;
}
}
cdi = cd[i] = {
p: pos[i],
s: size[i],
cNext: connectToNext
};
trace._base[i] = -0.5 * cdi.s;
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) {
cdi.id = String(trace.ids[i]);
}
// calculate total values
if (i === 0) cd[0].vTotal = 0;
cd[0].vTotal += fixNum(cdi.s);
// ratio from initial value
cdi.begR = fixNum(cdi.s) / fixNum(cd[0].s);
}
var prevGoodNum;
for (i = 0; i < serieslen; i++) {
cdi = cd[i];
if (cdi.s === BADNUM) continue;
// ratio of total value
cdi.sumR = cdi.s / cd[0].vTotal;
// ratio of previous (good) value
cdi.difR = prevGoodNum !== undefined ? cdi.s / prevGoodNum : 1;
prevGoodNum = cdi.s;
}
arraysToCalcdata(cd, trace);
calcSelection(cd, trace);
return cd;
};
function fixNum(a) {
return a === BADNUM ? 0 : a;
}
/***/ }),
/***/ 74732:
/***/ (function(module) {
"use strict";
module.exports = {
eventDataKeys: ['percentInitial', 'percentPrevious', 'percentTotal']
};
/***/ }),
/***/ 4804:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var setGroupPositions = (__webpack_require__(96376).setGroupPositions);
module.exports = function crossTraceCalc(gd, plotinfo) {
var fullLayout = gd._fullLayout;
var fullData = gd._fullData;
var calcdata = gd.calcdata;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var funnels = [];
var funnelsVert = [];
var funnelsHorz = [];
var cd, i;
for (i = 0; i < fullData.length; i++) {
var fullTrace = fullData[i];
var isHorizontal = fullTrace.orientation === 'h';
if (fullTrace.visible === true && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id && fullTrace.type === 'funnel') {
cd = calcdata[i];
if (isHorizontal) {
funnelsHorz.push(cd);
} else {
funnelsVert.push(cd);
}
funnels.push(cd);
}
}
var opts = {
mode: fullLayout.funnelmode,
norm: fullLayout.funnelnorm,
gap: fullLayout.funnelgap,
groupgap: fullLayout.funnelgroupgap
};
setGroupPositions(gd, xa, ya, funnelsVert, opts);
setGroupPositions(gd, ya, xa, funnelsHorz, opts);
for (i = 0; i < funnels.length; i++) {
cd = funnels[i];
for (var j = 0; j < cd.length; j++) {
if (j + 1 < cd.length) {
cd[j].nextP0 = cd[j + 1].p0;
cd[j].nextS0 = cd[j + 1].s0;
cd[j].nextP1 = cd[j + 1].p1;
cd[j].nextS1 = cd[j + 1].s1;
}
}
}
};
/***/ }),
/***/ 45432:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleGroupingDefaults = __webpack_require__(20011);
var handleText = (__webpack_require__(31508).handleText);
var handleXYDefaults = __webpack_require__(43980);
var handlePeriodDefaults = __webpack_require__(31147);
var attributes = __webpack_require__(20088);
var Color = __webpack_require__(76308);
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('orientation', traceOut.y && !traceOut.x ? 'v' : 'h');
coerce('offset');
coerce('width');
var text = coerce('text');
coerce('hovertext');
coerce('hovertemplate');
var textposition = coerce('textposition');
handleText(traceIn, traceOut, layout, coerce, textposition, {
moduleHasSelected: false,
moduleHasUnselected: false,
moduleHasConstrain: true,
moduleHasCliponaxis: true,
moduleHasTextangle: true,
moduleHasInsideanchor: true
});
if (traceOut.textposition !== 'none' && !traceOut.texttemplate) {
coerce('textinfo', Lib.isArrayOrTypedArray(text) ? 'text+value' : 'value');
}
var markerColor = coerce('marker.color', defaultColor);
coerce('marker.line.color', Color.defaultLine);
coerce('marker.line.width');
var connectorVisible = coerce('connector.visible');
if (connectorVisible) {
coerce('connector.fillcolor', defaultFillColor(markerColor));
var connectorLineWidth = coerce('connector.line.width');
if (connectorLineWidth) {
coerce('connector.line.color');
coerce('connector.line.dash');
}
}
coerce('zorder');
}
function defaultFillColor(markerColor) {
var cBase = Lib.isArrayOrTypedArray(markerColor) ? '#000' : markerColor;
return Color.addOpacity(cBase, 0.5 * Color.opacity(cBase));
}
function crossTraceDefaults(fullData, fullLayout) {
var traceIn, traceOut;
function coerce(attr) {
return Lib.coerce(traceOut._input, traceOut, attributes, attr);
}
if (fullLayout.funnelmode === 'group') {
for (var i = 0; i < fullData.length; i++) {
traceOut = fullData[i];
traceIn = traceOut._input;
handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce);
}
}
}
module.exports = {
supplyDefaults: supplyDefaults,
crossTraceDefaults: crossTraceDefaults
};
/***/ }),
/***/ 34580:
/***/ (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 funnel
if ('percentInitial' in pt) out.percentInitial = pt.percentInitial;
if ('percentPrevious' in pt) out.percentPrevious = pt.percentPrevious;
if ('percentTotal' in pt) out.percentTotal = pt.percentTotal;
if (pt.xa) out.xaxis = pt.xa;
if (pt.ya) out.yaxis = pt.ya;
return out;
};
/***/ }),
/***/ 31488:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var opacity = (__webpack_require__(76308).opacity);
var hoverOnBars = (__webpack_require__(63400).hoverOnBars);
var formatPercent = (__webpack_require__(3400).formatPercent);
module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
var point = hoverOnBars(pointData, xval, yval, hovermode, opts);
if (!point) return;
var cd = point.cd;
var trace = cd[0].trace;
var isHorizontal = trace.orientation === 'h';
// the closest data point
var index = point.index;
var di = cd[index];
var sizeLetter = isHorizontal ? 'x' : 'y';
point[sizeLetter + 'LabelVal'] = di.s;
point.percentInitial = di.begR;
point.percentInitialLabel = formatPercent(di.begR, 1);
point.percentPrevious = di.difR;
point.percentPreviousLabel = formatPercent(di.difR, 1);
point.percentTotal = di.sumR;
point.percentTotalLabel = formatPercent(di.sumR, 1);
var hoverinfo = di.hi || trace.hoverinfo;
var text = [];
if (hoverinfo && hoverinfo !== 'none' && hoverinfo !== 'skip') {
var isAll = hoverinfo === 'all';
var parts = hoverinfo.split('+');
var hasFlag = function (flag) {
return isAll || parts.indexOf(flag) !== -1;
};
if (hasFlag('percent initial')) {
text.push(point.percentInitialLabel + ' of initial');
}
if (hasFlag('percent previous')) {
text.push(point.percentPreviousLabel + ' of previous');
}
if (hasFlag('percent total')) {
text.push(point.percentTotalLabel + ' of total');
}
}
point.extraText = text.join('
');
point.color = getTraceColor(trace, di);
return [point];
};
function getTraceColor(trace, di) {
var cont = trace.marker;
var mc = di.mc || cont.color;
var mlc = di.mlc || cont.line.color;
var mlw = di.mlw || cont.line.width;
if (opacity(mc)) return mc;else if (opacity(mlc) && mlw) return mlc;
}
/***/ }),
/***/ 94704:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(20088),
layoutAttributes: __webpack_require__(7076),
supplyDefaults: (__webpack_require__(45432).supplyDefaults),
crossTraceDefaults: (__webpack_require__(45432).crossTraceDefaults),
supplyLayoutDefaults: __webpack_require__(11631),
calc: __webpack_require__(23096),
crossTraceCalc: __webpack_require__(4804),
plot: __webpack_require__(42200),
style: (__webpack_require__(44544).style),
hoverPoints: __webpack_require__(31488),
eventData: __webpack_require__(34580),
selectPoints: __webpack_require__(45784),
moduleType: 'trace',
name: 'funnel',
basePlotModule: __webpack_require__(57952),
categories: ['bar-like', 'cartesian', 'svg', 'oriented', 'showLegend', 'zoomScale'],
meta: {}
};
/***/ }),
/***/ 7076:
/***/ (function(module) {
"use strict";
module.exports = {
funnelmode: {
valType: 'enumerated',
values: ['stack', 'group', 'overlay'],
dflt: 'stack',
editType: 'calc'
},
funnelgap: {
valType: 'number',
min: 0,
max: 1,
editType: 'calc'
},
funnelgroupgap: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
editType: 'calc'
}
};
/***/ }),
/***/ 11631:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(7076);
module.exports = function (layoutIn, layoutOut, fullData) {
var hasTraceType = false;
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
for (var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (trace.visible && trace.type === 'funnel') {
hasTraceType = true;
break;
}
}
if (hasTraceType) {
coerce('funnelmode');
coerce('funnelgap', 0.2);
coerce('funnelgroupgap');
}
};
/***/ }),
/***/ 42200:
/***/ (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 BADNUM = (__webpack_require__(39032).BADNUM);
var barPlot = __webpack_require__(98184);
var clearMinTextSize = (__webpack_require__(82744).clearMinTextSize);
module.exports = function plot(gd, plotinfo, cdModule, traceLayer) {
var fullLayout = gd._fullLayout;
clearMinTextSize('funnel', fullLayout);
plotConnectorRegions(gd, plotinfo, cdModule, traceLayer);
plotConnectorLines(gd, plotinfo, cdModule, traceLayer);
barPlot.plot(gd, plotinfo, cdModule, traceLayer, {
mode: fullLayout.funnelmode,
norm: fullLayout.funnelmode,
gap: fullLayout.funnelgap,
groupgap: fullLayout.funnelgroupgap
});
};
function plotConnectorRegions(gd, plotinfo, cdModule, traceLayer) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
Lib.makeTraceGroups(traceLayer, cdModule, 'trace bars').each(function (cd) {
var plotGroup = d3.select(this);
var trace = cd[0].trace;
var group = Lib.ensureSingle(plotGroup, 'g', 'regions');
if (!trace.connector || !trace.connector.visible) {
group.remove();
return;
}
var isHorizontal = trace.orientation === 'h';
var connectors = group.selectAll('g.region').data(Lib.identity);
connectors.enter().append('g').classed('region', true);
connectors.exit().remove();
var len = connectors.size();
connectors.each(function (di, i) {
// don't draw lines between nulls
if (i !== len - 1 && !di.cNext) return;
var xy = getXY(di, xa, ya, isHorizontal);
var x = xy[0];
var y = xy[1];
var shape = '';
if (x[0] !== BADNUM && y[0] !== BADNUM && x[1] !== BADNUM && y[1] !== BADNUM && x[2] !== BADNUM && y[2] !== BADNUM && x[3] !== BADNUM && y[3] !== BADNUM) {
if (isHorizontal) {
shape += 'M' + x[0] + ',' + y[1] + 'L' + x[2] + ',' + y[2] + 'H' + x[3] + 'L' + x[1] + ',' + y[1] + 'Z';
} else {
shape += 'M' + x[1] + ',' + y[1] + 'L' + x[2] + ',' + y[3] + 'V' + y[2] + 'L' + x[1] + ',' + y[0] + 'Z';
}
}
if (shape === '') shape = 'M0,0Z';
Lib.ensureSingle(d3.select(this), 'path').attr('d', shape).call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
});
});
}
function plotConnectorLines(gd, plotinfo, cdModule, traceLayer) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
Lib.makeTraceGroups(traceLayer, cdModule, 'trace bars').each(function (cd) {
var plotGroup = d3.select(this);
var trace = cd[0].trace;
var group = Lib.ensureSingle(plotGroup, 'g', 'lines');
if (!trace.connector || !trace.connector.visible || !trace.connector.line.width) {
group.remove();
return;
}
var isHorizontal = trace.orientation === 'h';
var connectors = group.selectAll('g.line').data(Lib.identity);
connectors.enter().append('g').classed('line', true);
connectors.exit().remove();
var len = connectors.size();
connectors.each(function (di, i) {
// don't draw lines between nulls
if (i !== len - 1 && !di.cNext) return;
var xy = getXY(di, xa, ya, isHorizontal);
var x = xy[0];
var y = xy[1];
var shape = '';
if (x[3] !== undefined && y[3] !== undefined) {
if (isHorizontal) {
shape += 'M' + x[0] + ',' + y[1] + 'L' + x[2] + ',' + y[2];
shape += 'M' + x[1] + ',' + y[1] + 'L' + x[3] + ',' + y[2];
} else {
shape += 'M' + x[1] + ',' + y[1] + 'L' + x[2] + ',' + y[3];
shape += 'M' + x[1] + ',' + y[0] + 'L' + x[2] + ',' + y[2];
}
}
if (shape === '') shape = 'M0,0Z';
Lib.ensureSingle(d3.select(this), 'path').attr('d', shape).call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
});
});
}
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);
s[2] = sAxis.c2p(di.nextS0, true);
p[2] = pAxis.c2p(di.nextP0, true);
s[3] = sAxis.c2p(di.nextS1, true);
p[3] = pAxis.c2p(di.nextP1, true);
return isHorizontal ? [s, p] : [p, s];
}
/***/ }),
/***/ 44544:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var DESELECTDIM = (__webpack_require__(13448).DESELECTDIM);
var barStyle = __webpack_require__(60100);
var resizeText = (__webpack_require__(82744).resizeText);
var styleTextPoints = barStyle.styleTextPoints;
function style(gd, cd, sel) {
var s = sel ? sel : d3.select(gd).selectAll('g[class^="funnellayer"]').selectAll('g.trace');
resizeText(gd, s, 'funnel');
s.style('opacity', function (d) {
return d[0].trace.opacity;
});
s.each(function (d) {
var gTrace = d3.select(this);
var trace = d[0].trace;
gTrace.selectAll('.point > path').each(function (di) {
if (!di.isBlank) {
var cont = trace.marker;
d3.select(this).call(Color.fill, di.mc || cont.color).call(Color.stroke, di.mlc || cont.line.color).call(Drawing.dashLine, cont.line.dash, di.mlw || cont.line.width).style('opacity', trace.selectedpoints && !di.selected ? DESELECTDIM : 1);
}
});
styleTextPoints(gTrace, trace, gd);
gTrace.selectAll('.regions').each(function () {
d3.select(this).selectAll('path').style('stroke-width', 0).call(Color.fill, trace.connector.fillcolor);
});
gTrace.selectAll('.lines').each(function () {
var cont = trace.connector.line;
Drawing.lineGroupStyle(d3.select(this).selectAll('path'), cont.width, cont.color, cont.dash);
});
});
}
module.exports = {
style: style
};
/***/ }),
/***/ 22332:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var pieAttrs = __webpack_require__(74996);
var baseAttrs = __webpack_require__(45464);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = {
labels: pieAttrs.labels,
// equivalent of x0 and dx, if label is missing
label0: pieAttrs.label0,
dlabel: pieAttrs.dlabel,
values: pieAttrs.values,
marker: {
colors: pieAttrs.marker.colors,
line: {
color: extendFlat({}, pieAttrs.marker.line.color, {
dflt: null
}),
width: extendFlat({}, pieAttrs.marker.line.width, {
dflt: 1
}),
editType: 'calc'
},
pattern: pieAttrs.marker.pattern,
editType: 'calc'
},
text: pieAttrs.text,
hovertext: pieAttrs.hovertext,
scalegroup: extendFlat({}, pieAttrs.scalegroup, {}),
textinfo: extendFlat({}, pieAttrs.textinfo, {
flags: ['label', 'text', 'value', 'percent']
}),
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['label', 'color', 'value', 'text', 'percent']
}),
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['label', 'text', 'value', 'percent', 'name']
}),
hovertemplate: hovertemplateAttrs({}, {
keys: ['label', 'color', 'value', 'text', 'percent']
}),
textposition: extendFlat({}, pieAttrs.textposition, {
values: ['inside', 'none'],
dflt: 'inside'
}),
textfont: pieAttrs.textfont,
insidetextfont: pieAttrs.insidetextfont,
title: {
text: pieAttrs.title.text,
font: pieAttrs.title.font,
position: extendFlat({}, pieAttrs.title.position, {
values: ['top left', 'top center', 'top right'],
dflt: 'top center'
}),
editType: 'plot'
},
domain: domainAttrs({
name: 'funnelarea',
trace: true,
editType: 'calc'
}),
aspectratio: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'plot'
},
baseratio: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.333,
editType: 'plot'
}
};
/***/ }),
/***/ 91248:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var plots = __webpack_require__(7316);
exports.name = 'funnelarea';
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);
};
/***/ }),
/***/ 54000:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var pieCalc = __webpack_require__(45768);
function calc(gd, trace) {
return pieCalc.calc(gd, trace);
}
function crossTraceCalc(gd) {
pieCalc.crossTraceCalc(gd, {
type: 'funnelarea'
});
}
module.exports = {
calc: calc,
crossTraceCalc: crossTraceCalc
};
/***/ }),
/***/ 92688:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(22332);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var handleText = (__webpack_require__(31508).handleText);
var handleLabelsAndValues = (__webpack_require__(74174).handleLabelsAndValues);
var handleMarkerDefaults = (__webpack_require__(74174).handleMarkerDefaults);
module.exports = 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);
coerce('scalegroup');
var textData = coerce('text');
var textTemplate = coerce('texttemplate');
var textInfo;
if (!textTemplate) textInfo = coerce('textinfo', Array.isArray(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
});
} else if (textInfo === 'none') {
coerce('textposition', 'none');
}
handleDomainDefaults(traceOut, layout, coerce);
var title = coerce('title.text');
if (title) {
coerce('title.position');
Lib.coerceFont(coerce, 'title.font', layout.font);
}
coerce('aspectratio');
coerce('baseratio');
};
/***/ }),
/***/ 62396:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'funnelarea',
basePlotModule: __webpack_require__(91248),
categories: ['pie-like', 'funnelarea', 'showLegend'],
attributes: __webpack_require__(22332),
layoutAttributes: __webpack_require__(61280),
supplyDefaults: __webpack_require__(92688),
supplyLayoutDefaults: __webpack_require__(35384),
calc: (__webpack_require__(54000).calc),
crossTraceCalc: (__webpack_require__(54000).crossTraceCalc),
plot: __webpack_require__(39472),
style: __webpack_require__(62096),
styleOne: __webpack_require__(10528),
meta: {}
};
/***/ }),
/***/ 61280:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hiddenlabels = (__webpack_require__(85204).hiddenlabels);
module.exports = {
hiddenlabels: hiddenlabels,
funnelareacolorway: {
valType: 'colorlist',
editType: 'calc'
},
extendfunnelareacolors: {
valType: 'boolean',
dflt: true,
editType: 'calc'
}
};
/***/ }),
/***/ 35384:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(61280);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
coerce('hiddenlabels');
coerce('funnelareacolorway', layoutOut.colorway);
coerce('extendfunnelareacolors');
};
/***/ }),
/***/ 39472:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var strScale = Lib.strScale;
var strTranslate = Lib.strTranslate;
var svgTextUtils = __webpack_require__(72736);
var barPlot = __webpack_require__(98184);
var toMoveInsideBar = barPlot.toMoveInsideBar;
var uniformText = __webpack_require__(82744);
var recordMinTextSize = uniformText.recordMinTextSize;
var clearMinTextSize = uniformText.clearMinTextSize;
var pieHelpers = __webpack_require__(69656);
var piePlot = __webpack_require__(37820);
var attachFxHandlers = piePlot.attachFxHandlers;
var determineInsideTextFont = piePlot.determineInsideTextFont;
var layoutAreas = piePlot.layoutAreas;
var prerenderTitles = piePlot.prerenderTitles;
var positionTitleOutside = piePlot.positionTitleOutside;
var formatSliceLabel = piePlot.formatSliceLabel;
module.exports = function plot(gd, cdModule) {
var isStatic = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
clearMinTextSize('funnelarea', fullLayout);
prerenderTitles(cdModule, gd);
layoutAreas(cdModule, fullLayout._size);
Lib.makeTraceGroups(fullLayout._funnelarealayer, cdModule, 'trace').each(function (cd) {
var plotGroup = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
setCoords(cd);
plotGroup.each(function () {
var slices = d3.select(this).selectAll('g.slice').data(cd);
slices.enter().append('g').classed('slice', true);
slices.exit().remove();
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;
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);
var shape = 'M' + (cx + pt.TR[0]) + ',' + (cy + pt.TR[1]) + line(pt.TR, pt.BR) + line(pt.BR, pt.BL) + line(pt.BL, pt.TL) + 'Z';
slicePath.attr('d', shape);
// add text
formatSliceLabel(gd, pt, cd0);
var textPosition = pieHelpers.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, 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;
var x0, x1;
var y0 = Math.min(pt.BL[1], pt.BR[1]) + cy;
var y1 = Math.max(pt.TL[1], pt.TR[1]) + cy;
x0 = Math.max(pt.TL[0], pt.BL[0]) + cx;
x1 = Math.min(pt.TR[0], pt.BR[0]) + cx;
transform = toMoveInsideBar(x0, x1, y0, y1, textBB, {
isHorizontal: true,
constrained: true,
angle: 0,
anchor: 'middle'
});
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 = positionTitleOutside(cd0, fullLayout._size);
titleText.attr('transform', strTranslate(transform.x, transform.y) + strScale(Math.min(1, transform.scale)) + strTranslate(transform.tx, transform.ty));
});
});
});
};
function line(a, b) {
var dx = b[0] - a[0];
var dy = b[1] - a[1];
return 'l' + dx + ',' + dy;
}
function getBetween(a, b) {
return [0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1])];
}
function setCoords(cd) {
if (!cd.length) return;
var cd0 = cd[0];
var trace = cd0.trace;
var aspectratio = trace.aspectratio;
var h = trace.baseratio;
if (h > 0.999) h = 0.999; // TODO: may handle this case separately
var h2 = Math.pow(h, 2);
var v1 = cd0.vTotal;
var v0 = v1 * h2 / (1 - h2);
var totalValues = v1;
var sumSteps = v0 / v1;
function calcPos() {
var q = Math.sqrt(sumSteps);
return {
x: q,
y: -q
};
}
function getPoint() {
var pos = calcPos();
return [pos.x, pos.y];
}
var p;
var allPoints = [];
allPoints.push(getPoint());
var i, cdi;
for (i = cd.length - 1; i > -1; i--) {
cdi = cd[i];
if (cdi.hidden) continue;
var step = cdi.v / totalValues;
sumSteps += step;
allPoints.push(getPoint());
}
var minY = Infinity;
var maxY = -Infinity;
for (i = 0; i < allPoints.length; i++) {
p = allPoints[i];
minY = Math.min(minY, p[1]);
maxY = Math.max(maxY, p[1]);
}
// center the shape
for (i = 0; i < allPoints.length; i++) {
allPoints[i][1] -= (maxY + minY) / 2;
}
var lastX = allPoints[allPoints.length - 1][0];
// get pie r
var r = cd0.r;
var rY = (maxY - minY) / 2;
var scaleX = r / lastX;
var scaleY = r / rY * aspectratio;
// set funnelarea r
cd0.r = scaleY * rY;
// scale the shape
for (i = 0; i < allPoints.length; i++) {
allPoints[i][0] *= scaleX;
allPoints[i][1] *= scaleY;
}
// record first position
p = allPoints[0];
var prevLeft = [-p[0], p[1]];
var prevRight = [p[0], p[1]];
var n = 0; // note we skip the very first point.
for (i = cd.length - 1; i > -1; i--) {
cdi = cd[i];
if (cdi.hidden) continue;
n += 1;
var x = allPoints[n][0];
var y = allPoints[n][1];
cdi.TL = [-x, y];
cdi.TR = [x, y];
cdi.BL = prevLeft;
cdi.BR = prevRight;
cdi.pxmid = getBetween(cdi.TR, cdi.BR);
prevLeft = cdi.TL;
prevRight = cdi.TR;
}
}
/***/ }),
/***/ 62096:
/***/ (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._funnelarealayer.selectAll('.trace');
resizeText(gd, s, 'funnelarea');
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);
});
});
};
/***/ }),
/***/ 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 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, {
family: font.family,
size: fontSize,
color: fontColor,
weight: font.weight,
style: font.style,
variant: font.variant,
textcase: font.textcase,
lineposition: font.lineposition,
shadow: font.shadow
}).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;
}
/***/ }),
/***/ 74512:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var heatmapAttrs = __webpack_require__(83328);
var colorScaleAttrs = __webpack_require__(49084);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var commonList = ['z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'transpose', 'xtype', 'ytype'];
var attrs = {};
for (var i = 0; i < commonList.length; i++) {
var k = commonList[i];
attrs[k] = heatmapAttrs[k];
}
attrs.zsmooth = {
valType: 'enumerated',
values: ['fast', false],
dflt: 'fast',
editType: 'calc'
};
extendFlat(attrs, colorScaleAttrs('', {
cLetter: 'z',
autoColorDflt: false
}));
module.exports = overrideAll(attrs, 'calc', 'nested');
/***/ }),
/***/ 84656:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createHeatmap2D = (__webpack_require__(67792).gl_heatmap2d);
var Axes = __webpack_require__(54460);
var str2RGBArray = __webpack_require__(43080);
function Heatmap(scene, uid) {
this.scene = scene;
this.uid = uid;
this.type = 'heatmapgl';
this.name = '';
this.hoverinfo = 'all';
this.xData = [];
this.yData = [];
this.zData = [];
this.textLabels = [];
this.idToIndex = [];
this.bounds = [0, 0, 0, 0];
this.options = {
zsmooth: 'fast',
z: [],
x: [],
y: [],
shape: [0, 0],
colorLevels: [0],
colorValues: [0, 0, 0, 1]
};
this.heatmap = createHeatmap2D(scene.glplot, this.options);
this.heatmap._trace = this;
}
var proto = Heatmap.prototype;
proto.handlePick = function (pickResult) {
var options = this.options;
var shape = options.shape;
var index = pickResult.pointId;
var xIndex = index % shape[0];
var yIndex = Math.floor(index / shape[0]);
var zIndex = index;
return {
trace: this,
dataCoord: pickResult.dataCoord,
traceCoord: [options.x[xIndex], options.y[yIndex], options.z[zIndex]],
textLabel: this.textLabels[index],
name: this.name,
pointIndex: [yIndex, xIndex],
hoverinfo: this.hoverinfo
};
};
proto.update = function (fullTrace, calcTrace) {
var calcPt = calcTrace[0];
this.index = fullTrace.index;
this.name = fullTrace.name;
this.hoverinfo = fullTrace.hoverinfo;
// convert z from 2D -> 1D
var z = calcPt.z;
this.options.z = [].concat.apply([], z);
var rowLen = z[0].length;
var colLen = z.length;
this.options.shape = [rowLen, colLen];
this.options.x = calcPt.x;
this.options.y = calcPt.y;
this.options.zsmooth = fullTrace.zsmooth;
var colorOptions = convertColorscale(fullTrace);
this.options.colorLevels = colorOptions.colorLevels;
this.options.colorValues = colorOptions.colorValues;
// convert text from 2D -> 1D
this.textLabels = [].concat.apply([], fullTrace.text);
this.heatmap.update(this.options);
var xa = this.scene.xaxis;
var ya = this.scene.yaxis;
var xOpts, yOpts;
if (fullTrace.zsmooth === false) {
// increase padding for discretised heatmap as suggested by Louise Ord
xOpts = {
ppad: calcPt.x[1] - calcPt.x[0]
};
yOpts = {
ppad: calcPt.y[1] - calcPt.y[0]
};
}
fullTrace._extremes[xa._id] = Axes.findExtremes(xa, calcPt.x, xOpts);
fullTrace._extremes[ya._id] = Axes.findExtremes(ya, calcPt.y, yOpts);
};
proto.dispose = function () {
this.heatmap.dispose();
};
function convertColorscale(fullTrace) {
var scl = fullTrace.colorscale;
var zmin = fullTrace.zmin;
var zmax = fullTrace.zmax;
var N = scl.length;
var domain = new Array(N);
var range = new Array(4 * N);
for (var i = 0; i < N; i++) {
var si = scl[i];
var color = str2RGBArray(si[1]);
domain[i] = zmin + si[0] * (zmax - zmin);
for (var j = 0; j < 4; j++) {
range[4 * i + j] = color[j];
}
}
return {
colorLevels: domain,
colorValues: range
};
}
function createHeatmap(scene, fullTrace, calcTrace) {
var plot = new Heatmap(scene, fullTrace.uid);
plot.update(fullTrace, calcTrace);
return plot;
}
module.exports = createHeatmap;
/***/ }),
/***/ 86464:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleXYZDefaults = __webpack_require__(51264);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(74512);
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;
}
coerce('text');
coerce('zsmooth');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'z'
});
};
/***/ }),
/***/ 45536:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var deprecationWarning = ['*heatmapgl* trace is deprecated!', 'Please consider switching to the *heatmap* or *image* trace types.', 'Alternatively you could contribute/sponsor rewriting this trace type', 'based on cartesian features and using regl framework.'].join(' ');
module.exports = {
attributes: __webpack_require__(74512),
supplyDefaults: __webpack_require__(86464),
colorbar: __webpack_require__(96288),
calc: __webpack_require__(19512),
plot: __webpack_require__(84656),
moduleType: 'trace',
name: 'heatmapgl',
basePlotModule: __webpack_require__(39952),
categories: ['gl', 'gl2d', '2dMap'],
meta: {}
};
/***/ }),
/***/ 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: {}
};
/***/ }),
/***/ 97376:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var colorScaleAttrs = __webpack_require__(49084);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var pieAttrs = __webpack_require__(74996);
var sunburstAttrs = __webpack_require__(424);
var treemapAttrs = __webpack_require__(40516);
var constants = __webpack_require__(32984);
var extendFlat = (__webpack_require__(92880).extendFlat);
var pattern = (__webpack_require__(98192)/* .pattern */ .c);
module.exports = {
labels: sunburstAttrs.labels,
parents: sunburstAttrs.parents,
values: sunburstAttrs.values,
branchvalues: sunburstAttrs.branchvalues,
count: sunburstAttrs.count,
level: sunburstAttrs.level,
maxdepth: sunburstAttrs.maxdepth,
tiling: {
orientation: {
valType: 'enumerated',
values: ['v', 'h'],
dflt: 'h',
editType: 'plot'
},
flip: treemapAttrs.tiling.flip,
pad: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'plot'
},
editType: 'calc'
},
marker: extendFlat({
colors: sunburstAttrs.marker.colors,
line: sunburstAttrs.marker.line,
pattern: pattern,
editType: 'calc'
}, colorScaleAttrs('marker', {
colorAttr: 'colors',
anim: false // TODO: set to anim: true?
})),
leaf: sunburstAttrs.leaf,
pathbar: treemapAttrs.pathbar,
text: pieAttrs.text,
textinfo: sunburstAttrs.textinfo,
// TODO: incorporate `label` and `value` in the eventData
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: constants.eventDataKeys.concat(['label', 'value'])
}),
hovertext: pieAttrs.hovertext,
hoverinfo: sunburstAttrs.hoverinfo,
hovertemplate: hovertemplateAttrs({}, {
keys: constants.eventDataKeys
}),
textfont: pieAttrs.textfont,
insidetextfont: pieAttrs.insidetextfont,
outsidetextfont: treemapAttrs.outsidetextfont,
textposition: treemapAttrs.textposition,
sort: pieAttrs.sort,
root: sunburstAttrs.root,
domain: domainAttrs({
name: 'icicle',
trace: true,
editType: 'calc'
})
};
/***/ }),
/***/ 59564:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var plots = __webpack_require__(7316);
exports.name = 'icicle';
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);
};
/***/ }),
/***/ 73876:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var calc = __webpack_require__(3776);
exports.r = function (gd, trace) {
return calc.calc(gd, trace);
};
exports.q = function (gd) {
return calc._runCrossTraceCalc('icicle', gd);
};
/***/ }),
/***/ 7045:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(97376);
var Color = __webpack_require__(76308);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var handleText = (__webpack_require__(31508).handleText);
var TEXTPAD = (__webpack_require__(78048).TEXTPAD);
var handleMarkerDefaults = (__webpack_require__(74174).handleMarkerDefaults);
var Colorscale = __webpack_require__(8932);
var hasColorscale = Colorscale.hasColorscale;
var colorscaleDefaults = Colorscale.handleDefaults;
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var labels = coerce('labels');
var parents = coerce('parents');
if (!labels || !labels.length || !parents || !parents.length) {
traceOut.visible = false;
return;
}
var vals = coerce('values');
if (vals && vals.length) {
coerce('branchvalues');
} else {
coerce('count');
}
coerce('level');
coerce('maxdepth');
coerce('tiling.orientation');
coerce('tiling.flip');
coerce('tiling.pad');
var text = coerce('text');
coerce('texttemplate');
if (!traceOut.texttemplate) coerce('textinfo', Lib.isArrayOrTypedArray(text) ? 'text+label' : 'label');
coerce('hovertext');
coerce('hovertemplate');
var hasPathbar = coerce('pathbar.visible');
var textposition = 'auto';
handleText(traceIn, traceOut, layout, coerce, textposition, {
hasPathbar: hasPathbar,
moduleHasSelected: false,
moduleHasUnselected: false,
moduleHasConstrain: false,
moduleHasCliponaxis: false,
moduleHasTextangle: false,
moduleHasInsideanchor: false
});
coerce('textposition');
handleMarkerDefaults(traceIn, traceOut, layout, coerce);
var withColorscale = traceOut._hasColorscale = hasColorscale(traceIn, 'marker', 'colors') || (traceIn.marker || {}).coloraxis // N.B. special logic to consider "values" colorscales
;
if (withColorscale) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'marker.',
cLetter: 'c'
});
}
coerce('leaf.opacity', withColorscale ? 1 : 0.7);
traceOut._hovered = {
marker: {
line: {
width: 2,
color: Color.contrast(layout.paper_bgcolor)
}
}
};
if (hasPathbar) {
// This works even for multi-line labels as icicle pathbar trim out line breaks
coerce('pathbar.thickness', traceOut.pathbar.textfont.size + 2 * TEXTPAD);
coerce('pathbar.side');
coerce('pathbar.edgeshape');
}
coerce('sort');
coerce('root.color');
handleDomainDefaults(traceOut, layout, coerce);
// do not support transforms for now
traceOut._length = null;
};
/***/ }),
/***/ 67880:
/***/ (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 svgTextUtils = __webpack_require__(72736);
var partition = __webpack_require__(25132);
var styleOne = (__webpack_require__(47192).styleOne);
var constants = __webpack_require__(32984);
var helpers = __webpack_require__(78176);
var attachFxHandlers = __webpack_require__(45716);
var formatSliceLabel = (__webpack_require__(96488).formatSliceLabel);
var onPathbar = false; // for Descendants
module.exports = function drawDescendants(gd, cd, entry, slices, opts) {
var width = opts.width;
var height = opts.height;
var viewX = opts.viewX;
var viewY = opts.viewY;
var pathSlice = opts.pathSlice;
var toMoveInsideSlice = opts.toMoveInsideSlice;
var strTransform = opts.strTransform;
var hasTransition = opts.hasTransition;
var handleSlicesExit = opts.handleSlicesExit;
var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator;
var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator;
var prevEntry = opts.prevEntry;
var refRect = {};
var isStatic = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
var cd0 = cd[0];
var trace = cd0.trace;
var hasLeft = trace.textposition.indexOf('left') !== -1;
var hasRight = trace.textposition.indexOf('right') !== -1;
var hasBottom = trace.textposition.indexOf('bottom') !== -1;
// N.B. slice data isn't the calcdata,
// grab corresponding calcdata item in sliceData[i].data.data
var allData = partition(entry, [width, height], {
flipX: trace.tiling.flip.indexOf('x') > -1,
flipY: trace.tiling.flip.indexOf('y') > -1,
orientation: trace.tiling.orientation,
pad: {
inner: trace.tiling.pad
},
maxDepth: trace._maxDepth
});
var sliceData = allData.descendants();
var minVisibleDepth = Infinity;
var maxVisibleDepth = -Infinity;
sliceData.forEach(function (pt) {
var depth = pt.depth;
if (depth >= trace._maxDepth) {
// hide slices that won't show up on graph
pt.x0 = pt.x1 = (pt.x0 + pt.x1) / 2;
pt.y0 = pt.y1 = (pt.y0 + pt.y1) / 2;
} else {
minVisibleDepth = Math.min(minVisibleDepth, depth);
maxVisibleDepth = Math.max(maxVisibleDepth, depth);
}
});
slices = slices.data(sliceData, helpers.getPtId);
trace._maxVisibleLayers = isFinite(maxVisibleDepth) ? maxVisibleDepth - minVisibleDepth + 1 : 0;
slices.enter().append('g').classed('slice', true);
handleSlicesExit(slices, onPathbar, refRect, [width, height], pathSlice);
slices.order();
// next coords of previous entry
var nextOfPrevEntry = null;
if (hasTransition && prevEntry) {
var prevEntryId = helpers.getPtId(prevEntry);
slices.each(function (pt) {
if (nextOfPrevEntry === null && helpers.getPtId(pt) === prevEntryId) {
nextOfPrevEntry = {
x0: pt.x0,
x1: pt.x1,
y0: pt.y0,
y1: pt.y1
};
}
});
}
var getRefRect = function () {
return nextOfPrevEntry || {
x0: 0,
x1: width,
y0: 0,
y1: height
};
};
var updateSlices = slices;
if (hasTransition) {
updateSlices = updateSlices.transition().each('end', function () {
// N.B. gd._transitioning is (still) *true* by the time
// transition updates get here
var sliceTop = d3.select(this);
helpers.setSliceCursor(sliceTop, gd, {
hideOnRoot: true,
hideOnLeaves: false,
isTransitioning: false
});
});
}
updateSlices.each(function (pt) {
// for bbox
pt._x0 = viewX(pt.x0);
pt._x1 = viewX(pt.x1);
pt._y0 = viewY(pt.y0);
pt._y1 = viewY(pt.y1);
pt._hoverX = viewX(pt.x1 - trace.tiling.pad), pt._hoverY = hasBottom ? viewY(pt.y1 - trace.tiling.pad / 2) : viewY(pt.y0 + trace.tiling.pad / 2);
var sliceTop = d3.select(this);
var slicePath = Lib.ensureSingle(sliceTop, 'path', 'surface', function (s) {
s.style('pointer-events', isStatic ? 'none' : 'all');
});
if (hasTransition) {
slicePath.transition().attrTween('d', function (pt2) {
var interp = makeUpdateSliceInterpolator(pt2, onPathbar, getRefRect(), [width, height], {
orientation: trace.tiling.orientation,
flipX: trace.tiling.flip.indexOf('x') > -1,
flipY: trace.tiling.flip.indexOf('y') > -1
});
return function (t) {
return pathSlice(interp(t));
};
});
} else {
slicePath.attr('d', pathSlice);
}
sliceTop.call(attachFxHandlers, entry, gd, cd, {
styleOne: styleOne,
eventDataKeys: constants.eventDataKeys,
transitionTime: constants.CLICK_TRANSITION_TIME,
transitionEasing: constants.CLICK_TRANSITION_EASING
}).call(helpers.setSliceCursor, gd, {
isTransitioning: gd._transitioning
});
slicePath.call(styleOne, pt, trace, gd, {
hovered: false
});
if (pt.x0 === pt.x1 || pt.y0 === pt.y1) {
pt._text = '';
} else {
pt._text = formatSliceLabel(pt, entry, trace, cd, fullLayout) || '';
}
var sliceTextGroup = Lib.ensureSingle(sliceTop, 'g', 'slicetext');
var sliceText = Lib.ensureSingle(sliceTextGroup, '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, helpers.determineTextFont(trace, pt, fullLayout.font));
sliceText.text(pt._text || ' ') // use one space character instead of a blank string to avoid jumps during transition
.classed('slicetext', true).attr('text-anchor', hasRight ? 'end' : hasLeft ? 'start' : 'middle').call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
pt.textBB = Drawing.bBox(sliceText.node());
pt.transform = toMoveInsideSlice(pt, {
fontSize: font.size
});
pt.transform.fontSize = font.size;
if (hasTransition) {
sliceText.transition().attrTween('transform', function (pt2) {
var interp = makeUpdateTextInterpolator(pt2, onPathbar, getRefRect(), [width, height]);
return function (t) {
return strTransform(interp(t));
};
});
} else {
sliceText.attr('transform', strTransform(pt));
}
});
return nextOfPrevEntry;
};
/***/ }),
/***/ 29044:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'icicle',
basePlotModule: __webpack_require__(59564),
categories: [],
animatable: true,
attributes: __webpack_require__(97376),
layoutAttributes: __webpack_require__(90676),
supplyDefaults: __webpack_require__(7045),
supplyLayoutDefaults: __webpack_require__(4304),
calc: (__webpack_require__(73876)/* .calc */ .r),
crossTraceCalc: (__webpack_require__(73876)/* .crossTraceCalc */ .q),
plot: __webpack_require__(38364),
style: (__webpack_require__(47192).style),
colorbar: __webpack_require__(5528),
meta: {}
};
/***/ }),
/***/ 90676:
/***/ (function(module) {
"use strict";
module.exports = {
iciclecolorway: {
valType: 'colorlist',
editType: 'calc'
},
extendiciclecolors: {
valType: 'boolean',
dflt: true,
editType: 'calc'
}
};
/***/ }),
/***/ 4304:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(90676);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
coerce('iciclecolorway', layoutOut.colorway);
coerce('extendiciclecolors');
};
/***/ }),
/***/ 25132:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3Hierarchy = __webpack_require__(74148);
var flipTree = __webpack_require__(83024);
module.exports = function partition(entry, size, opts) {
var flipX = opts.flipX;
var flipY = opts.flipY;
var swapXY = opts.orientation === 'h';
var maxDepth = opts.maxDepth;
var newWidth = size[0];
var newHeight = size[1];
if (maxDepth) {
newWidth = (entry.height + 1) * size[0] / Math.min(entry.height + 1, maxDepth);
newHeight = (entry.height + 1) * size[1] / Math.min(entry.height + 1, maxDepth);
}
var result = d3Hierarchy.partition().padding(opts.pad.inner).size(swapXY ? [size[1], newWidth] : [size[0], newHeight])(entry);
if (swapXY || flipX || flipY) {
flipTree(result, size, {
swapXY: swapXY,
flipX: flipX,
flipY: flipY
});
}
return result;
};
/***/ }),
/***/ 38364:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var draw = __webpack_require__(95808);
var drawDescendants = __webpack_require__(67880);
module.exports = function _plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback) {
return draw(gd, cdmodule, transitionOpts, makeOnCompleteCallback, {
type: 'icicle',
drawDescendants: drawDescendants
});
};
/***/ }),
/***/ 47192:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
var Lib = __webpack_require__(3400);
var resizeText = (__webpack_require__(82744).resizeText);
var fillOne = __webpack_require__(60404);
function style(gd) {
var s = gd._fullLayout._iciclelayer.selectAll('.trace');
resizeText(gd, s, 'icicle');
s.each(function (cd) {
var gTrace = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
gTrace.style('opacity', trace.opacity);
gTrace.selectAll('path.surface').each(function (pt) {
d3.select(this).call(styleOne, pt, trace, gd);
});
});
}
function styleOne(s, pt, trace, gd) {
var cdi = pt.data.data;
var isLeaf = !pt.children;
var ptNumber = cdi.i;
var lineColor = Lib.castOption(trace, ptNumber, 'marker.line.color') || Color.defaultLine;
var lineWidth = Lib.castOption(trace, ptNumber, 'marker.line.width') || 0;
s.call(fillOne, pt, trace, gd).style('stroke-width', lineWidth).call(Color.stroke, lineColor).style('opacity', isLeaf ? trace.leaf.opacity : null);
}
module.exports = {
style: style,
styleOne: styleOne
};
/***/ }),
/***/ 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;
});
};
/***/ }),
/***/ 89864:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var extendFlat = (__webpack_require__(92880).extendFlat);
var extendDeep = (__webpack_require__(92880).extendDeep);
var overrideAll = (__webpack_require__(67824).overrideAll);
var fontAttrs = __webpack_require__(25376);
var colorAttrs = __webpack_require__(22548);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var axesAttrs = __webpack_require__(94724);
var templatedArray = (__webpack_require__(31780).templatedArray);
var delta = __webpack_require__(48164);
var descriptionOnlyNumbers = (__webpack_require__(29736).descriptionOnlyNumbers);
var textFontAttrs = fontAttrs({
editType: 'plot',
colorEditType: 'plot'
});
var gaugeBarAttrs = {
color: {
valType: 'color',
editType: 'plot'
},
line: {
color: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'plot'
},
width: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'plot'
},
editType: 'calc'
},
thickness: {
valType: 'number',
min: 0,
max: 1,
dflt: 1,
editType: 'plot'
},
editType: 'calc'
};
var rangeAttr = {
valType: 'info_array',
items: [{
valType: 'number',
editType: 'plot'
}, {
valType: 'number',
editType: 'plot'
}],
editType: 'plot'
};
var stepsAttrs = templatedArray('step', extendDeep({}, gaugeBarAttrs, {
range: rangeAttr
}));
module.exports = {
mode: {
valType: 'flaglist',
editType: 'calc',
flags: ['number', 'delta', 'gauge'],
dflt: 'number'
},
value: {
valType: 'number',
editType: 'calc',
anim: true
},
align: {
valType: 'enumerated',
values: ['left', 'center', 'right'],
editType: 'plot'
},
// position
domain: domainAttrs({
name: 'indicator',
trace: true,
editType: 'calc'
}),
title: {
text: {
valType: 'string',
editType: 'plot'
},
align: {
valType: 'enumerated',
values: ['left', 'center', 'right'],
editType: 'plot'
},
font: extendFlat({}, textFontAttrs, {}),
editType: 'plot'
},
number: {
valueformat: {
valType: 'string',
dflt: '',
editType: 'plot',
description: descriptionOnlyNumbers('value')
},
font: extendFlat({}, textFontAttrs, {}),
prefix: {
valType: 'string',
dflt: '',
editType: 'plot'
},
suffix: {
valType: 'string',
dflt: '',
editType: 'plot'
},
editType: 'plot'
},
delta: {
reference: {
valType: 'number',
editType: 'calc'
},
position: {
valType: 'enumerated',
values: ['top', 'bottom', 'left', 'right'],
dflt: 'bottom',
editType: 'plot'
},
relative: {
valType: 'boolean',
editType: 'plot',
dflt: false
},
valueformat: {
valType: 'string',
editType: 'plot',
description: descriptionOnlyNumbers('value')
},
increasing: {
symbol: {
valType: 'string',
dflt: delta.INCREASING.SYMBOL,
editType: 'plot'
},
color: {
valType: 'color',
dflt: delta.INCREASING.COLOR,
editType: 'plot'
},
// TODO: add attribute to show sign
editType: 'plot'
},
decreasing: {
symbol: {
valType: 'string',
dflt: delta.DECREASING.SYMBOL,
editType: 'plot'
},
color: {
valType: 'color',
dflt: delta.DECREASING.COLOR,
editType: 'plot'
},
// TODO: add attribute to hide sign
editType: 'plot'
},
font: extendFlat({}, textFontAttrs, {}),
prefix: {
valType: 'string',
dflt: '',
editType: 'plot'
},
suffix: {
valType: 'string',
dflt: '',
editType: 'plot'
},
editType: 'calc'
},
gauge: {
shape: {
valType: 'enumerated',
editType: 'plot',
dflt: 'angular',
values: ['angular', 'bullet']
},
bar: extendDeep({}, gaugeBarAttrs, {
color: {
dflt: 'green'
}
}),
// Background of the gauge
bgcolor: {
valType: 'color',
editType: 'plot'
},
bordercolor: {
valType: 'color',
dflt: colorAttrs.defaultLine,
editType: 'plot'
},
borderwidth: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'plot'
},
axis: overrideAll({
range: rangeAttr,
visible: extendFlat({}, axesAttrs.visible, {
dflt: true
}),
// tick and title properties named and function exactly as in axes
tickmode: axesAttrs.minor.tickmode,
nticks: axesAttrs.nticks,
tick0: axesAttrs.tick0,
dtick: axesAttrs.dtick,
tickvals: axesAttrs.tickvals,
ticktext: axesAttrs.ticktext,
ticks: extendFlat({}, axesAttrs.ticks, {
dflt: 'outside'
}),
ticklen: axesAttrs.ticklen,
tickwidth: axesAttrs.tickwidth,
tickcolor: axesAttrs.tickcolor,
ticklabelstep: axesAttrs.ticklabelstep,
showticklabels: axesAttrs.showticklabels,
labelalias: axesAttrs.labelalias,
tickfont: fontAttrs({}),
tickangle: axesAttrs.tickangle,
tickformat: axesAttrs.tickformat,
tickformatstops: axesAttrs.tickformatstops,
tickprefix: axesAttrs.tickprefix,
showtickprefix: axesAttrs.showtickprefix,
ticksuffix: axesAttrs.ticksuffix,
showticksuffix: axesAttrs.showticksuffix,
separatethousands: axesAttrs.separatethousands,
exponentformat: axesAttrs.exponentformat,
minexponent: axesAttrs.minexponent,
showexponent: axesAttrs.showexponent,
editType: 'plot'
}, 'plot'),
// Steps (or ranges) and thresholds
steps: stepsAttrs,
threshold: {
line: {
color: extendFlat({}, gaugeBarAttrs.line.color, {}),
width: extendFlat({}, gaugeBarAttrs.line.width, {
dflt: 1
}),
editType: 'plot'
},
thickness: extendFlat({}, gaugeBarAttrs.thickness, {
dflt: 0.85
}),
value: {
valType: 'number',
editType: 'calc',
dflt: false
},
editType: 'plot'
},
editType: 'plot'
// TODO: in future version, add marker: (bar|needle)
}
};
/***/ }),
/***/ 92728:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var plots = __webpack_require__(7316);
exports.name = 'indicator';
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);
};
/***/ }),
/***/ 79136:
/***/ (function(module) {
"use strict";
// var Lib = require('../../lib');
function calc(gd, trace) {
var cd = [];
var lastReading = trace.value;
if (!(typeof trace._lastValue === 'number')) trace._lastValue = trace.value;
var secondLastReading = trace._lastValue;
var deltaRef = secondLastReading;
if (trace._hasDelta && typeof trace.delta.reference === 'number') {
deltaRef = trace.delta.reference;
}
cd[0] = {
y: lastReading,
lastY: secondLastReading,
delta: lastReading - deltaRef,
relativeDelta: (lastReading - deltaRef) / deltaRef
};
return cd;
}
module.exports = {
calc: calc
};
/***/ }),
/***/ 12096:
/***/ (function(module) {
"use strict";
module.exports = {
// Defaults for delta
defaultNumberFontSize: 80,
bulletNumberDomainSize: 0.25,
bulletPadding: 0.025,
innerRadius: 0.75,
valueThickness: 0.5,
// thickness of value bars relative to full thickness,
titlePadding: 5,
horizontalPadding: 10
};
/***/ }),
/***/ 20424:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(89864);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var Template = __webpack_require__(31780);
var handleArrayContainerDefaults = __webpack_require__(51272);
var cn = __webpack_require__(12096);
var handleTickValueDefaults = __webpack_require__(26332);
var handleTickMarkDefaults = __webpack_require__(25404);
var handleTickLabelDefaults = __webpack_require__(95936);
var handlePrefixSuffixDefaults = __webpack_require__(42568);
function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
handleDomainDefaults(traceOut, layout, coerce);
// Mode
coerce('mode');
traceOut._hasNumber = traceOut.mode.indexOf('number') !== -1;
traceOut._hasDelta = traceOut.mode.indexOf('delta') !== -1;
traceOut._hasGauge = traceOut.mode.indexOf('gauge') !== -1;
var value = coerce('value');
traceOut._range = [0, typeof value === 'number' ? 1.5 * value : 1];
// Number attributes
var auto = new Array(2);
var bignumberFontSize;
if (traceOut._hasNumber) {
coerce('number.valueformat');
var numberFontDflt = Lib.extendFlat({}, layout.font);
numberFontDflt.size = undefined;
Lib.coerceFont(coerce, 'number.font', numberFontDflt);
if (traceOut.number.font.size === undefined) {
traceOut.number.font.size = cn.defaultNumberFontSize;
auto[0] = true;
}
coerce('number.prefix');
coerce('number.suffix');
bignumberFontSize = traceOut.number.font.size;
}
// delta attributes
var deltaFontSize;
if (traceOut._hasDelta) {
var deltaFontDflt = Lib.extendFlat({}, layout.font);
deltaFontDflt.size = undefined;
Lib.coerceFont(coerce, 'delta.font', deltaFontDflt);
if (traceOut.delta.font.size === undefined) {
traceOut.delta.font.size = (traceOut._hasNumber ? 0.5 : 1) * (bignumberFontSize || cn.defaultNumberFontSize);
auto[1] = true;
}
coerce('delta.reference', traceOut.value);
coerce('delta.relative');
coerce('delta.valueformat', traceOut.delta.relative ? '2%' : '');
coerce('delta.increasing.symbol');
coerce('delta.increasing.color');
coerce('delta.decreasing.symbol');
coerce('delta.decreasing.color');
coerce('delta.position');
coerce('delta.prefix');
coerce('delta.suffix');
deltaFontSize = traceOut.delta.font.size;
}
traceOut._scaleNumbers = (!traceOut._hasNumber || auto[0]) && (!traceOut._hasDelta || auto[1]) || false;
// Title attributes
var titleFontDflt = Lib.extendFlat({}, layout.font);
titleFontDflt.size = 0.25 * (bignumberFontSize || deltaFontSize || cn.defaultNumberFontSize);
Lib.coerceFont(coerce, 'title.font', titleFontDflt);
coerce('title.text');
// Gauge attributes
var gaugeIn, gaugeOut, axisIn, axisOut;
function coerceGauge(attr, dflt) {
return Lib.coerce(gaugeIn, gaugeOut, attributes.gauge, attr, dflt);
}
function coerceGaugeAxis(attr, dflt) {
return Lib.coerce(axisIn, axisOut, attributes.gauge.axis, attr, dflt);
}
if (traceOut._hasGauge) {
gaugeIn = traceIn.gauge;
if (!gaugeIn) gaugeIn = {};
gaugeOut = Template.newContainer(traceOut, 'gauge');
coerceGauge('shape');
var isBullet = traceOut._isBullet = traceOut.gauge.shape === 'bullet';
if (!isBullet) {
coerce('title.align', 'center');
}
var isAngular = traceOut._isAngular = traceOut.gauge.shape === 'angular';
if (!isAngular) {
coerce('align', 'center');
}
// gauge background
coerceGauge('bgcolor', layout.paper_bgcolor);
coerceGauge('borderwidth');
coerceGauge('bordercolor');
// gauge bar indicator
coerceGauge('bar.color');
coerceGauge('bar.line.color');
coerceGauge('bar.line.width');
var defaultBarThickness = cn.valueThickness * (traceOut.gauge.shape === 'bullet' ? 0.5 : 1);
coerceGauge('bar.thickness', defaultBarThickness);
// Gauge steps
handleArrayContainerDefaults(gaugeIn, gaugeOut, {
name: 'steps',
handleItemDefaults: stepDefaults
});
// Gauge threshold
coerceGauge('threshold.value');
coerceGauge('threshold.thickness');
coerceGauge('threshold.line.width');
coerceGauge('threshold.line.color');
// Gauge axis
axisIn = {};
if (gaugeIn) axisIn = gaugeIn.axis || {};
axisOut = Template.newContainer(gaugeOut, 'axis');
coerceGaugeAxis('visible');
traceOut._range = coerceGaugeAxis('range', traceOut._range);
var opts = {
font: layout.font,
noAutotickangles: true,
outerTicks: true,
noTicklabelshift: true,
noTicklabelstandoff: true
};
handleTickValueDefaults(axisIn, axisOut, coerceGaugeAxis, 'linear');
handlePrefixSuffixDefaults(axisIn, axisOut, coerceGaugeAxis, 'linear', opts);
handleTickLabelDefaults(axisIn, axisOut, coerceGaugeAxis, 'linear', opts);
handleTickMarkDefaults(axisIn, axisOut, coerceGaugeAxis, opts);
} else {
coerce('title.align', 'center');
coerce('align', 'center');
traceOut._isAngular = traceOut._isBullet = false;
}
// disable 1D transforms
traceOut._length = null;
}
function stepDefaults(stepIn, stepOut) {
function coerce(attr, dflt) {
return Lib.coerce(stepIn, stepOut, attributes.gauge.steps, attr, dflt);
}
coerce('color');
coerce('line.color');
coerce('line.width');
coerce('range');
coerce('thickness');
}
module.exports = {
supplyDefaults: supplyDefaults
};
/***/ }),
/***/ 43480:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'indicator',
basePlotModule: __webpack_require__(92728),
categories: ['svg', 'noOpacity', 'noHover'],
animatable: true,
attributes: __webpack_require__(89864),
supplyDefaults: (__webpack_require__(20424).supplyDefaults),
calc: (__webpack_require__(79136).calc),
plot: __webpack_require__(97864),
meta: {}
};
/***/ }),
/***/ 97864:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var interpolate = (__webpack_require__(67756)/* .interpolate */ .qy);
var interpolateNumber = (__webpack_require__(67756)/* .interpolateNumber */ .Gz);
var Lib = __webpack_require__(3400);
var strScale = Lib.strScale;
var strTranslate = Lib.strTranslate;
var rad2deg = Lib.rad2deg;
var MID_SHIFT = (__webpack_require__(84284).MID_SHIFT);
var Drawing = __webpack_require__(43616);
var cn = __webpack_require__(12096);
var svgTextUtils = __webpack_require__(72736);
var Axes = __webpack_require__(54460);
var handleAxisDefaults = __webpack_require__(28336);
var handleAxisPositionDefaults = __webpack_require__(37668);
var axisLayoutAttrs = __webpack_require__(94724);
var Color = __webpack_require__(76308);
var anchor = {
left: 'start',
center: 'middle',
right: 'end'
};
var position = {
left: 0,
center: 0.5,
right: 1
};
var SI_PREFIX = /[yzafpnµmkMGTPEZY]/;
function hasTransition(transitionOpts) {
// If transition config is provided, then it is only a partial replot and traces not
// updated are removed.
return transitionOpts && transitionOpts.duration > 0;
}
module.exports = function plot(gd, cdModule, transitionOpts, makeOnCompleteCallback) {
var fullLayout = gd._fullLayout;
var onComplete;
if (hasTransition(transitionOpts)) {
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();
}
}
Lib.makeTraceGroups(fullLayout._indicatorlayer, cdModule, 'trace').each(function (cd) {
var cd0 = cd[0];
var trace = cd0.trace;
var plotGroup = d3.select(this);
// Elements in trace
var hasGauge = trace._hasGauge;
var isAngular = trace._isAngular;
var isBullet = trace._isBullet;
// Domain size
var domain = trace.domain;
var size = {
w: fullLayout._size.w * (domain.x[1] - domain.x[0]),
h: fullLayout._size.h * (domain.y[1] - domain.y[0]),
l: fullLayout._size.l + fullLayout._size.w * domain.x[0],
r: fullLayout._size.r + fullLayout._size.w * (1 - domain.x[1]),
t: fullLayout._size.t + fullLayout._size.h * (1 - domain.y[1]),
b: fullLayout._size.b + fullLayout._size.h * domain.y[0]
};
var centerX = size.l + size.w / 2;
var centerY = size.t + size.h / 2;
// Angular gauge size
var radius = Math.min(size.w / 2, size.h); // fill domain
var innerRadius = cn.innerRadius * radius;
// Position numbers based on mode and set the scaling logic
var numbersX, numbersY, numbersScaler;
var numbersAlign = trace.align || 'center';
numbersY = centerY;
if (!hasGauge) {
numbersX = size.l + position[numbersAlign] * size.w;
numbersScaler = function (el) {
return fitTextInsideBox(el, size.w, size.h);
};
} else {
if (isAngular) {
numbersX = centerX;
numbersY = centerY + radius / 2;
numbersScaler = function (el) {
return fitTextInsideCircle(el, 0.9 * innerRadius);
};
}
if (isBullet) {
var padding = cn.bulletPadding;
var p = 1 - cn.bulletNumberDomainSize + padding;
numbersX = size.l + (p + (1 - p) * position[numbersAlign]) * size.w;
numbersScaler = function (el) {
return fitTextInsideBox(el, (cn.bulletNumberDomainSize - padding) * size.w, size.h);
};
}
}
// Draw numbers
drawNumbers(gd, plotGroup, cd, {
numbersX: numbersX,
numbersY: numbersY,
numbersScaler: numbersScaler,
transitionOpts: transitionOpts,
onComplete: onComplete
});
// Reexpress our gauge background attributes for drawing
var gaugeBg, gaugeOutline;
if (hasGauge) {
gaugeBg = {
range: trace.gauge.axis.range,
color: trace.gauge.bgcolor,
line: {
color: trace.gauge.bordercolor,
width: 0
},
thickness: 1
};
gaugeOutline = {
range: trace.gauge.axis.range,
color: 'rgba(0, 0, 0, 0)',
line: {
color: trace.gauge.bordercolor,
width: trace.gauge.borderwidth
},
thickness: 1
};
}
// Prepare angular gauge layers
var angularGauge = plotGroup.selectAll('g.angular').data(isAngular ? cd : []);
angularGauge.exit().remove();
var angularaxisLayer = plotGroup.selectAll('g.angularaxis').data(isAngular ? cd : []);
angularaxisLayer.exit().remove();
if (isAngular) {
drawAngularGauge(gd, plotGroup, cd, {
radius: radius,
innerRadius: innerRadius,
gauge: angularGauge,
layer: angularaxisLayer,
size: size,
gaugeBg: gaugeBg,
gaugeOutline: gaugeOutline,
transitionOpts: transitionOpts,
onComplete: onComplete
});
}
// Prepare bullet layers
var bulletGauge = plotGroup.selectAll('g.bullet').data(isBullet ? cd : []);
bulletGauge.exit().remove();
var bulletaxisLayer = plotGroup.selectAll('g.bulletaxis').data(isBullet ? cd : []);
bulletaxisLayer.exit().remove();
if (isBullet) {
drawBulletGauge(gd, plotGroup, cd, {
gauge: bulletGauge,
layer: bulletaxisLayer,
size: size,
gaugeBg: gaugeBg,
gaugeOutline: gaugeOutline,
transitionOpts: transitionOpts,
onComplete: onComplete
});
}
// title
var title = plotGroup.selectAll('text.title').data(cd);
title.exit().remove();
title.enter().append('text').classed('title', true);
title.attr('text-anchor', function () {
return isBullet ? anchor.right : anchor[trace.title.align];
}).text(trace.title.text).call(Drawing.font, trace.title.font).call(svgTextUtils.convertToTspans, gd);
// Position title
title.attr('transform', function () {
var titleX = size.l + size.w * position[trace.title.align];
var titleY;
var titlePadding = cn.titlePadding;
var titlebBox = Drawing.bBox(title.node());
if (hasGauge) {
if (isAngular) {
// position above axis ticks/labels
if (trace.gauge.axis.visible) {
var bBox = Drawing.bBox(angularaxisLayer.node());
titleY = bBox.top - titlePadding - titlebBox.bottom;
} else {
titleY = size.t + size.h / 2 - radius / 2 - titlebBox.bottom - titlePadding;
}
}
if (isBullet) {
// position outside domain
titleY = numbersY - (titlebBox.top + titlebBox.bottom) / 2;
titleX = size.l - cn.bulletPadding * size.w; // Outside domain, on the left
}
} else {
// position above numbers
titleY = trace._numbersTop - titlePadding - titlebBox.bottom;
}
return strTranslate(titleX, titleY);
});
});
};
function drawBulletGauge(gd, plotGroup, cd, opts) {
var trace = cd[0].trace;
var bullet = opts.gauge;
var axisLayer = opts.layer;
var gaugeBg = opts.gaugeBg;
var gaugeOutline = opts.gaugeOutline;
var size = opts.size;
var domain = trace.domain;
var transitionOpts = opts.transitionOpts;
var onComplete = opts.onComplete;
// preparing axis
var ax, vals, transFn, tickSign, shift;
// Enter bullet, axis
bullet.enter().append('g').classed('bullet', true);
bullet.attr('transform', strTranslate(size.l, size.t));
axisLayer.enter().append('g').classed('bulletaxis', true).classed('crisp', true);
axisLayer.selectAll('g.' + 'xbulletaxis' + 'tick,path,text').remove();
// Draw bullet
var bulletHeight = size.h; // use all vertical domain
var innerBulletHeight = trace.gauge.bar.thickness * bulletHeight;
var bulletLeft = domain.x[0];
var bulletRight = domain.x[0] + (domain.x[1] - domain.x[0]) * (trace._hasNumber || trace._hasDelta ? 1 - cn.bulletNumberDomainSize : 1);
ax = mockAxis(gd, trace.gauge.axis);
ax._id = 'xbulletaxis';
ax.domain = [bulletLeft, bulletRight];
ax.setScale();
vals = Axes.calcTicks(ax);
transFn = Axes.makeTransTickFn(ax);
tickSign = Axes.getTickSigns(ax)[2];
shift = size.t + size.h;
if (ax.visible) {
Axes.drawTicks(gd, ax, {
vals: ax.ticks === 'inside' ? Axes.clipEnds(ax, vals) : vals,
layer: axisLayer,
path: Axes.makeTickPath(ax, shift, tickSign),
transFn: transFn
});
Axes.drawLabels(gd, ax, {
vals: vals,
layer: axisLayer,
transFn: transFn,
labelFns: Axes.makeLabelFns(ax, shift)
});
}
function drawRect(s) {
s.attr('width', function (d) {
return Math.max(0, ax.c2p(d.range[1]) - ax.c2p(d.range[0]));
}).attr('x', function (d) {
return ax.c2p(d.range[0]);
}).attr('y', function (d) {
return 0.5 * (1 - d.thickness) * bulletHeight;
}).attr('height', function (d) {
return d.thickness * bulletHeight;
});
}
// Draw bullet background, steps
var boxes = [gaugeBg].concat(trace.gauge.steps);
var bgBullet = bullet.selectAll('g.bg-bullet').data(boxes);
bgBullet.enter().append('g').classed('bg-bullet', true).append('rect');
bgBullet.select('rect').call(drawRect).call(styleShape);
bgBullet.exit().remove();
// Draw value bar with transitions
var fgBullet = bullet.selectAll('g.value-bullet').data([trace.gauge.bar]);
fgBullet.enter().append('g').classed('value-bullet', true).append('rect');
fgBullet.select('rect').attr('height', innerBulletHeight).attr('y', (bulletHeight - innerBulletHeight) / 2).call(styleShape);
if (hasTransition(transitionOpts)) {
fgBullet.select('rect').transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each('end', function () {
onComplete && onComplete();
}).each('interrupt', function () {
onComplete && onComplete();
}).attr('width', Math.max(0, ax.c2p(Math.min(trace.gauge.axis.range[1], cd[0].y))));
} else {
fgBullet.select('rect').attr('width', typeof cd[0].y === 'number' ? Math.max(0, ax.c2p(Math.min(trace.gauge.axis.range[1], cd[0].y))) : 0);
}
fgBullet.exit().remove();
var data = cd.filter(function () {
return trace.gauge.threshold.value || trace.gauge.threshold.value === 0;
});
var threshold = bullet.selectAll('g.threshold-bullet').data(data);
threshold.enter().append('g').classed('threshold-bullet', true).append('line');
threshold.select('line').attr('x1', ax.c2p(trace.gauge.threshold.value)).attr('x2', ax.c2p(trace.gauge.threshold.value)).attr('y1', (1 - trace.gauge.threshold.thickness) / 2 * bulletHeight).attr('y2', (1 - (1 - trace.gauge.threshold.thickness) / 2) * bulletHeight).call(Color.stroke, trace.gauge.threshold.line.color).style('stroke-width', trace.gauge.threshold.line.width);
threshold.exit().remove();
var bulletOutline = bullet.selectAll('g.gauge-outline').data([gaugeOutline]);
bulletOutline.enter().append('g').classed('gauge-outline', true).append('rect');
bulletOutline.select('rect').call(drawRect).call(styleShape);
bulletOutline.exit().remove();
}
function drawAngularGauge(gd, plotGroup, cd, opts) {
var trace = cd[0].trace;
var size = opts.size;
var radius = opts.radius;
var innerRadius = opts.innerRadius;
var gaugeBg = opts.gaugeBg;
var gaugeOutline = opts.gaugeOutline;
var gaugePosition = [size.l + size.w / 2, size.t + size.h / 2 + radius / 2];
var gauge = opts.gauge;
var axisLayer = opts.layer;
var transitionOpts = opts.transitionOpts;
var onComplete = opts.onComplete;
// circular gauge
var theta = Math.PI / 2;
function valueToAngle(v) {
var min = trace.gauge.axis.range[0];
var max = trace.gauge.axis.range[1];
var angle = (v - min) / (max - min) * Math.PI - theta;
if (angle < -theta) return -theta;
if (angle > theta) return theta;
return angle;
}
function arcPathGenerator(size) {
return d3.svg.arc().innerRadius((innerRadius + radius) / 2 - size / 2 * (radius - innerRadius)).outerRadius((innerRadius + radius) / 2 + size / 2 * (radius - innerRadius)).startAngle(-theta);
}
function drawArc(p) {
p.attr('d', function (d) {
return arcPathGenerator(d.thickness).startAngle(valueToAngle(d.range[0])).endAngle(valueToAngle(d.range[1]))();
});
}
// preparing axis
var ax, vals, transFn, tickSign;
// Enter gauge and axis
gauge.enter().append('g').classed('angular', true);
gauge.attr('transform', strTranslate(gaugePosition[0], gaugePosition[1]));
axisLayer.enter().append('g').classed('angularaxis', true).classed('crisp', true);
axisLayer.selectAll('g.' + 'xangularaxis' + 'tick,path,text').remove();
ax = mockAxis(gd, trace.gauge.axis);
ax.type = 'linear';
ax.range = trace.gauge.axis.range;
ax._id = 'xangularaxis'; // or 'y', but I don't think this makes a difference here
ax.ticklabeloverflow = 'allow';
ax.setScale();
// 't'ick to 'g'eometric radians is used all over the place here
var t2g = function (d) {
return (ax.range[0] - d.x) / (ax.range[1] - ax.range[0]) * Math.PI + Math.PI;
};
var labelFns = {};
var out = Axes.makeLabelFns(ax, 0);
var labelStandoff = out.labelStandoff;
labelFns.xFn = function (d) {
var rad = t2g(d);
return Math.cos(rad) * labelStandoff;
};
labelFns.yFn = function (d) {
var rad = t2g(d);
var ff = Math.sin(rad) > 0 ? 0.2 : 1;
return -Math.sin(rad) * (labelStandoff + d.fontSize * ff) + Math.abs(Math.cos(rad)) * (d.fontSize * MID_SHIFT);
};
labelFns.anchorFn = function (d) {
var rad = t2g(d);
var cos = Math.cos(rad);
return Math.abs(cos) < 0.1 ? 'middle' : cos > 0 ? 'start' : 'end';
};
labelFns.heightFn = function (d, a, h) {
var rad = t2g(d);
return -0.5 * (1 + Math.sin(rad)) * h;
};
var _transFn = function (rad) {
return strTranslate(gaugePosition[0] + radius * Math.cos(rad), gaugePosition[1] - radius * Math.sin(rad));
};
transFn = function (d) {
return _transFn(t2g(d));
};
var transFn2 = function (d) {
var rad = t2g(d);
return _transFn(rad) + 'rotate(' + -rad2deg(rad) + ')';
};
vals = Axes.calcTicks(ax);
tickSign = Axes.getTickSigns(ax)[2];
if (ax.visible) {
tickSign = ax.ticks === 'inside' ? -1 : 1;
var pad = (ax.linewidth || 1) / 2;
Axes.drawTicks(gd, ax, {
vals: vals,
layer: axisLayer,
path: 'M' + tickSign * pad + ',0h' + tickSign * ax.ticklen,
transFn: transFn2
});
Axes.drawLabels(gd, ax, {
vals: vals,
layer: axisLayer,
transFn: transFn,
labelFns: labelFns
});
}
// Draw background + steps
var arcs = [gaugeBg].concat(trace.gauge.steps);
var bgArc = gauge.selectAll('g.bg-arc').data(arcs);
bgArc.enter().append('g').classed('bg-arc', true).append('path');
bgArc.select('path').call(drawArc).call(styleShape);
bgArc.exit().remove();
// Draw foreground with transition
var valueArcPathGenerator = arcPathGenerator(trace.gauge.bar.thickness);
var valueArc = gauge.selectAll('g.value-arc').data([trace.gauge.bar]);
valueArc.enter().append('g').classed('value-arc', true).append('path');
var valueArcPath = valueArc.select('path');
if (hasTransition(transitionOpts)) {
valueArcPath.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each('end', function () {
onComplete && onComplete();
}).each('interrupt', function () {
onComplete && onComplete();
}).attrTween('d', arcTween(valueArcPathGenerator, valueToAngle(cd[0].lastY), valueToAngle(cd[0].y)));
trace._lastValue = cd[0].y;
} else {
valueArcPath.attr('d', typeof cd[0].y === 'number' ? valueArcPathGenerator.endAngle(valueToAngle(cd[0].y)) : 'M0,0Z');
}
valueArcPath.call(styleShape);
valueArc.exit().remove();
// Draw threshold
arcs = [];
var v = trace.gauge.threshold.value;
if (v || v === 0) {
arcs.push({
range: [v, v],
color: trace.gauge.threshold.color,
line: {
color: trace.gauge.threshold.line.color,
width: trace.gauge.threshold.line.width
},
thickness: trace.gauge.threshold.thickness
});
}
var thresholdArc = gauge.selectAll('g.threshold-arc').data(arcs);
thresholdArc.enter().append('g').classed('threshold-arc', true).append('path');
thresholdArc.select('path').call(drawArc).call(styleShape);
thresholdArc.exit().remove();
// Draw border last
var gaugeBorder = gauge.selectAll('g.gauge-outline').data([gaugeOutline]);
gaugeBorder.enter().append('g').classed('gauge-outline', true).append('path');
gaugeBorder.select('path').call(drawArc).call(styleShape);
gaugeBorder.exit().remove();
}
function drawNumbers(gd, plotGroup, cd, opts) {
var trace = cd[0].trace;
var numbersX = opts.numbersX;
var numbersY = opts.numbersY;
var numbersAlign = trace.align || 'center';
var numbersAnchor = anchor[numbersAlign];
var transitionOpts = opts.transitionOpts;
var onComplete = opts.onComplete;
var numbers = Lib.ensureSingle(plotGroup, 'g', 'numbers');
var bignumberbBox, deltabBox;
var numbersbBox;
var data = [];
if (trace._hasNumber) data.push('number');
if (trace._hasDelta) {
data.push('delta');
if (trace.delta.position === 'left') data.reverse();
}
var sel = numbers.selectAll('text').data(data);
sel.enter().append('text');
sel.attr('text-anchor', function () {
return numbersAnchor;
}).attr('class', function (d) {
return d;
}).attr('x', null).attr('y', null).attr('dx', null).attr('dy', null);
sel.exit().remove();
// Function to override the number formatting used during transitions
function transitionFormat(valueformat, fmt, from, to) {
// For now, do not display SI prefix if start and end value do not have any
if (valueformat.match('s') &&
// If using SI prefix
from >= 0 !== to >= 0 &&
// If sign change
!fmt(from).slice(-1).match(SI_PREFIX) && !fmt(to).slice(-1).match(SI_PREFIX) // Has no SI prefix
) {
var transitionValueFormat = valueformat.slice().replace('s', 'f').replace(/\d+/, function (m) {
return parseInt(m) - 1;
});
var transitionAx = mockAxis(gd, {
tickformat: transitionValueFormat
});
return function (v) {
// Switch to fixed precision if number is smaller than one
if (Math.abs(v) < 1) return Axes.tickText(transitionAx, v).text;
return fmt(v);
};
} else {
return fmt;
}
}
function drawBignumber() {
var bignumberAx = mockAxis(gd, {
tickformat: trace.number.valueformat
}, trace._range);
bignumberAx.setScale();
Axes.prepTicks(bignumberAx);
var bignumberFmt = function (v) {
return Axes.tickText(bignumberAx, v).text;
};
var bignumberSuffix = trace.number.suffix;
var bignumberPrefix = trace.number.prefix;
var number = numbers.select('text.number');
function writeNumber() {
var txt = typeof cd[0].y === 'number' ? bignumberPrefix + bignumberFmt(cd[0].y) + bignumberSuffix : '-';
number.text(txt).call(Drawing.font, trace.number.font).call(svgTextUtils.convertToTspans, gd);
}
if (hasTransition(transitionOpts)) {
number.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each('end', function () {
writeNumber();
onComplete && onComplete();
}).each('interrupt', function () {
writeNumber();
onComplete && onComplete();
}).attrTween('text', function () {
var that = d3.select(this);
var interpolator = interpolateNumber(cd[0].lastY, cd[0].y);
trace._lastValue = cd[0].y;
var transitionFmt = transitionFormat(trace.number.valueformat, bignumberFmt, cd[0].lastY, cd[0].y);
return function (t) {
that.text(bignumberPrefix + transitionFmt(interpolator(t)) + bignumberSuffix);
};
});
} else {
writeNumber();
}
bignumberbBox = measureText(bignumberPrefix + bignumberFmt(cd[0].y) + bignumberSuffix, trace.number.font, numbersAnchor, gd);
return number;
}
function drawDelta() {
var deltaAx = mockAxis(gd, {
tickformat: trace.delta.valueformat
}, trace._range);
deltaAx.setScale();
Axes.prepTicks(deltaAx);
var deltaFmt = function (v) {
return Axes.tickText(deltaAx, v).text;
};
var deltaSuffix = trace.delta.suffix;
var deltaPrefix = trace.delta.prefix;
var deltaValue = function (d) {
var value = trace.delta.relative ? d.relativeDelta : d.delta;
return value;
};
var deltaFormatText = function (value, numberFmt) {
if (value === 0 || typeof value !== 'number' || isNaN(value)) return '-';
return (value > 0 ? trace.delta.increasing.symbol : trace.delta.decreasing.symbol) + deltaPrefix + numberFmt(value) + deltaSuffix;
};
var deltaFill = function (d) {
return d.delta >= 0 ? trace.delta.increasing.color : trace.delta.decreasing.color;
};
if (trace._deltaLastValue === undefined) {
trace._deltaLastValue = deltaValue(cd[0]);
}
var delta = numbers.select('text.delta');
delta.call(Drawing.font, trace.delta.font).call(Color.fill, deltaFill({
delta: trace._deltaLastValue
}));
function writeDelta() {
delta.text(deltaFormatText(deltaValue(cd[0]), deltaFmt)).call(Color.fill, deltaFill(cd[0])).call(svgTextUtils.convertToTspans, gd);
}
if (hasTransition(transitionOpts)) {
delta.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).tween('text', function () {
var that = d3.select(this);
var to = deltaValue(cd[0]);
var from = trace._deltaLastValue;
var transitionFmt = transitionFormat(trace.delta.valueformat, deltaFmt, from, to);
var interpolator = interpolateNumber(from, to);
trace._deltaLastValue = to;
return function (t) {
that.text(deltaFormatText(interpolator(t), transitionFmt));
that.call(Color.fill, deltaFill({
delta: interpolator(t)
}));
};
}).each('end', function () {
writeDelta();
onComplete && onComplete();
}).each('interrupt', function () {
writeDelta();
onComplete && onComplete();
});
} else {
writeDelta();
}
deltabBox = measureText(deltaFormatText(deltaValue(cd[0]), deltaFmt), trace.delta.font, numbersAnchor, gd);
return delta;
}
var key = trace.mode + trace.align;
var delta;
if (trace._hasDelta) {
delta = drawDelta();
key += trace.delta.position + trace.delta.font.size + trace.delta.font.family + trace.delta.valueformat;
key += trace.delta.increasing.symbol + trace.delta.decreasing.symbol;
numbersbBox = deltabBox;
}
if (trace._hasNumber) {
drawBignumber();
key += trace.number.font.size + trace.number.font.family + trace.number.valueformat + trace.number.suffix + trace.number.prefix;
numbersbBox = bignumberbBox;
}
// Position delta relative to bignumber
if (trace._hasDelta && trace._hasNumber) {
var bignumberCenter = [(bignumberbBox.left + bignumberbBox.right) / 2, (bignumberbBox.top + bignumberbBox.bottom) / 2];
var deltaCenter = [(deltabBox.left + deltabBox.right) / 2, (deltabBox.top + deltabBox.bottom) / 2];
var dx, dy;
var padding = 0.75 * trace.delta.font.size;
if (trace.delta.position === 'left') {
dx = cache(trace, 'deltaPos', 0, -1 * (bignumberbBox.width * position[trace.align] + deltabBox.width * (1 - position[trace.align]) + padding), key, Math.min);
dy = bignumberCenter[1] - deltaCenter[1];
numbersbBox = {
width: bignumberbBox.width + deltabBox.width + padding,
height: Math.max(bignumberbBox.height, deltabBox.height),
left: deltabBox.left + dx,
right: bignumberbBox.right,
top: Math.min(bignumberbBox.top, deltabBox.top + dy),
bottom: Math.max(bignumberbBox.bottom, deltabBox.bottom + dy)
};
}
if (trace.delta.position === 'right') {
dx = cache(trace, 'deltaPos', 0, bignumberbBox.width * (1 - position[trace.align]) + deltabBox.width * position[trace.align] + padding, key, Math.max);
dy = bignumberCenter[1] - deltaCenter[1];
numbersbBox = {
width: bignumberbBox.width + deltabBox.width + padding,
height: Math.max(bignumberbBox.height, deltabBox.height),
left: bignumberbBox.left,
right: deltabBox.right + dx,
top: Math.min(bignumberbBox.top, deltabBox.top + dy),
bottom: Math.max(bignumberbBox.bottom, deltabBox.bottom + dy)
};
}
if (trace.delta.position === 'bottom') {
dx = null;
dy = deltabBox.height;
numbersbBox = {
width: Math.max(bignumberbBox.width, deltabBox.width),
height: bignumberbBox.height + deltabBox.height,
left: Math.min(bignumberbBox.left, deltabBox.left),
right: Math.max(bignumberbBox.right, deltabBox.right),
top: bignumberbBox.bottom - bignumberbBox.height,
bottom: bignumberbBox.bottom + deltabBox.height
};
}
if (trace.delta.position === 'top') {
dx = null;
dy = bignumberbBox.top;
numbersbBox = {
width: Math.max(bignumberbBox.width, deltabBox.width),
height: bignumberbBox.height + deltabBox.height,
left: Math.min(bignumberbBox.left, deltabBox.left),
right: Math.max(bignumberbBox.right, deltabBox.right),
top: bignumberbBox.bottom - bignumberbBox.height - deltabBox.height,
bottom: bignumberbBox.bottom
};
}
delta.attr({
dx: dx,
dy: dy
});
}
// Resize numbers to fit within space and position
if (trace._hasNumber || trace._hasDelta) {
numbers.attr('transform', function () {
var m = opts.numbersScaler(numbersbBox);
key += m[2];
var scaleRatio = cache(trace, 'numbersScale', 1, m[0], key, Math.min);
var translateY;
if (!trace._scaleNumbers) scaleRatio = 1;
if (trace._isAngular) {
// align vertically to bottom
translateY = numbersY - scaleRatio * numbersbBox.bottom;
} else {
// align vertically to center
translateY = numbersY - scaleRatio * (numbersbBox.top + numbersbBox.bottom) / 2;
}
// Stash the top position of numbersbBox for title positioning
trace._numbersTop = scaleRatio * numbersbBox.top + translateY;
var ref = numbersbBox[numbersAlign];
if (numbersAlign === 'center') ref = (numbersbBox.left + numbersbBox.right) / 2;
var translateX = numbersX - scaleRatio * ref;
// Stash translateX
translateX = cache(trace, 'numbersTranslate', 0, translateX, key, Math.max);
return strTranslate(translateX, translateY) + strScale(scaleRatio);
});
}
}
// Apply fill, stroke, stroke-width to SVG shape
function styleShape(p) {
p.each(function (d) {
Color.stroke(d3.select(this), d.line.color);
}).each(function (d) {
Color.fill(d3.select(this), d.color);
}).style('stroke-width', function (d) {
return d.line.width;
});
}
// Returns a tween for a transition’s "d" attribute, transitioning any selected
// arcs from their current angle to the specified new angle.
function arcTween(arc, endAngle, newAngle) {
return function () {
var interp = interpolate(endAngle, newAngle);
return function (t) {
return arc.endAngle(interp(t))();
};
};
}
// mocks our axis
function mockAxis(gd, opts, zrange) {
var fullLayout = gd._fullLayout;
var axisIn = Lib.extendFlat({
type: 'linear',
ticks: 'outside',
range: zrange,
showline: true
}, opts);
var axisOut = {
type: 'linear',
_id: 'x' + opts._id
};
var axisOptions = {
letter: 'x',
font: fullLayout.font,
noAutotickangles: true,
noHover: true,
noTickson: true
};
function coerce(attr, dflt) {
return Lib.coerce(axisIn, axisOut, axisLayoutAttrs, attr, dflt);
}
handleAxisDefaults(axisIn, axisOut, coerce, axisOptions, fullLayout);
handleAxisPositionDefaults(axisIn, axisOut, coerce, axisOptions);
return axisOut;
}
function fitTextInsideBox(textBB, width, height) {
// compute scaling ratio to have text fit within specified width and height
var ratio = Math.min(width / textBB.width, height / textBB.height);
return [ratio, textBB, width + 'x' + height];
}
function fitTextInsideCircle(textBB, radius) {
// compute scaling ratio to have text fit within specified radius
var elRadius = Math.sqrt(textBB.width / 2 * (textBB.width / 2) + textBB.height * textBB.height);
var ratio = radius / elRadius;
return [ratio, textBB, radius];
}
function measureText(txt, font, textAnchor, gd) {
var element = document.createElementNS('http://www.w3.org/2000/svg', 'text');
var sel = d3.select(element);
sel.text(txt).attr('x', 0).attr('y', 0).attr('text-anchor', textAnchor).attr('data-unformatted', txt).call(svgTextUtils.convertToTspans, gd).call(Drawing.font, font);
return Drawing.bBox(sel.node());
}
function cache(trace, name, initialValue, value, key, fn) {
var objName = '_cache' + name;
if (!(trace[objName] && trace[objName].key === key)) {
trace[objName] = {
key: key,
value: initialValue
};
}
var v = Lib.aggNums(fn, null, [trace[objName].value, value], 2);
trace[objName].value = v;
return v;
}
/***/ }),
/***/ 50048:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorScaleAttrs = __webpack_require__(49084);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var meshAttrs = __webpack_require__(52948);
var baseAttrs = __webpack_require__(45464);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
function makeSliceAttr(axLetter) {
return {
show: {
valType: 'boolean',
dflt: false
},
locations: {
valType: 'data_array',
dflt: []
},
fill: {
valType: 'number',
min: 0,
max: 1,
dflt: 1
}
};
}
function makeCapAttr(axLetter) {
return {
show: {
valType: 'boolean',
dflt: true
},
fill: {
valType: 'number',
min: 0,
max: 1,
dflt: 1
}
};
}
var attrs = module.exports = overrideAll(extendFlat({
x: {
valType: 'data_array'
},
y: {
valType: 'data_array'
},
z: {
valType: 'data_array'
},
value: {
valType: 'data_array'
},
isomin: {
valType: 'number'
},
isomax: {
valType: 'number'
},
surface: {
show: {
valType: 'boolean',
dflt: true
},
count: {
valType: 'integer',
dflt: 2,
min: 1
},
fill: {
valType: 'number',
min: 0,
max: 1,
dflt: 1
},
pattern: {
valType: 'flaglist',
flags: ['A', 'B', 'C', 'D', 'E'],
extras: ['all', 'odd', 'even'],
dflt: 'all'
}
},
spaceframe: {
show: {
valType: 'boolean',
dflt: false
},
fill: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.15
}
},
slices: {
x: makeSliceAttr('x'),
y: makeSliceAttr('y'),
z: makeSliceAttr('z')
},
caps: {
x: makeCapAttr('x'),
y: makeCapAttr('y'),
z: makeCapAttr('z')
},
text: {
valType: 'string',
dflt: '',
arrayOk: true
},
hovertext: {
valType: 'string',
dflt: '',
arrayOk: true
},
hovertemplate: hovertemplateAttrs(),
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z'),
valuehoverformat: axisHoverFormat('value', 1),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
}, colorScaleAttrs('', {
colorAttr: '`value`',
showScaleDflt: true,
editTypeOverride: 'calc'
}), {
opacity: meshAttrs.opacity,
lightposition: meshAttrs.lightposition,
lighting: meshAttrs.lighting,
flatshading: meshAttrs.flatshading,
contour: meshAttrs.contour,
hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
}), 'calc', 'nested');
// required defaults to speed up surface normal calculations
attrs.flatshading.dflt = true;
attrs.lighting.facenormalsepsilon.dflt = 0;
attrs.x.editType = attrs.y.editType = attrs.z.editType = attrs.value.editType = 'calc+clearAxisTypes';
attrs.transforms = undefined;
/***/ }),
/***/ 62624:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorscaleCalc = __webpack_require__(47128);
var processGrid = (__webpack_require__(3832).processGrid);
var filter = (__webpack_require__(3832).filter);
module.exports = function calc(gd, trace) {
trace._len = Math.min(trace.x.length, trace.y.length, trace.z.length, trace.value.length);
trace._x = filter(trace.x, trace._len);
trace._y = filter(trace.y, trace._len);
trace._z = filter(trace.z, trace._len);
trace._value = filter(trace.value, trace._len);
var grid = processGrid(trace);
trace._gridFill = grid.fill;
trace._Xs = grid.Xs;
trace._Ys = grid.Ys;
trace._Zs = grid.Zs;
trace._len = grid.len;
var min = Infinity;
var max = -Infinity;
for (var i = 0; i < trace._len; i++) {
var v = trace._value[i];
min = Math.min(min, v);
max = Math.max(max, v);
}
trace._minValues = min;
trace._maxValues = max;
trace._vMin = trace.isomin === undefined || trace.isomin === null ? min : trace.isomin;
trace._vMax = trace.isomax === undefined || trace.isomax === null ? max : trace.isomax;
colorscaleCalc(gd, trace, {
vals: [trace._vMin, trace._vMax],
containerStr: '',
cLetter: 'c'
});
};
/***/ }),
/***/ 31460:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createMesh = (__webpack_require__(67792).gl_mesh3d);
var parseColorScale = (__webpack_require__(33040).parseColorScale);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var str2RgbaArray = __webpack_require__(43080);
var extractOpts = (__webpack_require__(8932).extractOpts);
var zip3 = __webpack_require__(52094);
var findNearestOnAxis = function (w, arr) {
for (var q = arr.length - 1; q > 0; q--) {
var min = Math.min(arr[q], arr[q - 1]);
var max = Math.max(arr[q], arr[q - 1]);
if (max > min && min < w && w <= max) {
return {
id: q,
distRatio: (max - w) / (max - min)
};
}
}
return {
id: 0,
distRatio: 0
};
};
function IsosurfaceTrace(scene, mesh, uid) {
this.scene = scene;
this.uid = uid;
this.mesh = mesh;
this.name = '';
this.data = null;
this.showContour = false;
}
var proto = IsosurfaceTrace.prototype;
proto.handlePick = function (selection) {
if (selection.object === this.mesh) {
var rawId = selection.data.index;
var x = this.data._meshX[rawId];
var y = this.data._meshY[rawId];
var z = this.data._meshZ[rawId];
var height = this.data._Ys.length;
var depth = this.data._Zs.length;
var i = findNearestOnAxis(x, this.data._Xs).id;
var j = findNearestOnAxis(y, this.data._Ys).id;
var k = findNearestOnAxis(z, this.data._Zs).id;
var selectIndex = selection.index = k + depth * j + depth * height * i;
selection.traceCoordinate = [this.data._meshX[selectIndex], this.data._meshY[selectIndex], this.data._meshZ[selectIndex], this.data._value[selectIndex]];
var text = this.data.hovertext || this.data.text;
if (isArrayOrTypedArray(text) && text[selectIndex] !== undefined) {
selection.textLabel = text[selectIndex];
} else if (text) {
selection.textLabel = text;
}
return true;
}
};
proto.update = function (data) {
var scene = this.scene;
var layout = scene.fullSceneLayout;
this.data = generateIsoMeshes(data);
// Unpack position data
function toDataCoords(axis, coord, scale, calendar) {
return coord.map(function (x) {
return axis.d2l(x, 0, calendar) * scale;
});
}
var positions = zip3(toDataCoords(layout.xaxis, data._meshX, scene.dataScale[0], data.xcalendar), toDataCoords(layout.yaxis, data._meshY, scene.dataScale[1], data.ycalendar), toDataCoords(layout.zaxis, data._meshZ, scene.dataScale[2], data.zcalendar));
var cells = zip3(data._meshI, data._meshJ, data._meshK);
var config = {
positions: positions,
cells: cells,
lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
ambient: data.lighting.ambient,
diffuse: data.lighting.diffuse,
specular: data.lighting.specular,
roughness: data.lighting.roughness,
fresnel: data.lighting.fresnel,
vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
faceNormalsEpsilon: data.lighting.facenormalsepsilon,
opacity: data.opacity,
contourEnable: data.contour.show,
contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
contourWidth: data.contour.width,
useFacetNormals: data.flatshading
};
var cOpts = extractOpts(data);
config.vertexIntensity = data._meshIntensity;
config.vertexIntensityBounds = [cOpts.min, cOpts.max];
config.colormap = parseColorScale(data);
// Update mesh
this.mesh.update(config);
};
proto.dispose = function () {
this.scene.glplot.remove(this.mesh);
this.mesh.dispose();
};
var GRID_TYPES = ['xyz', 'xzy', 'yxz', 'yzx', 'zxy', 'zyx'];
function generateIsoMeshes(data) {
data._meshI = [];
data._meshJ = [];
data._meshK = [];
var showSurface = data.surface.show;
var showSpaceframe = data.spaceframe.show;
var surfaceFill = data.surface.fill;
var spaceframeFill = data.spaceframe.fill;
var drawingSurface = false;
var drawingSpaceframe = false;
var numFaces = 0;
var numVertices;
var beginVertextLength;
var Xs = data._Xs;
var Ys = data._Ys;
var Zs = data._Zs;
var width = Xs.length;
var height = Ys.length;
var depth = Zs.length;
var filled = GRID_TYPES.indexOf(data._gridFill.replace(/-/g, '').replace(/\+/g, ''));
var getIndex = function (i, j, k) {
switch (filled) {
case 5:
// 'zyx'
return k + depth * j + depth * height * i;
case 4:
// 'zxy'
return k + depth * i + depth * width * j;
case 3:
// 'yzx'
return j + height * k + height * depth * i;
case 2:
// 'yxz'
return j + height * i + height * width * k;
case 1:
// 'xzy'
return i + width * k + width * depth * j;
default:
// case 0: // 'xyz'
return i + width * j + width * height * k;
}
};
var minValues = data._minValues;
var maxValues = data._maxValues;
var vMin = data._vMin;
var vMax = data._vMax;
var allXs;
var allYs;
var allZs;
var allVs;
function findVertexId(x, y, z) {
// could be used to find the vertex id of previously generated vertex within the group
var len = allVs.length;
for (var f = beginVertextLength; f < len; f++) {
if (x === allXs[f] && y === allYs[f] && z === allZs[f]) {
return f;
}
}
return -1;
}
function beginGroup() {
beginVertextLength = numVertices;
}
function emptyVertices() {
allXs = [];
allYs = [];
allZs = [];
allVs = [];
numVertices = 0;
beginGroup();
}
function addVertex(x, y, z, v) {
allXs.push(x);
allYs.push(y);
allZs.push(z);
allVs.push(v);
numVertices++;
return numVertices - 1;
}
function addFace(a, b, c) {
data._meshI.push(a);
data._meshJ.push(b);
data._meshK.push(c);
numFaces++;
return numFaces - 1;
}
function getCenter(A, B, C) {
var M = [];
for (var i = 0; i < A.length; i++) {
M[i] = (A[i] + B[i] + C[i]) / 3.0;
}
return M;
}
function getBetween(A, B, r) {
var M = [];
for (var i = 0; i < A.length; i++) {
M[i] = A[i] * (1 - r) + r * B[i];
}
return M;
}
var activeFill;
function setFill(fill) {
activeFill = fill;
}
function createOpenTri(xyzv, abc) {
var A = xyzv[0];
var B = xyzv[1];
var C = xyzv[2];
var G = getCenter(A, B, C);
var r = Math.sqrt(1 - activeFill);
var p1 = getBetween(G, A, r);
var p2 = getBetween(G, B, r);
var p3 = getBetween(G, C, r);
var a = abc[0];
var b = abc[1];
var c = abc[2];
return {
xyzv: [[A, B, p2], [p2, p1, A], [B, C, p3], [p3, p2, B], [C, A, p1], [p1, p3, C]],
abc: [[a, b, -1], [-1, -1, a], [b, c, -1], [-1, -1, b], [c, a, -1], [-1, -1, c]]
};
}
function styleIncludes(style, char) {
if (style === 'all' || style === null) return true;
return style.indexOf(char) > -1;
}
function mapValue(style, value) {
if (style === null) return value;
return style;
}
function drawTri(style, xyzv, abc) {
beginGroup();
var allXYZVs = [xyzv];
var allABCs = [abc];
if (activeFill >= 1) {
allXYZVs = [xyzv];
allABCs = [abc];
} else if (activeFill > 0) {
var openTri = createOpenTri(xyzv, abc);
allXYZVs = openTri.xyzv;
allABCs = openTri.abc;
}
for (var f = 0; f < allXYZVs.length; f++) {
xyzv = allXYZVs[f];
abc = allABCs[f];
var pnts = [];
for (var i = 0; i < 3; i++) {
var x = xyzv[i][0];
var y = xyzv[i][1];
var z = xyzv[i][2];
var v = xyzv[i][3];
var id = abc[i] > -1 ? abc[i] : findVertexId(x, y, z);
if (id > -1) {
pnts[i] = id;
} else {
pnts[i] = addVertex(x, y, z, mapValue(style, v));
}
}
addFace(pnts[0], pnts[1], pnts[2]);
}
}
function drawQuad(style, xyzv, abcd) {
var makeTri = function (i, j, k) {
drawTri(style, [xyzv[i], xyzv[j], xyzv[k]], [abcd[i], abcd[j], abcd[k]]);
};
makeTri(0, 1, 2);
makeTri(2, 3, 0);
}
function drawTetra(style, xyzv, abcd) {
var makeTri = function (i, j, k) {
drawTri(style, [xyzv[i], xyzv[j], xyzv[k]], [abcd[i], abcd[j], abcd[k]]);
};
makeTri(0, 1, 2);
makeTri(3, 0, 1);
makeTri(2, 3, 0);
makeTri(1, 2, 3);
}
function calcIntersection(pointOut, pointIn, min, max) {
var value = pointOut[3];
if (value < min) value = min;
if (value > max) value = max;
var ratio = (pointOut[3] - value) / (pointOut[3] - pointIn[3] + 0.000000001); // we had to add this error to force solve the tiny caps
var result = [];
for (var s = 0; s < 4; s++) {
result[s] = (1 - ratio) * pointOut[s] + ratio * pointIn[s];
}
return result;
}
function inRange(value, min, max) {
return value >= min && value <= max;
}
function almostInFinalRange(value) {
var vErr = 0.001 * (vMax - vMin);
return value >= vMin - vErr && value <= vMax + vErr;
}
function getXYZV(indecies) {
var xyzv = [];
for (var q = 0; q < 4; q++) {
var index = indecies[q];
xyzv.push([data._x[index], data._y[index], data._z[index], data._value[index]]);
}
return xyzv;
}
var MAX_PASS = 3;
function tryCreateTri(style, xyzv, abc, min, max, nPass) {
if (!nPass) nPass = 1;
abc = [-1, -1, -1]; // Note: for the moment we override indices
// to run faster! But it is possible to comment this line
// to reduce the number of vertices.
var result = false;
var ok = [inRange(xyzv[0][3], min, max), inRange(xyzv[1][3], min, max), inRange(xyzv[2][3], min, max)];
if (!ok[0] && !ok[1] && !ok[2]) {
return false;
}
var tryDrawTri = function (style, xyzv, abc) {
if (
// we check here if the points are in `real` iso-min/max range
almostInFinalRange(xyzv[0][3]) && almostInFinalRange(xyzv[1][3]) && almostInFinalRange(xyzv[2][3])) {
drawTri(style, xyzv, abc);
return true;
} else if (nPass < MAX_PASS) {
return tryCreateTri(style, xyzv, abc, vMin, vMax, ++nPass); // i.e. second pass using actual vMin vMax bounds
}
return false;
};
if (ok[0] && ok[1] && ok[2]) {
return tryDrawTri(style, xyzv, abc) || result;
}
var interpolated = false;
[[0, 1, 2], [2, 0, 1], [1, 2, 0]].forEach(function (e) {
if (ok[e[0]] && ok[e[1]] && !ok[e[2]]) {
var A = xyzv[e[0]];
var B = xyzv[e[1]];
var C = xyzv[e[2]];
var p1 = calcIntersection(C, A, min, max);
var p2 = calcIntersection(C, B, min, max);
result = tryDrawTri(style, [p2, p1, A], [-1, -1, abc[e[0]]]) || result;
result = tryDrawTri(style, [A, B, p2], [abc[e[0]], abc[e[1]], -1]) || result;
interpolated = true;
}
});
if (interpolated) return result;
[[0, 1, 2], [1, 2, 0], [2, 0, 1]].forEach(function (e) {
if (ok[e[0]] && !ok[e[1]] && !ok[e[2]]) {
var A = xyzv[e[0]];
var B = xyzv[e[1]];
var C = xyzv[e[2]];
var p1 = calcIntersection(B, A, min, max);
var p2 = calcIntersection(C, A, min, max);
result = tryDrawTri(style, [p2, p1, A], [-1, -1, abc[e[0]]]) || result;
interpolated = true;
}
});
return result;
}
function tryCreateTetra(style, abcd, min, max) {
var result = false;
var xyzv = getXYZV(abcd);
var ok = [inRange(xyzv[0][3], min, max), inRange(xyzv[1][3], min, max), inRange(xyzv[2][3], min, max), inRange(xyzv[3][3], min, max)];
if (!ok[0] && !ok[1] && !ok[2] && !ok[3]) {
return result;
}
if (ok[0] && ok[1] && ok[2] && ok[3]) {
if (drawingSpaceframe) {
result = drawTetra(style, xyzv, abcd) || result;
}
return result;
}
var interpolated = false;
[[0, 1, 2, 3], [3, 0, 1, 2], [2, 3, 0, 1], [1, 2, 3, 0]].forEach(function (e) {
if (ok[e[0]] && ok[e[1]] && ok[e[2]] && !ok[e[3]]) {
var A = xyzv[e[0]];
var B = xyzv[e[1]];
var C = xyzv[e[2]];
var D = xyzv[e[3]];
if (drawingSpaceframe) {
result = drawTri(style, [A, B, C], [abcd[e[0]], abcd[e[1]], abcd[e[2]]]) || result;
} else {
var p1 = calcIntersection(D, A, min, max);
var p2 = calcIntersection(D, B, min, max);
var p3 = calcIntersection(D, C, min, max);
result = drawTri(null, [p1, p2, p3], [-1, -1, -1]) || result;
}
interpolated = true;
}
});
if (interpolated) return result;
[[0, 1, 2, 3], [1, 2, 3, 0], [2, 3, 0, 1], [3, 0, 1, 2], [0, 2, 3, 1], [1, 3, 2, 0]].forEach(function (e) {
if (ok[e[0]] && ok[e[1]] && !ok[e[2]] && !ok[e[3]]) {
var A = xyzv[e[0]];
var B = xyzv[e[1]];
var C = xyzv[e[2]];
var D = xyzv[e[3]];
var p1 = calcIntersection(C, A, min, max);
var p2 = calcIntersection(C, B, min, max);
var p3 = calcIntersection(D, B, min, max);
var p4 = calcIntersection(D, A, min, max);
if (drawingSpaceframe) {
result = drawTri(style, [A, p4, p1], [abcd[e[0]], -1, -1]) || result;
result = drawTri(style, [B, p2, p3], [abcd[e[1]], -1, -1]) || result;
} else {
result = drawQuad(null, [p1, p2, p3, p4], [-1, -1, -1, -1]) || result;
}
interpolated = true;
}
});
if (interpolated) return result;
[[0, 1, 2, 3], [1, 2, 3, 0], [2, 3, 0, 1], [3, 0, 1, 2]].forEach(function (e) {
if (ok[e[0]] && !ok[e[1]] && !ok[e[2]] && !ok[e[3]]) {
var A = xyzv[e[0]];
var B = xyzv[e[1]];
var C = xyzv[e[2]];
var D = xyzv[e[3]];
var p1 = calcIntersection(B, A, min, max);
var p2 = calcIntersection(C, A, min, max);
var p3 = calcIntersection(D, A, min, max);
if (drawingSpaceframe) {
result = drawTri(style, [A, p1, p2], [abcd[e[0]], -1, -1]) || result;
result = drawTri(style, [A, p2, p3], [abcd[e[0]], -1, -1]) || result;
result = drawTri(style, [A, p3, p1], [abcd[e[0]], -1, -1]) || result;
} else {
result = drawTri(null, [p1, p2, p3], [-1, -1, -1]) || result;
}
interpolated = true;
}
});
return result;
}
function addCube(style, p000, p001, p010, p011, p100, p101, p110, p111, min, max) {
var result = false;
if (drawingSurface) {
if (styleIncludes(style, 'A')) {
result = tryCreateTetra(null, [p000, p001, p010, p100], min, max) || result;
}
if (styleIncludes(style, 'B')) {
result = tryCreateTetra(null, [p001, p010, p011, p111], min, max) || result;
}
if (styleIncludes(style, 'C')) {
result = tryCreateTetra(null, [p001, p100, p101, p111], min, max) || result;
}
if (styleIncludes(style, 'D')) {
result = tryCreateTetra(null, [p010, p100, p110, p111], min, max) || result;
}
if (styleIncludes(style, 'E')) {
result = tryCreateTetra(null, [p001, p010, p100, p111], min, max) || result;
}
}
if (drawingSpaceframe) {
result = tryCreateTetra(style, [p001, p010, p100, p111], min, max) || result;
}
return result;
}
function addRect(style, a, b, c, d, min, max, previousResult) {
return [previousResult[0] === true ? true : tryCreateTri(style, getXYZV([a, b, c]), [a, b, c], min, max), previousResult[1] === true ? true : tryCreateTri(style, getXYZV([c, d, a]), [c, d, a], min, max)];
}
function begin2dCell(style, p00, p01, p10, p11, min, max, isEven, previousResult) {
// used to create caps and/or slices on exact axis points
if (isEven) {
return addRect(style, p00, p01, p11, p10, min, max, previousResult);
} else {
return addRect(style, p01, p11, p10, p00, min, max, previousResult);
}
}
function beginSection(style, i, j, k, min, max, distRatios) {
// used to create slices between axis points
var result = false;
var A, B, C, D;
var makeSection = function () {
result = tryCreateTri(style, [A, B, C], [-1, -1, -1], min, max) || result;
result = tryCreateTri(style, [C, D, A], [-1, -1, -1], min, max) || result;
};
var rX = distRatios[0];
var rY = distRatios[1];
var rZ = distRatios[2];
if (rX) {
A = getBetween(getXYZV([getIndex(i, j - 0, k - 0)])[0], getXYZV([getIndex(i - 1, j - 0, k - 0)])[0], rX);
B = getBetween(getXYZV([getIndex(i, j - 0, k - 1)])[0], getXYZV([getIndex(i - 1, j - 0, k - 1)])[0], rX);
C = getBetween(getXYZV([getIndex(i, j - 1, k - 1)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rX);
D = getBetween(getXYZV([getIndex(i, j - 1, k - 0)])[0], getXYZV([getIndex(i - 1, j - 1, k - 0)])[0], rX);
makeSection();
}
if (rY) {
A = getBetween(getXYZV([getIndex(i - 0, j, k - 0)])[0], getXYZV([getIndex(i - 0, j - 1, k - 0)])[0], rY);
B = getBetween(getXYZV([getIndex(i - 0, j, k - 1)])[0], getXYZV([getIndex(i - 0, j - 1, k - 1)])[0], rY);
C = getBetween(getXYZV([getIndex(i - 1, j, k - 1)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rY);
D = getBetween(getXYZV([getIndex(i - 1, j, k - 0)])[0], getXYZV([getIndex(i - 1, j - 1, k - 0)])[0], rY);
makeSection();
}
if (rZ) {
A = getBetween(getXYZV([getIndex(i - 0, j - 0, k)])[0], getXYZV([getIndex(i - 0, j - 0, k - 1)])[0], rZ);
B = getBetween(getXYZV([getIndex(i - 0, j - 1, k)])[0], getXYZV([getIndex(i - 0, j - 1, k - 1)])[0], rZ);
C = getBetween(getXYZV([getIndex(i - 1, j - 1, k)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rZ);
D = getBetween(getXYZV([getIndex(i - 1, j - 0, k)])[0], getXYZV([getIndex(i - 1, j - 0, k - 1)])[0], rZ);
makeSection();
}
return result;
}
function begin3dCell(style, p000, p001, p010, p011, p100, p101, p110, p111, min, max, isEven) {
// used to create spaceframe and/or iso-surfaces
var cellStyle = style;
if (isEven) {
if (drawingSurface && style === 'even') cellStyle = null;
return addCube(cellStyle, p000, p001, p010, p011, p100, p101, p110, p111, min, max);
} else {
if (drawingSurface && style === 'odd') cellStyle = null;
return addCube(cellStyle, p111, p110, p101, p100, p011, p010, p001, p000, min, max);
}
}
function draw2dX(style, items, min, max, previousResult) {
var result = [];
var n = 0;
for (var q = 0; q < items.length; q++) {
var i = items[q];
for (var k = 1; k < depth; k++) {
for (var j = 1; j < height; j++) {
result.push(begin2dCell(style, getIndex(i, j - 1, k - 1), getIndex(i, j - 1, k), getIndex(i, j, k - 1), getIndex(i, j, k), min, max, (i + j + k) % 2, previousResult && previousResult[n] ? previousResult[n] : []));
n++;
}
}
}
return result;
}
function draw2dY(style, items, min, max, previousResult) {
var result = [];
var n = 0;
for (var q = 0; q < items.length; q++) {
var j = items[q];
for (var i = 1; i < width; i++) {
for (var k = 1; k < depth; k++) {
result.push(begin2dCell(style, getIndex(i - 1, j, k - 1), getIndex(i, j, k - 1), getIndex(i - 1, j, k), getIndex(i, j, k), min, max, (i + j + k) % 2, previousResult && previousResult[n] ? previousResult[n] : []));
n++;
}
}
}
return result;
}
function draw2dZ(style, items, min, max, previousResult) {
var result = [];
var n = 0;
for (var q = 0; q < items.length; q++) {
var k = items[q];
for (var j = 1; j < height; j++) {
for (var i = 1; i < width; i++) {
result.push(begin2dCell(style, getIndex(i - 1, j - 1, k), getIndex(i - 1, j, k), getIndex(i, j - 1, k), getIndex(i, j, k), min, max, (i + j + k) % 2, previousResult && previousResult[n] ? previousResult[n] : []));
n++;
}
}
}
return result;
}
function draw3d(style, min, max) {
for (var k = 1; k < depth; k++) {
for (var j = 1; j < height; j++) {
for (var i = 1; i < width; i++) {
begin3dCell(style, getIndex(i - 1, j - 1, k - 1), getIndex(i - 1, j - 1, k), getIndex(i - 1, j, k - 1), getIndex(i - 1, j, k), getIndex(i, j - 1, k - 1), getIndex(i, j - 1, k), getIndex(i, j, k - 1), getIndex(i, j, k), min, max, (i + j + k) % 2);
}
}
}
}
function drawSpaceframe(style, min, max) {
drawingSpaceframe = true;
draw3d(style, min, max);
drawingSpaceframe = false;
}
function drawSurface(style, min, max) {
drawingSurface = true;
draw3d(style, min, max);
drawingSurface = false;
}
function drawSectionX(style, items, min, max, distRatios, previousResult) {
var result = [];
var n = 0;
for (var q = 0; q < items.length; q++) {
var i = items[q];
for (var k = 1; k < depth; k++) {
for (var j = 1; j < height; j++) {
result.push(beginSection(style, i, j, k, min, max, distRatios[q], previousResult && previousResult[n] ? previousResult[n] : []));
n++;
}
}
}
return result;
}
function drawSectionY(style, items, min, max, distRatios, previousResult) {
var result = [];
var n = 0;
for (var q = 0; q < items.length; q++) {
var j = items[q];
for (var i = 1; i < width; i++) {
for (var k = 1; k < depth; k++) {
result.push(beginSection(style, i, j, k, min, max, distRatios[q], previousResult && previousResult[n] ? previousResult[n] : []));
n++;
}
}
}
return result;
}
function drawSectionZ(style, items, min, max, distRatios, previousResult) {
var result = [];
var n = 0;
for (var q = 0; q < items.length; q++) {
var k = items[q];
for (var j = 1; j < height; j++) {
for (var i = 1; i < width; i++) {
result.push(beginSection(style, i, j, k, min, max, distRatios[q], previousResult && previousResult[n] ? previousResult[n] : []));
n++;
}
}
}
return result;
}
function createRange(a, b) {
var range = [];
for (var q = a; q < b; q++) {
range.push(q);
}
return range;
}
function insertGridPoints() {
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
for (var k = 0; k < depth; k++) {
var index = getIndex(i, j, k);
addVertex(data._x[index], data._y[index], data._z[index], data._value[index]);
}
}
}
}
function drawAll() {
emptyVertices();
// insert grid points
insertGridPoints();
var activeStyle = null;
// draw spaceframes
if (showSpaceframe && spaceframeFill) {
setFill(spaceframeFill);
drawSpaceframe(activeStyle, vMin, vMax);
}
// draw iso-surfaces
if (showSurface && surfaceFill) {
setFill(surfaceFill);
var surfacePattern = data.surface.pattern;
var surfaceCount = data.surface.count;
for (var q = 0; q < surfaceCount; q++) {
var ratio = surfaceCount === 1 ? 0.5 : q / (surfaceCount - 1);
var level = (1 - ratio) * vMin + ratio * vMax;
var d1 = Math.abs(level - minValues);
var d2 = Math.abs(level - maxValues);
var ranges = d1 > d2 ? [minValues, level] : [level, maxValues];
drawSurface(surfacePattern, ranges[0], ranges[1]);
}
}
var setupMinMax = [[Math.min(vMin, maxValues), Math.max(vMin, maxValues)], [Math.min(minValues, vMax), Math.max(minValues, vMax)]];
['x', 'y', 'z'].forEach(function (e) {
var preRes = [];
for (var s = 0; s < setupMinMax.length; s++) {
var count = 0;
var activeMin = setupMinMax[s][0];
var activeMax = setupMinMax[s][1];
// draw slices
var slice = data.slices[e];
if (slice.show && slice.fill) {
setFill(slice.fill);
var exactIndices = [];
var ceilIndices = [];
var distRatios = [];
if (slice.locations.length) {
for (var q = 0; q < slice.locations.length; q++) {
var near = findNearestOnAxis(slice.locations[q], e === 'x' ? Xs : e === 'y' ? Ys : Zs);
if (near.distRatio === 0) {
exactIndices.push(near.id);
} else if (near.id > 0) {
ceilIndices.push(near.id);
if (e === 'x') {
distRatios.push([near.distRatio, 0, 0]);
} else if (e === 'y') {
distRatios.push([0, near.distRatio, 0]);
} else {
distRatios.push([0, 0, near.distRatio]);
}
}
}
} else {
if (e === 'x') {
exactIndices = createRange(1, width - 1);
} else if (e === 'y') {
exactIndices = createRange(1, height - 1);
} else {
exactIndices = createRange(1, depth - 1);
}
}
if (ceilIndices.length > 0) {
if (e === 'x') {
preRes[count] = drawSectionX(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
} else if (e === 'y') {
preRes[count] = drawSectionY(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
} else {
preRes[count] = drawSectionZ(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
}
count++;
}
if (exactIndices.length > 0) {
if (e === 'x') {
preRes[count] = draw2dX(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
} else if (e === 'y') {
preRes[count] = draw2dY(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
} else {
preRes[count] = draw2dZ(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
}
count++;
}
}
// draw caps
var cap = data.caps[e];
if (cap.show && cap.fill) {
setFill(cap.fill);
if (e === 'x') {
preRes[count] = draw2dX(activeStyle, [0, width - 1], activeMin, activeMax, preRes[count]);
} else if (e === 'y') {
preRes[count] = draw2dY(activeStyle, [0, height - 1], activeMin, activeMax, preRes[count]);
} else {
preRes[count] = draw2dZ(activeStyle, [0, depth - 1], activeMin, activeMax, preRes[count]);
}
count++;
}
}
});
// remove vertices arrays (i.e. grid points) in case no face was created.
if (numFaces === 0) {
emptyVertices();
}
data._meshX = allXs;
data._meshY = allYs;
data._meshZ = allZs;
data._meshIntensity = allVs;
data._Xs = Xs;
data._Ys = Ys;
data._Zs = Zs;
}
drawAll();
return data;
}
function createIsosurfaceTrace(scene, data) {
var gl = scene.glplot.gl;
var mesh = createMesh({
gl: gl
});
var result = new IsosurfaceTrace(scene, mesh, data.uid);
mesh._trace = result;
result.update(data);
scene.glplot.add(mesh);
return result;
}
module.exports = {
findNearestOnAxis: findNearestOnAxis,
generateIsoMeshes: generateIsoMeshes,
createIsosurfaceTrace: createIsosurfaceTrace
};
/***/ }),
/***/ 70548:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var attributes = __webpack_require__(50048);
var colorscaleDefaults = __webpack_require__(27260);
function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
supplyIsoDefaults(traceIn, traceOut, defaultColor, layout, coerce);
}
function supplyIsoDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
var isomin = coerce('isomin');
var isomax = coerce('isomax');
if (isomax !== undefined && isomax !== null && isomin !== undefined && isomin !== null && isomin > isomax) {
// applying default values in this case:
traceOut.isomin = null;
traceOut.isomax = null;
}
var x = coerce('x');
var y = coerce('y');
var z = coerce('z');
var value = coerce('value');
if (!x || !x.length || !y || !y.length || !z || !z.length || !value || !value.length) {
traceOut.visible = false;
return;
}
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);
coerce('valuehoverformat');
['x', 'y', 'z'].forEach(function (dim) {
coerce(dim + 'hoverformat');
var capDim = 'caps.' + dim;
var showCap = coerce(capDim + '.show');
if (showCap) {
coerce(capDim + '.fill');
}
var sliceDim = 'slices.' + dim;
var showSlice = coerce(sliceDim + '.show');
if (showSlice) {
coerce(sliceDim + '.fill');
coerce(sliceDim + '.locations');
}
});
var showSpaceframe = coerce('spaceframe.show');
if (showSpaceframe) {
coerce('spaceframe.fill');
}
var showSurface = coerce('surface.show');
if (showSurface) {
coerce('surface.count');
coerce('surface.fill');
coerce('surface.pattern');
}
var showContour = coerce('contour.show');
if (showContour) {
coerce('contour.color');
coerce('contour.width');
}
// Coerce remaining properties
['text', 'hovertext', 'hovertemplate', 'lighting.ambient', 'lighting.diffuse', 'lighting.specular', 'lighting.roughness', 'lighting.fresnel', 'lighting.vertexnormalsepsilon', 'lighting.facenormalsepsilon', 'lightposition.x', 'lightposition.y', 'lightposition.z', 'flatshading', 'opacity'].forEach(function (x) {
coerce(x);
});
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'c'
});
// disable 1D transforms (for now)
traceOut._length = null;
}
module.exports = {
supplyDefaults: supplyDefaults,
supplyIsoDefaults: supplyIsoDefaults
};
/***/ }),
/***/ 6296:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(50048),
supplyDefaults: (__webpack_require__(70548).supplyDefaults),
calc: __webpack_require__(62624),
colorbar: {
min: 'cmin',
max: 'cmax'
},
plot: (__webpack_require__(31460).createIsosurfaceTrace),
moduleType: 'trace',
name: 'isosurface',
basePlotModule: __webpack_require__(12536),
categories: ['gl3d', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 52948:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorScaleAttrs = __webpack_require__(49084);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var surfaceAttrs = __webpack_require__(16716);
var baseAttrs = __webpack_require__(45464);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = extendFlat({
x: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
y: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
z: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
i: {
valType: 'data_array',
editType: 'calc'
},
j: {
valType: 'data_array',
editType: 'calc'
},
k: {
valType: 'data_array',
editType: 'calc'
},
text: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'calc'
},
hovertext: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'calc'
},
hovertemplate: hovertemplateAttrs({
editType: 'calc'
}),
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z'),
delaunayaxis: {
valType: 'enumerated',
values: ['x', 'y', 'z'],
dflt: 'z',
editType: 'calc'
},
alphahull: {
valType: 'number',
dflt: -1,
editType: 'calc'
},
intensity: {
valType: 'data_array',
editType: 'calc'
},
intensitymode: {
valType: 'enumerated',
values: ['vertex', 'cell'],
dflt: 'vertex',
editType: 'calc'
},
// Color field
color: {
valType: 'color',
editType: 'calc'
},
vertexcolor: {
valType: 'data_array',
editType: 'calc'
},
facecolor: {
valType: 'data_array',
editType: 'calc'
},
transforms: undefined
}, colorScaleAttrs('', {
colorAttr: '`intensity`',
showScaleDflt: true,
editTypeOverride: 'calc'
}), {
opacity: surfaceAttrs.opacity,
// Flat shaded mode
flatshading: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
contour: {
show: extendFlat({}, surfaceAttrs.contours.x.show, {}),
color: surfaceAttrs.contours.x.color,
width: surfaceAttrs.contours.x.width,
editType: 'calc'
},
lightposition: {
x: extendFlat({}, surfaceAttrs.lightposition.x, {
dflt: 1e5
}),
y: extendFlat({}, surfaceAttrs.lightposition.y, {
dflt: 1e5
}),
z: extendFlat({}, surfaceAttrs.lightposition.z, {
dflt: 0
}),
editType: 'calc'
},
lighting: extendFlat({
vertexnormalsepsilon: {
valType: 'number',
min: 0.00,
max: 1,
dflt: 1e-12,
// otherwise finely tessellated things eg. the brain will have no specular light reflection
editType: 'calc'
},
facenormalsepsilon: {
valType: 'number',
min: 0.00,
max: 1,
dflt: 1e-6,
// even the brain model doesn't appear to need finer than this
editType: 'calc'
},
editType: 'calc'
}, surfaceAttrs.lighting),
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
editType: 'calc'
}),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
});
/***/ }),
/***/ 1876:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorscaleCalc = __webpack_require__(47128);
module.exports = function calc(gd, trace) {
if (trace.intensity) {
colorscaleCalc(gd, trace, {
vals: trace.intensity,
containerStr: '',
cLetter: 'c'
});
}
};
/***/ }),
/***/ 576:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createMesh = (__webpack_require__(67792).gl_mesh3d);
var triangulate = (__webpack_require__(67792).delaunay_triangulate);
var alphaShape = (__webpack_require__(67792).alpha_shape);
var convexHull = (__webpack_require__(67792).convex_hull);
var parseColorScale = (__webpack_require__(33040).parseColorScale);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var str2RgbaArray = __webpack_require__(43080);
var extractOpts = (__webpack_require__(8932).extractOpts);
var zip3 = __webpack_require__(52094);
function Mesh3DTrace(scene, mesh, uid) {
this.scene = scene;
this.uid = uid;
this.mesh = mesh;
this.name = '';
this.color = '#fff';
this.data = null;
this.showContour = false;
}
var proto = Mesh3DTrace.prototype;
proto.handlePick = function (selection) {
if (selection.object === this.mesh) {
var selectIndex = selection.index = selection.data.index;
if (selection.data._cellCenter) {
selection.traceCoordinate = selection.data.dataCoordinate;
} else {
selection.traceCoordinate = [this.data.x[selectIndex], this.data.y[selectIndex], this.data.z[selectIndex]];
}
var text = this.data.hovertext || this.data.text;
if (isArrayOrTypedArray(text) && text[selectIndex] !== undefined) {
selection.textLabel = text[selectIndex];
} else if (text) {
selection.textLabel = text;
}
return true;
}
};
function parseColorArray(colors) {
var b = [];
var len = colors.length;
for (var i = 0; i < len; i++) {
b[i] = str2RgbaArray(colors[i]);
}
return b;
}
// Unpack position data
function toDataCoords(axis, coord, scale, calendar) {
var b = [];
var len = coord.length;
for (var i = 0; i < len; i++) {
b[i] = axis.d2l(coord[i], 0, calendar) * scale;
}
return b;
}
// Round indices if passed as floats
function toRoundIndex(a) {
var b = [];
var len = a.length;
for (var i = 0; i < len; i++) {
b[i] = Math.round(a[i]);
}
return b;
}
function delaunayCells(delaunayaxis, positions) {
var d = ['x', 'y', 'z'].indexOf(delaunayaxis);
var b = [];
var len = positions.length;
for (var i = 0; i < len; i++) {
b[i] = [positions[i][(d + 1) % 3], positions[i][(d + 2) % 3]];
}
return triangulate(b);
}
// Validate indices
function hasValidIndices(list, numVertices) {
var len = list.length;
for (var i = 0; i < len; i++) {
if (list[i] <= -0.5 || list[i] >= numVertices - 0.5) {
// Note: the indices would be rounded -0.49 is valid.
return false;
}
}
return true;
}
proto.update = function (data) {
var scene = this.scene;
var layout = scene.fullSceneLayout;
this.data = data;
var numVertices = data.x.length;
var positions = zip3(toDataCoords(layout.xaxis, data.x, scene.dataScale[0], data.xcalendar), toDataCoords(layout.yaxis, data.y, scene.dataScale[1], data.ycalendar), toDataCoords(layout.zaxis, data.z, scene.dataScale[2], data.zcalendar));
var cells;
if (data.i && data.j && data.k) {
if (data.i.length !== data.j.length || data.j.length !== data.k.length || !hasValidIndices(data.i, numVertices) || !hasValidIndices(data.j, numVertices) || !hasValidIndices(data.k, numVertices)) {
return;
}
cells = zip3(toRoundIndex(data.i), toRoundIndex(data.j), toRoundIndex(data.k));
} else if (data.alphahull === 0) {
cells = convexHull(positions);
} else if (data.alphahull > 0) {
cells = alphaShape(data.alphahull, positions);
} else {
cells = delaunayCells(data.delaunayaxis, positions);
}
var config = {
positions: positions,
cells: cells,
lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
ambient: data.lighting.ambient,
diffuse: data.lighting.diffuse,
specular: data.lighting.specular,
roughness: data.lighting.roughness,
fresnel: data.lighting.fresnel,
vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
faceNormalsEpsilon: data.lighting.facenormalsepsilon,
opacity: data.opacity,
contourEnable: data.contour.show,
contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
contourWidth: data.contour.width,
useFacetNormals: data.flatshading
};
if (data.intensity) {
var cOpts = extractOpts(data);
this.color = '#fff';
var mode = data.intensitymode;
config[mode + 'Intensity'] = data.intensity;
config[mode + 'IntensityBounds'] = [cOpts.min, cOpts.max];
config.colormap = parseColorScale(data);
} else if (data.vertexcolor) {
this.color = data.vertexcolor[0];
config.vertexColors = parseColorArray(data.vertexcolor);
} else if (data.facecolor) {
this.color = data.facecolor[0];
config.cellColors = parseColorArray(data.facecolor);
} else {
this.color = data.color;
config.meshColor = str2RgbaArray(data.color);
}
// Update mesh
this.mesh.update(config);
};
proto.dispose = function () {
this.scene.glplot.remove(this.mesh);
this.mesh.dispose();
};
function createMesh3DTrace(scene, data) {
var gl = scene.glplot.gl;
var mesh = createMesh({
gl: gl
});
var result = new Mesh3DTrace(scene, mesh, data.uid);
mesh._trace = result;
result.update(data);
scene.glplot.add(mesh);
return result;
}
module.exports = createMesh3DTrace;
/***/ }),
/***/ 74212:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(52948);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
// read in face/vertex properties
function readComponents(array) {
var ret = array.map(function (attr) {
var result = coerce(attr);
if (result && Lib.isArrayOrTypedArray(result)) return result;
return null;
});
return ret.every(function (x) {
return x && x.length === ret[0].length;
}) && ret;
}
var coords = readComponents(['x', 'y', 'z']);
if (!coords) {
traceOut.visible = false;
return;
}
readComponents(['i', 'j', 'k']);
// three indices should be all provided or not
if (traceOut.i && (!traceOut.j || !traceOut.k) || traceOut.j && (!traceOut.k || !traceOut.i) || traceOut.k && (!traceOut.i || !traceOut.j)) {
traceOut.visible = false;
return;
}
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);
// Coerce remaining properties
['lighting.ambient', 'lighting.diffuse', 'lighting.specular', 'lighting.roughness', 'lighting.fresnel', 'lighting.vertexnormalsepsilon', 'lighting.facenormalsepsilon', 'lightposition.x', 'lightposition.y', 'lightposition.z', 'flatshading', 'alphahull', 'delaunayaxis', 'opacity'].forEach(function (x) {
coerce(x);
});
var showContour = coerce('contour.show');
if (showContour) {
coerce('contour.color');
coerce('contour.width');
}
if ('intensity' in traceIn) {
coerce('intensity');
coerce('intensitymode');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'c'
});
} else {
traceOut.showscale = false;
if ('facecolor' in traceIn) coerce('facecolor');else if ('vertexcolor' in traceIn) coerce('vertexcolor');else coerce('color', defaultColor);
}
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
coerce('xhoverformat');
coerce('yhoverformat');
coerce('zhoverformat');
// disable 1D transforms
// x/y/z should match lengths, and i/j/k should match as well, but
// the two sets have different lengths so transforms wouldn't work.
traceOut._length = null;
};
/***/ }),
/***/ 7404:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(52948),
supplyDefaults: __webpack_require__(74212),
calc: __webpack_require__(1876),
colorbar: {
min: 'cmin',
max: 'cmax'
},
plot: __webpack_require__(576),
moduleType: 'trace',
name: 'mesh3d',
basePlotModule: __webpack_require__(12536),
categories: ['gl3d', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 20279:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var extendFlat = (__webpack_require__(3400).extendFlat);
var scatterAttrs = __webpack_require__(52904);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var fxAttrs = __webpack_require__(55756);
var delta = __webpack_require__(48164);
var INCREASING_COLOR = delta.INCREASING.COLOR;
var DECREASING_COLOR = delta.DECREASING.COLOR;
var lineAttrs = scatterAttrs.line;
function directionAttrs(lineColorDefault) {
return {
line: {
color: extendFlat({}, lineAttrs.color, {
dflt: lineColorDefault
}),
width: lineAttrs.width,
dash: dash,
editType: 'style'
},
editType: 'style'
};
}
module.exports = {
xperiod: scatterAttrs.xperiod,
xperiod0: scatterAttrs.xperiod0,
xperiodalignment: scatterAttrs.xperiodalignment,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
x: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
open: {
valType: 'data_array',
editType: 'calc'
},
high: {
valType: 'data_array',
editType: 'calc'
},
low: {
valType: 'data_array',
editType: 'calc'
},
close: {
valType: 'data_array',
editType: 'calc'
},
line: {
width: extendFlat({}, lineAttrs.width, {}),
dash: extendFlat({}, dash, {}),
editType: 'style'
},
increasing: directionAttrs(INCREASING_COLOR),
decreasing: directionAttrs(DECREASING_COLOR),
text: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'calc'
},
hovertext: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'calc'
},
tickwidth: {
valType: 'number',
min: 0,
max: 0.5,
dflt: 0.3,
editType: 'calc'
},
hoverlabel: extendFlat({}, fxAttrs.hoverlabel, {
split: {
valType: 'boolean',
dflt: false,
editType: 'style'
}
}),
zorder: scatterAttrs.zorder
};
/***/ }),
/***/ 42812:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var _ = Lib._;
var Axes = __webpack_require__(54460);
var alignPeriod = __webpack_require__(1220);
var BADNUM = (__webpack_require__(39032).BADNUM);
function calc(gd, trace) {
var xa = Axes.getFromId(gd, trace.xaxis);
var ya = Axes.getFromId(gd, trace.yaxis);
var tickLen = convertTickWidth(gd, xa, trace);
var minDiff = trace._minDiff;
trace._minDiff = null;
var origX = trace._origX;
trace._origX = null;
var x = trace._xcalc;
trace._xcalc = null;
var cd = calcCommon(gd, trace, origX, x, ya, ptFunc);
trace._extremes[xa._id] = Axes.findExtremes(xa, x, {
vpad: minDiff / 2
});
if (cd.length) {
Lib.extendFlat(cd[0].t, {
wHover: minDiff / 2,
tickLen: tickLen
});
return cd;
} else {
return [{
t: {
empty: true
}
}];
}
}
function ptFunc(o, h, l, c) {
return {
o: o,
h: h,
l: l,
c: c
};
}
// shared between OHLC and candlestick
// ptFunc makes a calcdata point specific to each trace type, from oi, hi, li, ci
function calcCommon(gd, trace, origX, x, ya, ptFunc) {
var o = ya.makeCalcdata(trace, 'open');
var h = ya.makeCalcdata(trace, 'high');
var l = ya.makeCalcdata(trace, 'low');
var c = ya.makeCalcdata(trace, 'close');
var hasTextArray = Lib.isArrayOrTypedArray(trace.text);
var hasHovertextArray = Lib.isArrayOrTypedArray(trace.hovertext);
// we're optimists - before we have any changing data, assume increasing
var increasing = true;
var cPrev = null;
var hasPeriod = !!trace.xperiodalignment;
var cd = [];
for (var i = 0; i < x.length; i++) {
var xi = x[i];
var oi = o[i];
var hi = h[i];
var li = l[i];
var ci = c[i];
if (xi !== BADNUM && oi !== BADNUM && hi !== BADNUM && li !== BADNUM && ci !== BADNUM) {
if (ci === oi) {
// if open == close, look for a change from the previous close
if (cPrev !== null && ci !== cPrev) increasing = ci > cPrev;
// else (c === cPrev or cPrev is null) no change
} else increasing = ci > oi;
cPrev = ci;
var pt = ptFunc(oi, hi, li, ci);
pt.pos = xi;
pt.yc = (oi + ci) / 2;
pt.i = i;
pt.dir = increasing ? 'increasing' : 'decreasing';
// For categoryorder, store low and high
pt.x = pt.pos;
pt.y = [li, hi];
if (hasPeriod) pt.orig_p = origX[i]; // used by hover
if (hasTextArray) pt.tx = trace.text[i];
if (hasHovertextArray) pt.htx = trace.hovertext[i];
cd.push(pt);
} else {
cd.push({
pos: xi,
empty: true
});
}
}
trace._extremes[ya._id] = Axes.findExtremes(ya, Lib.concat(l, h), {
padded: true
});
if (cd.length) {
cd[0].t = {
labels: {
open: _(gd, 'open:') + ' ',
high: _(gd, 'high:') + ' ',
low: _(gd, 'low:') + ' ',
close: _(gd, 'close:') + ' '
}
};
}
return cd;
}
/*
* find min x-coordinates difference of all traces
* attached to this x-axis and stash the result in _minDiff
* in all traces; when a trace uses this in its
* calc step it deletes _minDiff, so that next calc this is
* done again in case the data changed.
* also since we need it here, stash _xcalc (and _origX) on the trace
*/
function convertTickWidth(gd, xa, trace) {
var minDiff = trace._minDiff;
if (!minDiff) {
var fullData = gd._fullData;
var ohlcTracesOnThisXaxis = [];
minDiff = Infinity;
var i;
for (i = 0; i < fullData.length; i++) {
var tracei = fullData[i];
if (tracei.type === 'ohlc' && tracei.visible === true && tracei.xaxis === xa._id) {
ohlcTracesOnThisXaxis.push(tracei);
var origX = xa.makeCalcdata(tracei, 'x');
tracei._origX = origX;
var xcalc = alignPeriod(trace, xa, 'x', origX).vals;
tracei._xcalc = xcalc;
var _minDiff = Lib.distinctVals(xcalc).minDiff;
if (_minDiff && isFinite(_minDiff)) {
minDiff = Math.min(minDiff, _minDiff);
}
}
}
// if minDiff is still Infinity here, set it to 1
if (minDiff === Infinity) minDiff = 1;
for (i = 0; i < ohlcTracesOnThisXaxis.length; i++) {
ohlcTracesOnThisXaxis[i]._minDiff = minDiff;
}
}
return minDiff * trace.tickwidth;
}
module.exports = {
calc: calc,
calcCommon: calcCommon
};
/***/ }),
/***/ 23860:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleOHLC = __webpack_require__(52744);
var handlePeriodDefaults = __webpack_require__(31147);
var attributes = __webpack_require__(20279);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleOHLC(traceIn, traceOut, coerce, layout);
if (!len) {
traceOut.visible = false;
return;
}
handlePeriodDefaults(traceIn, traceOut, layout, coerce, {
x: true
});
coerce('xhoverformat');
coerce('yhoverformat');
coerce('line.width');
coerce('line.dash');
handleDirection(traceIn, traceOut, coerce, 'increasing');
handleDirection(traceIn, traceOut, coerce, 'decreasing');
coerce('text');
coerce('hovertext');
coerce('tickwidth');
layout._requestRangeslider[traceOut.xaxis] = true;
coerce('zorder');
};
function handleDirection(traceIn, traceOut, coerce, direction) {
coerce(direction + '.line.color');
coerce(direction + '.line.width', traceOut.line.width);
coerce(direction + '.line.dash', traceOut.line.dash);
}
/***/ }),
/***/ 18720:
/***/ (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 = (__webpack_require__(3400).fillText);
var delta = __webpack_require__(48164);
var DIRSYMBOL = {
increasing: delta.INCREASING.SYMBOL,
decreasing: delta.DECREASING.SYMBOL
};
function hoverPoints(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var trace = cd[0].trace;
if (trace.hoverlabel.split) {
return hoverSplit(pointData, xval, yval, hovermode);
}
return hoverOnPoints(pointData, xval, yval, hovermode);
}
function _getClosestPoint(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var xa = pointData.xa;
var trace = cd[0].trace;
var t = cd[0].t;
var type = trace.type;
var minAttr = type === 'ohlc' ? 'l' : 'min';
var maxAttr = type === 'ohlc' ? 'h' : 'max';
var hoverPseudoDistance, spikePseudoDistance;
// potentially shift xval for grouped candlesticks
var centerShift = t.bPos || 0;
var shiftPos = function (di) {
return di.pos + centerShift - xval;
};
// ohlc and candlestick call displayHalfWidth different things...
var displayHalfWidth = t.bdPos || t.tickLen;
var hoverHalfWidth = t.wHover;
// if two figures are overlaying, let the narrowest one win
var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0])));
hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;
function dx(di) {
var pos = shiftPos(di);
return Fx.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance);
}
function dy(di) {
var min = di[minAttr];
var max = di[maxAttr];
return min === max || Fx.inbox(min - yval, max - yval, hoverPseudoDistance);
}
function dxy(di) {
return (dx(di) + dy(di)) / 2;
}
var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
Fx.getClosest(cd, distfn, pointData);
if (pointData.index === false) return null;
var di = cd[pointData.index];
if (di.empty) return null;
var dir = di.dir;
var container = trace[dir];
var lc = container.line.color;
if (Color.opacity(lc) && container.line.width) pointData.color = lc;else pointData.color = container.fillcolor;
pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true);
pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true);
pointData.xLabelVal = di.orig_p !== undefined ? di.orig_p : di.pos;
pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
pointData.xSpike = xa.c2p(di.pos, true);
return pointData;
}
function hoverSplit(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var ya = pointData.ya;
var trace = cd[0].trace;
var t = cd[0].t;
var closeBoxData = [];
var closestPoint = _getClosestPoint(pointData, xval, yval, hovermode);
// skip the rest (for this trace) if we didn't find a close point
if (!closestPoint) return [];
var cdIndex = closestPoint.index;
var di = cd[cdIndex];
var hoverinfo = di.hi || trace.hoverinfo;
var hoverParts = hoverinfo.split('+');
var isAll = hoverinfo === 'all';
var hasY = isAll || hoverParts.indexOf('y') !== -1;
// similar to hoverOnPoints, we return nothing
// if all or y is not present.
if (!hasY) return [];
var attrs = ['high', 'open', 'close', 'low'];
// several attributes can have the same y-coordinate. We will
// bunch them together in a single text block. For this, we keep
// a dictionary mapping y-coord -> point data.
var usedVals = {};
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
var val = trace[attr][closestPoint.index];
var valPx = ya.c2p(val, true);
var pointData2;
if (val in usedVals) {
pointData2 = usedVals[val];
pointData2.yLabel += '
' + t.labels[attr] + Axes.hoverLabelText(ya, val, trace.yhoverformat);
} else {
// copy out to a new object for each new y-value to label
pointData2 = Lib.extendFlat({}, closestPoint);
pointData2.y0 = pointData2.y1 = valPx;
pointData2.yLabelVal = val;
pointData2.yLabel = t.labels[attr] + Axes.hoverLabelText(ya, val, trace.yhoverformat);
pointData2.name = '';
closeBoxData.push(pointData2);
usedVals[val] = pointData2;
}
}
return closeBoxData;
}
function hoverOnPoints(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var ya = pointData.ya;
var trace = cd[0].trace;
var t = cd[0].t;
var closestPoint = _getClosestPoint(pointData, xval, yval, hovermode);
// skip the rest (for this trace) if we didn't find a close point
if (!closestPoint) return [];
// we don't make a calcdata point if we're missing any piece (x/o/h/l/c)
// so we need to fix the index here to point to the data arrays
var cdIndex = closestPoint.index;
var di = cd[cdIndex];
var i = closestPoint.index = di.i;
var dir = di.dir;
function getLabelLine(attr) {
return t.labels[attr] + Axes.hoverLabelText(ya, trace[attr][i], trace.yhoverformat);
}
var hoverinfo = di.hi || trace.hoverinfo;
var hoverParts = hoverinfo.split('+');
var isAll = hoverinfo === 'all';
var hasY = isAll || hoverParts.indexOf('y') !== -1;
var hasText = isAll || hoverParts.indexOf('text') !== -1;
var textParts = hasY ? [getLabelLine('open'), getLabelLine('high'), getLabelLine('low'), getLabelLine('close') + ' ' + DIRSYMBOL[dir]] : [];
if (hasText) fillText(di, trace, textParts);
// don't make .yLabelVal or .text, since we're managing hoverinfo
// put it all in .extraText
closestPoint.extraText = textParts.join('
');
// this puts the label *and the spike* at the midpoint of the box, ie
// halfway between open and close, not between high and low.
closestPoint.y0 = closestPoint.y1 = ya.c2p(di.yc, true);
return [closestPoint];
}
module.exports = {
hoverPoints: hoverPoints,
hoverSplit: hoverSplit,
hoverOnPoints: hoverOnPoints
};
/***/ }),
/***/ 65456:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'ohlc',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', 'showLegend'],
meta: {},
attributes: __webpack_require__(20279),
supplyDefaults: __webpack_require__(23860),
calc: (__webpack_require__(42812).calc),
plot: __webpack_require__(36664),
style: __webpack_require__(14008),
hoverPoints: (__webpack_require__(18720).hoverPoints),
selectPoints: __webpack_require__(97384)
};
/***/ }),
/***/ 52744:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
module.exports = function handleOHLC(traceIn, traceOut, coerce, layout) {
var x = coerce('x');
var open = coerce('open');
var high = coerce('high');
var low = coerce('low');
var close = coerce('close');
coerce('hoverlabel.split');
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x'], layout);
if (!(open && high && low && close)) return;
var len = Math.min(open.length, high.length, low.length, close.length);
if (x) len = Math.min(len, Lib.minRowLength(x));
traceOut._length = len;
return len;
};
/***/ }),
/***/ 36664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
module.exports = function plot(gd, plotinfo, cdOHLC, ohlcLayer) {
var ya = plotinfo.yaxis;
var xa = plotinfo.xaxis;
var posHasRangeBreaks = !!xa.rangebreaks;
Lib.makeTraceGroups(ohlcLayer, cdOHLC, 'trace ohlc').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 tickLen = t.tickLen;
var paths = plotGroup.selectAll('path').data(Lib.identity);
paths.enter().append('path');
paths.exit().remove();
paths.attr('d', function (d) {
if (d.empty) return 'M0,0Z';
var xo = xa.c2p(d.pos - tickLen, true);
var xc = xa.c2p(d.pos + tickLen, true);
var x = posHasRangeBreaks ? (xo + xc) / 2 : xa.c2p(d.pos, true);
var yo = ya.c2p(d.o, true);
var yh = ya.c2p(d.h, true);
var yl = ya.c2p(d.l, true);
var yc = ya.c2p(d.c, true);
return 'M' + xo + ',' + yo + 'H' + x + 'M' + x + ',' + yh + 'V' + yl + 'M' + xc + ',' + yc + 'H' + x;
});
});
};
/***/ }),
/***/ 97384:
/***/ (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;
// for (potentially grouped) candlesticks
var posOffset = cd[0].t.bPos || 0;
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];
if (selectionTester.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)], null, di.i, searchInfo)) {
selection.push({
pointNumber: di.i,
x: xa.c2d(di.pos),
y: ya.c2d(di.yc)
});
di.selected = 1;
} else {
di.selected = 0;
}
}
}
return selection;
};
/***/ }),
/***/ 14008:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
module.exports = function style(gd, cd, sel) {
var s = sel ? sel : d3.select(gd).selectAll('g.ohlclayer').selectAll('g.trace');
s.style('opacity', function (d) {
return d[0].trace.opacity;
});
s.each(function (d) {
var trace = d[0].trace;
d3.select(this).selectAll('path').each(function (di) {
if (di.empty) return;
var dirLine = trace[di.dir].line;
d3.select(this).style('fill', 'none').call(Color.stroke, dirLine.color).call(Drawing.dashLine, dirLine.dash, dirLine.width)
// TODO: custom selection style for OHLC
.style('opacity', trace.selectedpoints && !di.selected ? 0.3 : 1);
});
});
};
/***/ }),
/***/ 72140:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var extendFlat = (__webpack_require__(92880).extendFlat);
var baseAttrs = __webpack_require__(45464);
var fontAttrs = __webpack_require__(25376);
var colorScaleAttrs = __webpack_require__(49084);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var line = extendFlat({
editType: 'calc'
}, colorScaleAttrs('line', {
editTypeOverride: 'calc'
}), {
shape: {
valType: 'enumerated',
values: ['linear', 'hspline'],
dflt: 'linear',
editType: 'plot'
},
hovertemplate: hovertemplateAttrs({
editType: 'plot',
arrayOk: false
}, {
keys: ['count', 'probability']
})
});
module.exports = {
domain: domainAttrs({
name: 'parcats',
trace: true,
editType: 'calc'
}),
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['count', 'probability'],
editType: 'plot',
arrayOk: false
}),
hoveron: {
valType: 'enumerated',
values: ['category', 'color', 'dimension'],
dflt: 'category',
editType: 'plot'
},
hovertemplate: hovertemplateAttrs({
editType: 'plot',
arrayOk: false
}, {
keys: ['count', 'probability', 'category', 'categorycount', 'colorcount', 'bandcolorcount']
}),
arrangement: {
valType: 'enumerated',
values: ['perpendicular', 'freeform', 'fixed'],
dflt: 'perpendicular',
editType: 'plot'
},
bundlecolors: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
sortpaths: {
valType: 'enumerated',
values: ['forward', 'backward'],
dflt: 'forward',
editType: 'plot'
},
labelfont: fontAttrs({
editType: 'calc'
}),
tickfont: fontAttrs({
autoShadowDflt: true,
editType: 'calc'
}),
dimensions: {
_isLinkedToArray: 'dimension',
label: {
valType: 'string',
editType: 'calc'
},
categoryorder: {
valType: 'enumerated',
values: ['trace', 'category ascending', 'category descending', 'array'],
dflt: 'trace',
editType: 'calc'
},
categoryarray: {
valType: 'data_array',
editType: 'calc'
},
ticktext: {
valType: 'data_array',
editType: 'calc'
},
values: {
valType: 'data_array',
dflt: [],
editType: 'calc'
},
displayindex: {
valType: 'integer',
editType: 'calc'
},
editType: 'calc',
visible: {
valType: 'boolean',
dflt: true,
editType: 'calc'
}
},
line: line,
counts: {
valType: 'number',
min: 0,
dflt: 1,
arrayOk: true,
editType: 'calc'
},
// Hide unsupported top-level properties from plot-schema
customdata: undefined,
hoverlabel: undefined,
ids: undefined,
legend: undefined,
legendgroup: undefined,
legendrank: undefined,
opacity: undefined,
selectedpoints: undefined,
showlegend: undefined
};
/***/ }),
/***/ 91800:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var getModuleCalcData = (__webpack_require__(84888)/* .getModuleCalcData */ ._M);
var parcatsPlot = __webpack_require__(60268);
var PARCATS = 'parcats';
exports.name = PARCATS;
exports.plot = function (gd, traces, transitionOpts, makeOnCompleteCallback) {
var cdModuleAndOthers = getModuleCalcData(gd.calcdata, PARCATS);
if (cdModuleAndOthers.length) {
var calcData = cdModuleAndOthers[0];
parcatsPlot(gd, calcData, transitionOpts, makeOnCompleteCallback);
}
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var hadTable = oldFullLayout._has && oldFullLayout._has('parcats');
var hasTable = newFullLayout._has && newFullLayout._has('parcats');
if (hadTable && !hasTable) {
oldFullLayout._paperdiv.selectAll('.parcats').remove();
}
};
/***/ }),
/***/ 69136:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// Requirements
// ============
var wrap = (__webpack_require__(71688).wrap);
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var colorscaleCalc = __webpack_require__(47128);
var filterUnique = __webpack_require__(68944);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var isNumeric = __webpack_require__(38248);
/**
* Create a wrapped ParcatsModel object from trace
*
* Note: trace defaults have already been applied
* @param {Object} gd
* @param {Object} trace
* @return {Array.
}
*/
module.exports = function calc(gd, trace) {
var visibleDims = Lib.filterVisible(trace.dimensions);
if (visibleDims.length === 0) return [];
var uniqueInfoDims = visibleDims.map(function (dim) {
var categoryValues;
if (dim.categoryorder === 'trace') {
// Use order of first occurrence in trace
categoryValues = null;
} else if (dim.categoryorder === 'array') {
// Use categories specified in `categoryarray` first,
// then add extra to the end in trace order
categoryValues = dim.categoryarray;
} else {
// Get all categories up front
categoryValues = filterUnique(dim.values);
// order them
var allNumeric = true;
for (var i = 0; i < categoryValues.length; i++) {
if (!isNumeric(categoryValues[i])) {
allNumeric = false;
break;
}
}
categoryValues.sort(allNumeric ? Lib.sorterAsc : undefined);
if (dim.categoryorder === 'category descending') {
categoryValues = categoryValues.reverse();
}
}
return getUniqueInfo(dim.values, categoryValues);
});
var counts, count, totalCount;
if (Lib.isArrayOrTypedArray(trace.counts)) {
counts = trace.counts;
} else {
counts = [trace.counts];
}
validateDimensionDisplayInds(visibleDims);
visibleDims.forEach(function (dim, dimInd) {
validateCategoryProperties(dim, uniqueInfoDims[dimInd]);
});
// Handle path colors
// ------------------
var line = trace.line;
var markerColorscale;
// Process colorscale
if (line) {
if (hasColorscale(trace, 'line')) {
colorscaleCalc(gd, trace, {
vals: trace.line.color,
containerStr: 'line',
cLetter: 'c'
});
}
markerColorscale = Drawing.tryColorscale(line);
} else {
markerColorscale = Lib.identity;
}
// Build color generation function
function getMarkerColorInfo(index) {
var value, rawColor;
if (Lib.isArrayOrTypedArray(line.color)) {
value = line.color[index % line.color.length];
rawColor = value;
} else {
value = line.color;
}
return {
color: markerColorscale(value),
rawColor: rawColor
};
}
// Number of values and counts
// ---------------------------
var numValues = visibleDims[0].values.length;
// Build path info
// ---------------
// Mapping from category inds to PathModel objects
var pathModels = {};
// Category inds array for each dimension
var categoryIndsDims = uniqueInfoDims.map(function (di) {
return di.inds;
});
// Initialize total count
totalCount = 0;
var valueInd;
var d;
for (valueInd = 0; valueInd < numValues; valueInd++) {
// Category inds for this input value across dimensions
var categoryIndsPath = [];
for (d = 0; d < categoryIndsDims.length; d++) {
categoryIndsPath.push(categoryIndsDims[d][valueInd]);
}
// Count
count = counts[valueInd % counts.length];
// Update total count
totalCount += count;
// Path color
var pathColorInfo = getMarkerColorInfo(valueInd);
// path key
var pathKey = categoryIndsPath + '-' + pathColorInfo.rawColor;
// Create / Update PathModel
if (pathModels[pathKey] === undefined) {
pathModels[pathKey] = createPathModel(categoryIndsPath, pathColorInfo.color, pathColorInfo.rawColor);
}
updatePathModel(pathModels[pathKey], valueInd, count);
}
var dimensionModels = visibleDims.map(function (di, i) {
return createDimensionModel(i, di._index, di._displayindex, di.label, totalCount);
});
for (valueInd = 0; valueInd < numValues; valueInd++) {
count = counts[valueInd % counts.length];
for (d = 0; d < dimensionModels.length; d++) {
var containerInd = dimensionModels[d].containerInd;
var catInd = uniqueInfoDims[d].inds[valueInd];
var cats = dimensionModels[d].categories;
if (cats[catInd] === undefined) {
var catValue = trace.dimensions[containerInd]._categoryarray[catInd];
var catLabel = trace.dimensions[containerInd]._ticktext[catInd];
cats[catInd] = createCategoryModel(d, catInd, catValue, catLabel);
}
updateCategoryModel(cats[catInd], valueInd, count);
}
}
// Compute unique
return wrap(createParcatsModel(dimensionModels, pathModels, totalCount));
};
// Models
// ======
// Parcats Model
// -------------
/**
* @typedef {Object} ParcatsModel
* Object containing calculated information about a parcats trace
*
* @property {Array.} dimensions
* Array of dimension models
* @property {Object.} paths
* Dictionary from category inds string (e.g. "1,2,1,1") to path model
* @property {Number} maxCats
* The maximum number of categories of any dimension in the diagram
* @property {Number} count
* Total number of input values
* @property {Object} trace
*/
/**
* Create and new ParcatsModel object
* @param {Array.} dimensions
* @param {Object.} paths
* @param {Number} count
* @return {ParcatsModel}
*/
function createParcatsModel(dimensions, paths, count) {
var maxCats = dimensions.map(function (d) {
return d.categories.length;
}).reduce(function (v1, v2) {
return Math.max(v1, v2);
});
return {
dimensions: dimensions,
paths: paths,
trace: undefined,
maxCats: maxCats,
count: count
};
}
// Dimension Model
// ---------------
/**
* @typedef {Object} DimensionModel
* Object containing calculated information about a single dimension
*
* @property {Number} dimensionInd
* The index of this dimension among the *visible* dimensions
* @property {Number} containerInd
* The index of this dimension in the original dimensions container,
* irrespective of dimension visibility
* @property {Number} displayInd
* The display index of this dimension (where 0 is the left most dimension)
* @property {String} dimensionLabel
* The label of this dimension
* @property {Number} count
* Total number of input values
* @property {Array.} categories
* @property {Number|null} dragX
* The x position of dimension that is currently being dragged. null if not being dragged
*/
/**
* Create and new DimensionModel object with an empty categories array
* @param {Number} dimensionInd
* @param {Number} containerInd
* @param {Number} displayInd
* @param {String} dimensionLabel
* @param {Number} count
* Total number of input values
* @return {DimensionModel}
*/
function createDimensionModel(dimensionInd, containerInd, displayInd, dimensionLabel, count) {
return {
dimensionInd: dimensionInd,
containerInd: containerInd,
displayInd: displayInd,
dimensionLabel: dimensionLabel,
count: count,
categories: [],
dragX: null
};
}
// Category Model
// --------------
/**
* @typedef {Object} CategoryModel
* Object containing calculated information about a single category.
*
* @property {Number} dimensionInd
* The index of this categories dimension
* @property {Number} categoryInd
* The index of this category
* @property {Number} displayInd
* The display index of this category (where 0 is the topmost category)
* @property {String} categoryLabel
* The name of this category
* @property categoryValue: Raw value of the category
* @property {Array} valueInds
* Array of indices (into the original value array) of all samples in this category
* @property {Number} count
* The number of elements from the original array in this path
* @property {Number|null} dragY
* The y position of category that is currently being dragged. null if not being dragged
*/
/**
* Create and return a new CategoryModel object
* @param {Number} dimensionInd
* @param {Number} categoryInd
* The display index of this category (where 0 is the topmost category)
* @param {String} categoryValue
* @param {String} categoryLabel
* @return {CategoryModel}
*/
function createCategoryModel(dimensionInd, categoryInd, categoryValue, categoryLabel) {
return {
dimensionInd: dimensionInd,
categoryInd: categoryInd,
categoryValue: categoryValue,
displayInd: categoryInd,
categoryLabel: categoryLabel,
valueInds: [],
count: 0,
dragY: null
};
}
/**
* Update a CategoryModel object with a new value index
* Note: The calling parameter is modified in place.
*
* @param {CategoryModel} categoryModel
* @param {Number} valueInd
* @param {Number} count
*/
function updateCategoryModel(categoryModel, valueInd, count) {
categoryModel.valueInds.push(valueInd);
categoryModel.count += count;
}
// Path Model
// ----------
/**
* @typedef {Object} PathModel
* Object containing calculated information about the samples in a path.
*
* @property {Array} categoryInds
* Array of category indices for each dimension (length `numDimensions`)
* @param {String} pathColor
* Color of this path. (Note: Any colorscaling has already taken place)
* @property {Array} valueInds
* Array of indices (into the original value array) of all samples in this path
* @property {Number} count
* The number of elements from the original array in this path
* @property {String} color
* The path's color (ass CSS color string)
* @property rawColor
* The raw color value specified by the user. May be a CSS color string or a Number
*/
/**
* Create and return a new PathModel object
* @param {Array} categoryInds
* @param color
* @param rawColor
* @return {PathModel}
*/
function createPathModel(categoryInds, color, rawColor) {
return {
categoryInds: categoryInds,
color: color,
rawColor: rawColor,
valueInds: [],
count: 0
};
}
/**
* Update a PathModel object with a new value index
* Note: The calling parameter is modified in place.
*
* @param {PathModel} pathModel
* @param {Number} valueInd
* @param {Number} count
*/
function updatePathModel(pathModel, valueInd, count) {
pathModel.valueInds.push(valueInd);
pathModel.count += count;
}
// Unique calculations
// ===================
/**
* @typedef {Object} UniqueInfo
* Object containing information about the unique values of an input array
*
* @property {Array} uniqueValues
* The unique values in the input array
* @property {Array} uniqueCounts
* The number of times each entry in uniqueValues occurs in input array.
* This has the same length as `uniqueValues`
* @property {Array} inds
* Indices into uniqueValues that would reproduce original input array
*/
/**
* Compute unique value information for an array
*
* IMPORTANT: Note that values are considered unique
* if their string representations are unique.
*
* @param {Array} values
* @param {Array|undefined} uniqueValues
* Array of expected unique values. The uniqueValues property of the resulting UniqueInfo object will begin with
* these entries. Entries are included even if there are zero occurrences in the values array. Entries found in
* the values array that are not present in uniqueValues will be included at the end of the array in the
* UniqueInfo object.
* @return {UniqueInfo}
*/
function getUniqueInfo(values, uniqueValues) {
// Initialize uniqueValues if not specified
if (uniqueValues === undefined || uniqueValues === null) {
uniqueValues = [];
} else {
// Shallow copy so append below doesn't alter input array
uniqueValues = uniqueValues.map(function (e) {
return e;
});
}
// Initialize Variables
var uniqueValueCounts = {};
var uniqueValueInds = {};
var inds = [];
// Initialize uniqueValueCounts and
uniqueValues.forEach(function (uniqueVal, valInd) {
uniqueValueCounts[uniqueVal] = 0;
uniqueValueInds[uniqueVal] = valInd;
});
// Compute the necessary unique info in a single pass
for (var i = 0; i < values.length; i++) {
var item = values[i];
var itemInd;
if (uniqueValueCounts[item] === undefined) {
// This item has a previously unseen value
uniqueValueCounts[item] = 1;
itemInd = uniqueValues.push(item) - 1;
uniqueValueInds[item] = itemInd;
} else {
// Increment count for this item
uniqueValueCounts[item]++;
itemInd = uniqueValueInds[item];
}
inds.push(itemInd);
}
// Build UniqueInfo
var uniqueCounts = uniqueValues.map(function (v) {
return uniqueValueCounts[v];
});
return {
uniqueValues: uniqueValues,
uniqueCounts: uniqueCounts,
inds: inds
};
}
/**
* Validate the requested display order for the dimensions.
* If the display order is a permutation of 0 through dimensions.length - 1, link to _displayindex
* Otherwise, replace the display order with the dimension order
* @param {Object} trace
*/
function validateDimensionDisplayInds(visibleDims) {
var displayInds = visibleDims.map(function (d) {
return d.displayindex;
});
var i;
if (isRangePermutation(displayInds)) {
for (i = 0; i < visibleDims.length; i++) {
visibleDims[i]._displayindex = visibleDims[i].displayindex;
}
} else {
for (i = 0; i < visibleDims.length; i++) {
visibleDims[i]._displayindex = i;
}
}
}
/**
* Update category properties based on the unique values found for this dimension
* @param {Object} dim
* @param {UniqueInfo} uniqueInfoDim
*/
function validateCategoryProperties(dim, uniqueInfoDim) {
// Update categoryarray
dim._categoryarray = uniqueInfoDim.uniqueValues;
// Handle ticktext
if (dim.ticktext === null || dim.ticktext === undefined) {
dim._ticktext = [];
} else {
// Shallow copy to avoid modifying input array
dim._ticktext = dim.ticktext.slice();
}
// Extend ticktext with elements from uniqueInfoDim.uniqueValues
for (var i = dim._ticktext.length; i < uniqueInfoDim.uniqueValues.length; i++) {
dim._ticktext.push(uniqueInfoDim.uniqueValues[i]);
}
}
/**
* Determine whether an array contains a permutation of the integers from 0 to the array's length - 1
* @param {Array} inds
* @return {boolean}
*/
function isRangePermutation(inds) {
var indsSpecified = new Array(inds.length);
for (var i = 0; i < inds.length; i++) {
// Check for out of bounds
if (inds[i] < 0 || inds[i] >= inds.length) {
return false;
}
// Check for collisions with already specified index
if (indsSpecified[inds[i]] !== undefined) {
return false;
}
indsSpecified[inds[i]] = true;
}
// Nothing out of bounds and no collisions. We have a permutation
return true;
}
/***/ }),
/***/ 76671:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var colorscaleDefaults = __webpack_require__(27260);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var handleArrayContainerDefaults = __webpack_require__(51272);
var attributes = __webpack_require__(72140);
var mergeLength = __webpack_require__(26284);
var isTypedArraySpec = (__webpack_require__(38116).isTypedArraySpec);
function handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
coerce('line.shape');
coerce('line.hovertemplate');
var lineColor = coerce('line.color', layout.colorway[0]);
if (hasColorscale(traceIn, 'line') && Lib.isArrayOrTypedArray(lineColor)) {
if (lineColor.length) {
coerce('line.colorscale');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'line.',
cLetter: 'c'
});
return lineColor.length;
} else {
traceOut.line.color = defaultColor;
}
}
return Infinity;
}
function dimensionDefaults(dimensionIn, dimensionOut) {
function coerce(attr, dflt) {
return Lib.coerce(dimensionIn, dimensionOut, attributes.dimensions, attr, dflt);
}
var values = coerce('values');
var visible = coerce('visible');
if (!(values && values.length)) {
visible = dimensionOut.visible = false;
}
if (visible) {
// Dimension level
coerce('label');
coerce('displayindex', dimensionOut._index);
// Category level
var arrayIn = dimensionIn.categoryarray;
var isValidArray = Lib.isArrayOrTypedArray(arrayIn) && arrayIn.length > 0 || isTypedArraySpec(arrayIn);
var orderDefault;
if (isValidArray) orderDefault = 'array';
var order = coerce('categoryorder', orderDefault);
// coerce 'categoryarray' only in array order case
if (order === 'array') {
coerce('categoryarray');
coerce('ticktext');
} else {
delete dimensionIn.categoryarray;
delete dimensionIn.ticktext;
}
// cannot set 'categoryorder' to 'array' with an invalid 'categoryarray'
if (!isValidArray && order === 'array') {
dimensionOut.categoryorder = 'trace';
}
}
}
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
name: 'dimensions',
handleItemDefaults: dimensionDefaults
});
var len = handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
handleDomainDefaults(traceOut, layout, coerce);
if (!Array.isArray(dimensions) || !dimensions.length) {
traceOut.visible = false;
}
mergeLength(traceOut, dimensions, 'values', len);
coerce('hoveron');
coerce('hovertemplate');
coerce('arrangement');
coerce('bundlecolors');
coerce('sortpaths');
coerce('counts');
var layoutFont = layout.font;
Lib.coerceFont(coerce, 'labelfont', layoutFont, {
overrideDflt: {
size: Math.round(layoutFont.size)
}
});
Lib.coerceFont(coerce, 'tickfont', layoutFont, {
autoShadowDflt: true,
overrideDflt: {
size: Math.round(layoutFont.size / 1.2)
}
});
};
/***/ }),
/***/ 22020:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(72140),
supplyDefaults: __webpack_require__(76671),
calc: __webpack_require__(69136),
plot: __webpack_require__(60268),
colorbar: {
container: 'line',
min: 'cmin',
max: 'cmax'
},
moduleType: 'trace',
name: 'parcats',
basePlotModule: __webpack_require__(91800),
categories: ['noOpacity'],
meta: {}
};
/***/ }),
/***/ 51036:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var interpolateNumber = (__webpack_require__(67756)/* .interpolateNumber */ .Gz);
var Plotly = __webpack_require__(36424);
var Fx = __webpack_require__(93024);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var Drawing = __webpack_require__(43616);
var tinycolor = __webpack_require__(49760);
var svgTextUtils = __webpack_require__(72736);
function performPlot(parcatsModels, graphDiv, layout, svg) {
var isStatic = graphDiv._context.staticPlot;
var viewModels = parcatsModels.map(createParcatsViewModel.bind(0, graphDiv, layout));
// Get (potentially empty) parcatslayer selection with bound data to single element array
var layerSelection = svg.selectAll('g.parcatslayer').data([null]);
// Initialize single parcatslayer group if it doesn't exist
layerSelection.enter().append('g').attr('class', 'parcatslayer').style('pointer-events', isStatic ? 'none' : 'all');
// Bind data to children of layerSelection and get reference to traceSelection
var traceSelection = layerSelection.selectAll('g.trace.parcats').data(viewModels, key);
// Initialize group for each trace/dimensions
var traceEnter = traceSelection.enter().append('g').attr('class', 'trace parcats');
// Update properties for each trace
traceSelection.attr('transform', function (d) {
return strTranslate(d.x, d.y);
});
// Initialize paths group
traceEnter.append('g').attr('class', 'paths');
// Update paths transform
var pathsSelection = traceSelection.select('g.paths');
// Get paths selection
var pathSelection = pathsSelection.selectAll('path.path').data(function (d) {
return d.paths;
}, key);
// Update existing path colors
pathSelection.attr('fill', function (d) {
return d.model.color;
});
// Create paths
var pathSelectionEnter = pathSelection.enter().append('path').attr('class', 'path').attr('stroke-opacity', 0).attr('fill', function (d) {
return d.model.color;
}).attr('fill-opacity', 0);
stylePathsNoHover(pathSelectionEnter);
// Set path geometry
pathSelection.attr('d', function (d) {
return d.svgD;
});
// sort paths
if (!pathSelectionEnter.empty()) {
// Only sort paths if there has been a change.
// Otherwise paths are already sorted or a hover operation may be in progress
pathSelection.sort(compareRawColor);
}
// Remove any old paths
pathSelection.exit().remove();
// Path hover
pathSelection.on('mouseover', mouseoverPath).on('mouseout', mouseoutPath).on('click', clickPath);
// Initialize dimensions group
traceEnter.append('g').attr('class', 'dimensions');
// Update dimensions transform
var dimensionsSelection = traceSelection.select('g.dimensions');
// Get dimension selection
var dimensionSelection = dimensionsSelection.selectAll('g.dimension').data(function (d) {
return d.dimensions;
}, key);
// Create dimension groups
dimensionSelection.enter().append('g').attr('class', 'dimension');
// Update dimension group transforms
dimensionSelection.attr('transform', function (d) {
return strTranslate(d.x, 0);
});
// Remove any old dimensions
dimensionSelection.exit().remove();
// Get category selection
var categorySelection = dimensionSelection.selectAll('g.category').data(function (d) {
return d.categories;
}, key);
// Initialize category groups
var categoryGroupEnterSelection = categorySelection.enter().append('g').attr('class', 'category');
// Update category transforms
categorySelection.attr('transform', function (d) {
return strTranslate(0, d.y);
});
// Initialize rectangle
categoryGroupEnterSelection.append('rect').attr('class', 'catrect').attr('pointer-events', 'none');
// Update rectangle
categorySelection.select('rect.catrect').attr('fill', 'none').attr('width', function (d) {
return d.width;
}).attr('height', function (d) {
return d.height;
});
styleCategoriesNoHover(categoryGroupEnterSelection);
// Initialize color band rects
var bandSelection = categorySelection.selectAll('rect.bandrect').data( /** @param {CategoryViewModel} catViewModel*/
function (catViewModel) {
return catViewModel.bands;
}, key);
// Raise all update bands to the top so that fading enter/exit bands will be behind
bandSelection.each(function () {
Lib.raiseToTop(this);
});
// Update band color
bandSelection.attr('fill', function (d) {
return d.color;
});
var bandsSelectionEnter = bandSelection.enter().append('rect').attr('class', 'bandrect').attr('stroke-opacity', 0).attr('fill', function (d) {
return d.color;
}).attr('fill-opacity', 0);
bandSelection.attr('fill', function (d) {
return d.color;
}).attr('width', function (d) {
return d.width;
}).attr('height', function (d) {
return d.height;
}).attr('y', function (d) {
return d.y;
}).attr('cursor', /** @param {CategoryBandViewModel} bandModel*/
function (bandModel) {
if (bandModel.parcatsViewModel.arrangement === 'fixed') {
return 'default';
} else if (bandModel.parcatsViewModel.arrangement === 'perpendicular') {
return 'ns-resize';
} else {
return 'move';
}
});
styleBandsNoHover(bandsSelectionEnter);
bandSelection.exit().remove();
// Initialize category label
categoryGroupEnterSelection.append('text').attr('class', 'catlabel').attr('pointer-events', 'none');
// Update category label
categorySelection.select('text.catlabel').attr('text-anchor', function (d) {
if (catInRightDim(d)) {
// Place label to the right of category
return 'start';
} else {
// Place label to the left of category
return 'end';
}
}).attr('alignment-baseline', 'middle').style('fill', 'rgb(0, 0, 0)').attr('x', function (d) {
if (catInRightDim(d)) {
// Place label to the right of category
return d.width + 5;
} else {
// Place label to the left of category
return -5;
}
}).attr('y', function (d) {
return d.height / 2;
}).text(function (d) {
return d.model.categoryLabel;
}).each( /** @param {CategoryViewModel} catModel*/
function (catModel) {
Drawing.font(d3.select(this), catModel.parcatsViewModel.categorylabelfont);
svgTextUtils.convertToTspans(d3.select(this), graphDiv);
});
// Initialize dimension label
categoryGroupEnterSelection.append('text').attr('class', 'dimlabel');
// Update dimension label
categorySelection.select('text.dimlabel').attr('text-anchor', 'middle').attr('alignment-baseline', 'baseline').attr('cursor', /** @param {CategoryViewModel} catModel*/
function (catModel) {
if (catModel.parcatsViewModel.arrangement === 'fixed') {
return 'default';
} else {
return 'ew-resize';
}
}).attr('x', function (d) {
return d.width / 2;
}).attr('y', -5).text(function (d, i) {
if (i === 0) {
// Add dimension label above topmost category
return d.parcatsViewModel.model.dimensions[d.model.dimensionInd].dimensionLabel;
} else {
return null;
}
}).each( /** @param {CategoryViewModel} catModel*/
function (catModel) {
Drawing.font(d3.select(this), catModel.parcatsViewModel.labelfont);
});
// Category hover
// categorySelection.select('rect.catrect')
categorySelection.selectAll('rect.bandrect').on('mouseover', mouseoverCategoryBand).on('mouseout', mouseoutCategory);
// Remove unused categories
categorySelection.exit().remove();
// Setup drag
dimensionSelection.call(d3.behavior.drag().origin(function (d) {
return {
x: d.x,
y: 0
};
}).on('dragstart', dragDimensionStart).on('drag', dragDimension).on('dragend', dragDimensionEnd));
// Save off selections to view models
traceSelection.each(function (d) {
d.traceSelection = d3.select(this);
d.pathSelection = d3.select(this).selectAll('g.paths').selectAll('path.path');
d.dimensionSelection = d3.select(this).selectAll('g.dimensions').selectAll('g.dimension');
});
// Remove any orphan traces
traceSelection.exit().remove();
}
/**
* Create / update parcat traces
*
* @param {Object} graphDiv
* @param {Object} svg
* @param {Array.} parcatsModels
* @param {Layout} layout
*/
module.exports = function (graphDiv, svg, parcatsModels, layout) {
performPlot(parcatsModels, graphDiv, layout, svg);
};
/**
* Function the returns the key property of an object for use with as D3 join function
* @param d
*/
function key(d) {
return d.key;
}
/** True if a category view model is in the right-most display dimension
* @param {CategoryViewModel} d */
function catInRightDim(d) {
var numDims = d.parcatsViewModel.dimensions.length;
var leftDimInd = d.parcatsViewModel.dimensions[numDims - 1].model.dimensionInd;
return d.model.dimensionInd === leftDimInd;
}
/**
* @param {PathViewModel} a
* @param {PathViewModel} b
*/
function compareRawColor(a, b) {
if (a.model.rawColor > b.model.rawColor) {
return 1;
} else if (a.model.rawColor < b.model.rawColor) {
return -1;
} else {
return 0;
}
}
/**
* Handle path mouseover
* @param {PathViewModel} d
*/
function mouseoverPath(d) {
if (!d.parcatsViewModel.dragDimension) {
// We're not currently dragging
if (d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
// hoverinfo is not skip, so we at least style the paths and emit interaction events
// Raise path to top
Lib.raiseToTop(this);
stylePathsHover(d3.select(this));
// Emit hover event
var points = buildPointsArrayForPath(d);
var constraints = buildConstraintsForPath(d);
d.parcatsViewModel.graphDiv.emit('plotly_hover', {
points: points,
event: d3.event,
constraints: constraints
});
// Handle hover label
if (d.parcatsViewModel.hoverinfoItems.indexOf('none') === -1) {
// hoverinfo is a combination of 'count' and 'probability'
// Mouse
var hoverX = d3.mouse(this)[0];
// Label
var gd = d.parcatsViewModel.graphDiv;
var trace = d.parcatsViewModel.trace;
var fullLayout = gd._fullLayout;
var rootBBox = fullLayout._paperdiv.node().getBoundingClientRect();
var graphDivBBox = d.parcatsViewModel.graphDiv.getBoundingClientRect();
// Find path center in path coordinates
var pathCenterX, pathCenterY, dimInd;
for (dimInd = 0; dimInd < d.leftXs.length - 1; dimInd++) {
if (d.leftXs[dimInd] + d.dimWidths[dimInd] - 2 <= hoverX && hoverX <= d.leftXs[dimInd + 1] + 2) {
var leftDim = d.parcatsViewModel.dimensions[dimInd];
var rightDim = d.parcatsViewModel.dimensions[dimInd + 1];
pathCenterX = (leftDim.x + leftDim.width + rightDim.x) / 2;
pathCenterY = (d.topYs[dimInd] + d.topYs[dimInd + 1] + d.height) / 2;
break;
}
}
// Find path center in root coordinates
var hoverCenterX = d.parcatsViewModel.x + pathCenterX;
var hoverCenterY = d.parcatsViewModel.y + pathCenterY;
var textColor = tinycolor.mostReadable(d.model.color, ['black', 'white']);
var count = d.model.count;
var prob = count / d.parcatsViewModel.model.count;
var labels = {
countLabel: count,
probabilityLabel: prob.toFixed(3)
};
// Build hover text
var hovertextParts = [];
if (d.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
hovertextParts.push(['Count:', labels.countLabel].join(' '));
}
if (d.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
hovertextParts.push(['P:', labels.probabilityLabel].join(' '));
}
var hovertext = hovertextParts.join(' ');
var mouseX = d3.mouse(gd)[0];
Fx.loneHover({
trace: trace,
x: hoverCenterX - rootBBox.left + graphDivBBox.left,
y: hoverCenterY - rootBBox.top + graphDivBBox.top,
text: hovertext,
color: d.model.color,
borderColor: 'black',
fontFamily: 'Monaco, "Courier New", monospace',
fontSize: 10,
fontColor: textColor,
idealAlign: mouseX < hoverCenterX ? 'right' : 'left',
hovertemplate: (trace.line || {}).hovertemplate,
hovertemplateLabels: labels,
eventData: [{
data: trace._input,
fullData: trace,
count: count,
probability: prob
}]
}, {
container: fullLayout._hoverlayer.node(),
outerContainer: fullLayout._paper.node(),
gd: gd
});
}
}
}
}
/**
* Handle path mouseout
* @param {PathViewModel} d
*/
function mouseoutPath(d) {
if (!d.parcatsViewModel.dragDimension) {
// We're not currently dragging
stylePathsNoHover(d3.select(this));
// Remove and hover label
Fx.loneUnhover(d.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());
// Restore path order
d.parcatsViewModel.pathSelection.sort(compareRawColor);
// Emit unhover event
if (d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
var points = buildPointsArrayForPath(d);
var constraints = buildConstraintsForPath(d);
d.parcatsViewModel.graphDiv.emit('plotly_unhover', {
points: points,
event: d3.event,
constraints: constraints
});
}
}
}
/**
* Build array of point objects for a path
*
* For use in click/hover events
* @param {PathViewModel} d
*/
function buildPointsArrayForPath(d) {
var points = [];
var curveNumber = getTraceIndex(d.parcatsViewModel);
for (var i = 0; i < d.model.valueInds.length; i++) {
var pointNumber = d.model.valueInds[i];
points.push({
curveNumber: curveNumber,
pointNumber: pointNumber
});
}
return points;
}
/**
* Build constraints object for a path
*
* For use in click/hover events
* @param {PathViewModel} d
*/
function buildConstraintsForPath(d) {
var constraints = {};
var dimensions = d.parcatsViewModel.model.dimensions;
// dimensions
for (var i = 0; i < dimensions.length; i++) {
var dimension = dimensions[i];
var category = dimension.categories[d.model.categoryInds[i]];
constraints[dimension.containerInd] = category.categoryValue;
}
// color
if (d.model.rawColor !== undefined) {
constraints.color = d.model.rawColor;
}
return constraints;
}
/**
* Handle path click
* @param {PathViewModel} d
*/
function clickPath(d) {
if (d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
// hoverinfo it's skip, so interaction events aren't disabled
var points = buildPointsArrayForPath(d);
var constraints = buildConstraintsForPath(d);
d.parcatsViewModel.graphDiv.emit('plotly_click', {
points: points,
event: d3.event,
constraints: constraints
});
}
}
function stylePathsNoHover(pathSelection) {
pathSelection.attr('fill', function (d) {
return d.model.color;
}).attr('fill-opacity', 0.6).attr('stroke', 'lightgray').attr('stroke-width', 0.2).attr('stroke-opacity', 1.0);
}
function stylePathsHover(pathSelection) {
pathSelection.attr('fill-opacity', 0.8).attr('stroke', function (d) {
return tinycolor.mostReadable(d.model.color, ['black', 'white']);
}).attr('stroke-width', 0.3);
}
function styleCategoryHover(categorySelection) {
categorySelection.select('rect.catrect').attr('stroke', 'black').attr('stroke-width', 2.5);
}
function styleCategoriesNoHover(categorySelection) {
categorySelection.select('rect.catrect').attr('stroke', 'black').attr('stroke-width', 1).attr('stroke-opacity', 1);
}
function styleBandsHover(bandsSelection) {
bandsSelection.attr('stroke', 'black').attr('stroke-width', 1.5);
}
function styleBandsNoHover(bandsSelection) {
bandsSelection.attr('stroke', 'black').attr('stroke-width', 0.2).attr('stroke-opacity', 1.0).attr('fill-opacity', 1.0);
}
/**
* Return selection of all paths that pass through the specified category
* @param {CategoryBandViewModel} catBandViewModel
*/
function selectPathsThroughCategoryBandColor(catBandViewModel) {
var allPaths = catBandViewModel.parcatsViewModel.pathSelection;
var dimInd = catBandViewModel.categoryViewModel.model.dimensionInd;
var catInd = catBandViewModel.categoryViewModel.model.categoryInd;
return allPaths.filter( /** @param {PathViewModel} pathViewModel */
function (pathViewModel) {
return pathViewModel.model.categoryInds[dimInd] === catInd && pathViewModel.model.color === catBandViewModel.color;
});
}
/**
* Perform hover styling for all paths that pass though the specified band element's category
*
* @param {HTMLElement} bandElement
* HTML element for band
*
*/
function styleForCategoryHovermode(bandElement) {
// Get all bands in the current category
var bandSel = d3.select(bandElement.parentNode).selectAll('rect.bandrect');
// Raise and style paths
bandSel.each(function (bvm) {
var paths = selectPathsThroughCategoryBandColor(bvm);
stylePathsHover(paths);
paths.each(function () {
// Raise path to top
Lib.raiseToTop(this);
});
});
// Style category
styleCategoryHover(d3.select(bandElement.parentNode));
}
/**
* Perform hover styling for all paths that pass though the category of the specified band element and share the
* same color
*
* @param {HTMLElement} bandElement
* HTML element for band
*
*/
function styleForColorHovermode(bandElement) {
var bandViewModel = d3.select(bandElement).datum();
var catPaths = selectPathsThroughCategoryBandColor(bandViewModel);
stylePathsHover(catPaths);
catPaths.each(function () {
// Raise path to top
Lib.raiseToTop(this);
});
// Style category for drag
d3.select(bandElement.parentNode).selectAll('rect.bandrect').filter(function (b) {
return b.color === bandViewModel.color;
}).each(function () {
Lib.raiseToTop(this);
styleBandsHover(d3.select(this));
});
}
/**
* @param {HTMLElement} bandElement
* HTML element for band
* @param eventName
* Event name (plotly_hover or plotly_click)
* @param event
* Mouse Event
*/
function emitPointsEventCategoryHovermode(bandElement, eventName, event) {
// Get all bands in the current category
var bandViewModel = d3.select(bandElement).datum();
var categoryModel = bandViewModel.categoryViewModel.model;
var gd = bandViewModel.parcatsViewModel.graphDiv;
var bandSel = d3.select(bandElement.parentNode).selectAll('rect.bandrect');
var points = [];
bandSel.each(function (bvm) {
var paths = selectPathsThroughCategoryBandColor(bvm);
paths.each(function (pathViewModel) {
// Extend points array
Array.prototype.push.apply(points, buildPointsArrayForPath(pathViewModel));
});
});
var constraints = {};
constraints[categoryModel.dimensionInd] = categoryModel.categoryValue;
gd.emit(eventName, {
points: points,
event: event,
constraints: constraints
});
}
/**
* @param {HTMLElement} bandElement
* HTML element for band
* @param eventName
* Event name (plotly_hover or plotly_click)
* @param event
* Mouse Event
*/
function emitPointsEventColorHovermode(bandElement, eventName, event) {
var bandViewModel = d3.select(bandElement).datum();
var categoryModel = bandViewModel.categoryViewModel.model;
var gd = bandViewModel.parcatsViewModel.graphDiv;
var paths = selectPathsThroughCategoryBandColor(bandViewModel);
var points = [];
paths.each(function (pathViewModel) {
// Extend points array
Array.prototype.push.apply(points, buildPointsArrayForPath(pathViewModel));
});
var constraints = {};
constraints[categoryModel.dimensionInd] = categoryModel.categoryValue;
// color
if (bandViewModel.rawColor !== undefined) {
constraints.color = bandViewModel.rawColor;
}
gd.emit(eventName, {
points: points,
event: event,
constraints: constraints
});
}
/**
* Create hover label for a band element's category (for use when hoveron === 'category')
*
* @param {ClientRect} rootBBox
* Client bounding box for root of figure
* @param {HTMLElement} bandElement
* HTML element for band
*
*/
function createHoverLabelForCategoryHovermode(gd, rootBBox, bandElement) {
gd._fullLayout._calcInverseTransform(gd);
var scaleX = gd._fullLayout._invScaleX;
var scaleY = gd._fullLayout._invScaleY;
// Selections
var rectSelection = d3.select(bandElement.parentNode).select('rect.catrect');
var rectBoundingBox = rectSelection.node().getBoundingClientRect();
// Models
/** @type {CategoryViewModel} */
var catViewModel = rectSelection.datum();
var parcatsViewModel = catViewModel.parcatsViewModel;
var dimensionModel = parcatsViewModel.model.dimensions[catViewModel.model.dimensionInd];
var trace = parcatsViewModel.trace;
// Positions
var hoverCenterY = rectBoundingBox.top + rectBoundingBox.height / 2;
var hoverCenterX, hoverLabelIdealAlign;
if (parcatsViewModel.dimensions.length > 1 && dimensionModel.displayInd === parcatsViewModel.dimensions.length - 1) {
// right most dimension
hoverCenterX = rectBoundingBox.left;
hoverLabelIdealAlign = 'left';
} else {
hoverCenterX = rectBoundingBox.left + rectBoundingBox.width;
hoverLabelIdealAlign = 'right';
}
var count = catViewModel.model.count;
var catLabel = catViewModel.model.categoryLabel;
var prob = count / catViewModel.parcatsViewModel.model.count;
var labels = {
countLabel: count,
categoryLabel: catLabel,
probabilityLabel: prob.toFixed(3)
};
// Hover label text
var hoverinfoParts = [];
if (catViewModel.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
hoverinfoParts.push(['Count:', labels.countLabel].join(' '));
}
if (catViewModel.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
hoverinfoParts.push(['P(' + labels.categoryLabel + '):', labels.probabilityLabel].join(' '));
}
var hovertext = hoverinfoParts.join(' ');
return {
trace: trace,
x: scaleX * (hoverCenterX - rootBBox.left),
y: scaleY * (hoverCenterY - rootBBox.top),
text: hovertext,
color: 'lightgray',
borderColor: 'black',
fontFamily: 'Monaco, "Courier New", monospace',
fontSize: 12,
fontColor: 'black',
idealAlign: hoverLabelIdealAlign,
hovertemplate: trace.hovertemplate,
hovertemplateLabels: labels,
eventData: [{
data: trace._input,
fullData: trace,
count: count,
category: catLabel,
probability: prob
}]
};
}
/**
* Create hover label for a band element's category (for use when hoveron === 'category')
*
* @param {ClientRect} rootBBox
* Client bounding box for root of figure
* @param {HTMLElement} bandElement
* HTML element for band
*
*/
function createHoverLabelForDimensionHovermode(gd, rootBBox, bandElement) {
var allHoverlabels = [];
d3.select(bandElement.parentNode.parentNode).selectAll('g.category').select('rect.catrect').each(function () {
var bandNode = this;
allHoverlabels.push(createHoverLabelForCategoryHovermode(gd, rootBBox, bandNode));
});
return allHoverlabels;
}
/**
* Create hover labels for a band element's category (for use when hoveron === 'dimension')
*
* @param {ClientRect} rootBBox
* Client bounding box for root of figure
* @param {HTMLElement} bandElement
* HTML element for band
*
*/
function createHoverLabelForColorHovermode(gd, rootBBox, bandElement) {
gd._fullLayout._calcInverseTransform(gd);
var scaleX = gd._fullLayout._invScaleX;
var scaleY = gd._fullLayout._invScaleY;
var bandBoundingBox = bandElement.getBoundingClientRect();
// Models
/** @type {CategoryBandViewModel} */
var bandViewModel = d3.select(bandElement).datum();
var catViewModel = bandViewModel.categoryViewModel;
var parcatsViewModel = catViewModel.parcatsViewModel;
var dimensionModel = parcatsViewModel.model.dimensions[catViewModel.model.dimensionInd];
var trace = parcatsViewModel.trace;
// positions
var hoverCenterY = bandBoundingBox.y + bandBoundingBox.height / 2;
var hoverCenterX, hoverLabelIdealAlign;
if (parcatsViewModel.dimensions.length > 1 && dimensionModel.displayInd === parcatsViewModel.dimensions.length - 1) {
// right most dimension
hoverCenterX = bandBoundingBox.left;
hoverLabelIdealAlign = 'left';
} else {
hoverCenterX = bandBoundingBox.left + bandBoundingBox.width;
hoverLabelIdealAlign = 'right';
}
// Labels
var catLabel = catViewModel.model.categoryLabel;
// Counts
var totalCount = bandViewModel.parcatsViewModel.model.count;
var bandColorCount = 0;
bandViewModel.categoryViewModel.bands.forEach(function (b) {
if (b.color === bandViewModel.color) {
bandColorCount += b.count;
}
});
var catCount = catViewModel.model.count;
var colorCount = 0;
parcatsViewModel.pathSelection.each( /** @param {PathViewModel} pathViewModel */
function (pathViewModel) {
if (pathViewModel.model.color === bandViewModel.color) {
colorCount += pathViewModel.model.count;
}
});
var pColorAndCat = bandColorCount / totalCount;
var pCatGivenColor = bandColorCount / colorCount;
var pColorGivenCat = bandColorCount / catCount;
var labels = {
countLabel: bandColorCount,
categoryLabel: catLabel,
probabilityLabel: pColorAndCat.toFixed(3)
};
// Hover label text
var hoverinfoParts = [];
if (catViewModel.parcatsViewModel.hoverinfoItems.indexOf('count') !== -1) {
hoverinfoParts.push(['Count:', labels.countLabel].join(' '));
}
if (catViewModel.parcatsViewModel.hoverinfoItems.indexOf('probability') !== -1) {
hoverinfoParts.push('P(color ∩ ' + catLabel + '): ' + labels.probabilityLabel);
hoverinfoParts.push('P(' + catLabel + ' | color): ' + pCatGivenColor.toFixed(3));
hoverinfoParts.push('P(color | ' + catLabel + '): ' + pColorGivenCat.toFixed(3));
}
var hovertext = hoverinfoParts.join(' ');
// Compute text color
var textColor = tinycolor.mostReadable(bandViewModel.color, ['black', 'white']);
return {
trace: trace,
x: scaleX * (hoverCenterX - rootBBox.left),
y: scaleY * (hoverCenterY - rootBBox.top),
// name: 'NAME',
text: hovertext,
color: bandViewModel.color,
borderColor: 'black',
fontFamily: 'Monaco, "Courier New", monospace',
fontColor: textColor,
fontSize: 10,
idealAlign: hoverLabelIdealAlign,
hovertemplate: trace.hovertemplate,
hovertemplateLabels: labels,
eventData: [{
data: trace._input,
fullData: trace,
category: catLabel,
count: totalCount,
probability: pColorAndCat,
categorycount: catCount,
colorcount: colorCount,
bandcolorcount: bandColorCount
}]
};
}
/**
* Handle dimension mouseover
* @param {CategoryBandViewModel} bandViewModel
*/
function mouseoverCategoryBand(bandViewModel) {
if (!bandViewModel.parcatsViewModel.dragDimension) {
// We're not currently dragging
if (bandViewModel.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
// hoverinfo is not skip, so we at least style the bands and emit interaction events
// Mouse
var mouseY = d3.mouse(this)[1];
if (mouseY < -1) {
// Hover is above above the category rectangle (probably the dimension title text)
return;
}
var gd = bandViewModel.parcatsViewModel.graphDiv;
var fullLayout = gd._fullLayout;
var rootBBox = fullLayout._paperdiv.node().getBoundingClientRect();
var hoveron = bandViewModel.parcatsViewModel.hoveron;
/** @type {HTMLElement} */
var bandElement = this;
// Handle style and events
if (hoveron === 'color') {
styleForColorHovermode(bandElement);
emitPointsEventColorHovermode(bandElement, 'plotly_hover', d3.event);
} else {
styleForCategoryHovermode(bandElement);
emitPointsEventCategoryHovermode(bandElement, 'plotly_hover', d3.event);
}
// Handle hover label
if (bandViewModel.parcatsViewModel.hoverinfoItems.indexOf('none') === -1) {
var hoverItems;
if (hoveron === 'category') {
hoverItems = createHoverLabelForCategoryHovermode(gd, rootBBox, bandElement);
} else if (hoveron === 'color') {
hoverItems = createHoverLabelForColorHovermode(gd, rootBBox, bandElement);
} else if (hoveron === 'dimension') {
hoverItems = createHoverLabelForDimensionHovermode(gd, rootBBox, bandElement);
}
if (hoverItems) {
Fx.loneHover(hoverItems, {
container: fullLayout._hoverlayer.node(),
outerContainer: fullLayout._paper.node(),
gd: gd
});
}
}
}
}
}
/**
* Handle dimension mouseover
* @param {CategoryBandViewModel} bandViewModel
*/
function mouseoutCategory(bandViewModel) {
var parcatsViewModel = bandViewModel.parcatsViewModel;
if (!parcatsViewModel.dragDimension) {
// We're not dragging anything
// Reset unhovered styles
stylePathsNoHover(parcatsViewModel.pathSelection);
styleCategoriesNoHover(parcatsViewModel.dimensionSelection.selectAll('g.category'));
styleBandsNoHover(parcatsViewModel.dimensionSelection.selectAll('g.category').selectAll('rect.bandrect'));
// Remove hover label
Fx.loneUnhover(parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());
// Restore path order
parcatsViewModel.pathSelection.sort(compareRawColor);
// Emit unhover event
if (parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
var hoveron = bandViewModel.parcatsViewModel.hoveron;
var bandElement = this;
// Handle style and events
if (hoveron === 'color') {
emitPointsEventColorHovermode(bandElement, 'plotly_unhover', d3.event);
} else {
emitPointsEventCategoryHovermode(bandElement, 'plotly_unhover', d3.event);
}
}
}
}
/**
* Handle dimension drag start
* @param {DimensionViewModel} d
*/
function dragDimensionStart(d) {
// Check if dragging is supported
if (d.parcatsViewModel.arrangement === 'fixed') {
return;
}
// Save off initial drag indexes for dimension
d.dragDimensionDisplayInd = d.model.displayInd;
d.initialDragDimensionDisplayInds = d.parcatsViewModel.model.dimensions.map(function (d) {
return d.displayInd;
});
d.dragHasMoved = false;
// Check for category hit
d.dragCategoryDisplayInd = null;
d3.select(this).selectAll('g.category').select('rect.catrect').each( /** @param {CategoryViewModel} catViewModel */
function (catViewModel) {
var catMouseX = d3.mouse(this)[0];
var catMouseY = d3.mouse(this)[1];
if (-2 <= catMouseX && catMouseX <= catViewModel.width + 2 && -2 <= catMouseY && catMouseY <= catViewModel.height + 2) {
// Save off initial drag indexes for categories
d.dragCategoryDisplayInd = catViewModel.model.displayInd;
d.initialDragCategoryDisplayInds = d.model.categories.map(function (c) {
return c.displayInd;
});
// Initialize categories dragY to be the current y position
catViewModel.model.dragY = catViewModel.y;
// Raise category
Lib.raiseToTop(this.parentNode);
// Get band element
d3.select(this.parentNode).selectAll('rect.bandrect')
/** @param {CategoryBandViewModel} bandViewModel */.each(function (bandViewModel) {
if (bandViewModel.y < catMouseY && catMouseY <= bandViewModel.y + bandViewModel.height) {
d.potentialClickBand = this;
}
});
}
});
// Update toplevel drag dimension
d.parcatsViewModel.dragDimension = d;
// Remove hover label if any
Fx.loneUnhover(d.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());
}
/**
* Handle dimension drag
* @param {DimensionViewModel} d
*/
function dragDimension(d) {
// Check if dragging is supported
if (d.parcatsViewModel.arrangement === 'fixed') {
return;
}
d.dragHasMoved = true;
if (d.dragDimensionDisplayInd === null) {
return;
}
var dragDimInd = d.dragDimensionDisplayInd;
var prevDimInd = dragDimInd - 1;
var nextDimInd = dragDimInd + 1;
var dragDimension = d.parcatsViewModel.dimensions[dragDimInd];
// Update category
if (d.dragCategoryDisplayInd !== null) {
var dragCategory = dragDimension.categories[d.dragCategoryDisplayInd];
// Update dragY by dy
dragCategory.model.dragY += d3.event.dy;
var categoryY = dragCategory.model.dragY;
// Check for category drag swaps
var catDisplayInd = dragCategory.model.displayInd;
var dimCategoryViews = dragDimension.categories;
var catAbove = dimCategoryViews[catDisplayInd - 1];
var catBelow = dimCategoryViews[catDisplayInd + 1];
// Check for overlap above
if (catAbove !== undefined) {
if (categoryY < catAbove.y + catAbove.height / 2.0) {
// Swap display inds
dragCategory.model.displayInd = catAbove.model.displayInd;
catAbove.model.displayInd = catDisplayInd;
}
}
if (catBelow !== undefined) {
if (categoryY + dragCategory.height > catBelow.y + catBelow.height / 2.0) {
// Swap display inds
dragCategory.model.displayInd = catBelow.model.displayInd;
catBelow.model.displayInd = catDisplayInd;
}
}
// Update category drag display index
d.dragCategoryDisplayInd = dragCategory.model.displayInd;
}
// Update dimension position
if (d.dragCategoryDisplayInd === null || d.parcatsViewModel.arrangement === 'freeform') {
dragDimension.model.dragX = d3.event.x;
// Check for dimension swaps
var prevDimension = d.parcatsViewModel.dimensions[prevDimInd];
var nextDimension = d.parcatsViewModel.dimensions[nextDimInd];
if (prevDimension !== undefined) {
if (dragDimension.model.dragX < prevDimension.x + prevDimension.width) {
// Swap display inds
dragDimension.model.displayInd = prevDimension.model.displayInd;
prevDimension.model.displayInd = dragDimInd;
}
}
if (nextDimension !== undefined) {
if (dragDimension.model.dragX + dragDimension.width > nextDimension.x) {
// Swap display inds
dragDimension.model.displayInd = nextDimension.model.displayInd;
nextDimension.model.displayInd = d.dragDimensionDisplayInd;
}
}
// Update drag display index
d.dragDimensionDisplayInd = dragDimension.model.displayInd;
}
// Update view models
updateDimensionViewModels(d.parcatsViewModel);
updatePathViewModels(d.parcatsViewModel);
// Update svg geometry
updateSvgCategories(d.parcatsViewModel);
updateSvgPaths(d.parcatsViewModel);
}
/**
* Handle dimension drag end
* @param {DimensionViewModel} d
*/
function dragDimensionEnd(d) {
// Check if dragging is supported
if (d.parcatsViewModel.arrangement === 'fixed') {
return;
}
if (d.dragDimensionDisplayInd === null) {
return;
}
d3.select(this).selectAll('text').attr('font-weight', 'normal');
// Compute restyle command
// -----------------------
var restyleData = {};
var traceInd = getTraceIndex(d.parcatsViewModel);
// ### Handle dimension reordering ###
var finalDragDimensionDisplayInds = d.parcatsViewModel.model.dimensions.map(function (d) {
return d.displayInd;
});
var anyDimsReordered = d.initialDragDimensionDisplayInds.some(function (initDimDisplay, dimInd) {
return initDimDisplay !== finalDragDimensionDisplayInds[dimInd];
});
if (anyDimsReordered) {
finalDragDimensionDisplayInds.forEach(function (finalDimDisplay, dimInd) {
var containerInd = d.parcatsViewModel.model.dimensions[dimInd].containerInd;
restyleData['dimensions[' + containerInd + '].displayindex'] = finalDimDisplay;
});
}
// ### Handle category reordering ###
var anyCatsReordered = false;
if (d.dragCategoryDisplayInd !== null) {
var finalDragCategoryDisplayInds = d.model.categories.map(function (c) {
return c.displayInd;
});
anyCatsReordered = d.initialDragCategoryDisplayInds.some(function (initCatDisplay, catInd) {
return initCatDisplay !== finalDragCategoryDisplayInds[catInd];
});
if (anyCatsReordered) {
// Sort a shallow copy of the category models by display index
var sortedCategoryModels = d.model.categories.slice().sort(function (a, b) {
return a.displayInd - b.displayInd;
});
// Get new categoryarray and ticktext values
var newCategoryArray = sortedCategoryModels.map(function (v) {
return v.categoryValue;
});
var newCategoryLabels = sortedCategoryModels.map(function (v) {
return v.categoryLabel;
});
restyleData['dimensions[' + d.model.containerInd + '].categoryarray'] = [newCategoryArray];
restyleData['dimensions[' + d.model.containerInd + '].ticktext'] = [newCategoryLabels];
restyleData['dimensions[' + d.model.containerInd + '].categoryorder'] = 'array';
}
}
// Handle potential click event
// ----------------------------
if (d.parcatsViewModel.hoverinfoItems.indexOf('skip') === -1) {
if (!d.dragHasMoved && d.potentialClickBand) {
if (d.parcatsViewModel.hoveron === 'color') {
emitPointsEventColorHovermode(d.potentialClickBand, 'plotly_click', d3.event.sourceEvent);
} else {
emitPointsEventCategoryHovermode(d.potentialClickBand, 'plotly_click', d3.event.sourceEvent);
}
}
}
// Nullify drag states
// -------------------
d.model.dragX = null;
if (d.dragCategoryDisplayInd !== null) {
var dragCategory = d.parcatsViewModel.dimensions[d.dragDimensionDisplayInd].categories[d.dragCategoryDisplayInd];
dragCategory.model.dragY = null;
d.dragCategoryDisplayInd = null;
}
d.dragDimensionDisplayInd = null;
d.parcatsViewModel.dragDimension = null;
d.dragHasMoved = null;
d.potentialClickBand = null;
// Update view models
// ------------------
updateDimensionViewModels(d.parcatsViewModel);
updatePathViewModels(d.parcatsViewModel);
// Perform transition
// ------------------
var transition = d3.transition().duration(300).ease('cubic-in-out');
transition.each(function () {
updateSvgCategories(d.parcatsViewModel, true);
updateSvgPaths(d.parcatsViewModel, true);
}).each('end', function () {
if (anyDimsReordered || anyCatsReordered) {
// Perform restyle if the order of categories or dimensions changed
Plotly.restyle(d.parcatsViewModel.graphDiv, restyleData, [traceInd]);
}
});
}
/**
*
* @param {ParcatsViewModel} parcatsViewModel
*/
function getTraceIndex(parcatsViewModel) {
var traceInd;
var allTraces = parcatsViewModel.graphDiv._fullData;
for (var i = 0; i < allTraces.length; i++) {
if (parcatsViewModel.key === allTraces[i].uid) {
traceInd = i;
break;
}
}
return traceInd;
}
/** Update the svg paths for view model
* @param {ParcatsViewModel} parcatsViewModel
* @param {boolean} hasTransition Whether to update element with transition
*/
function updateSvgPaths(parcatsViewModel, hasTransition) {
if (hasTransition === undefined) {
hasTransition = false;
}
function transition(selection) {
return hasTransition ? selection.transition() : selection;
}
// Update binding
parcatsViewModel.pathSelection.data(function (d) {
return d.paths;
}, key);
// Update paths
transition(parcatsViewModel.pathSelection).attr('d', function (d) {
return d.svgD;
});
}
/** Update the svg paths for view model
* @param {ParcatsViewModel} parcatsViewModel
* @param {boolean} hasTransition Whether to update element with transition
*/
function updateSvgCategories(parcatsViewModel, hasTransition) {
if (hasTransition === undefined) {
hasTransition = false;
}
function transition(selection) {
return hasTransition ? selection.transition() : selection;
}
// Update binding
parcatsViewModel.dimensionSelection.data(function (d) {
return d.dimensions;
}, key);
var categorySelection = parcatsViewModel.dimensionSelection.selectAll('g.category').data(function (d) {
return d.categories;
}, key);
// Update dimension position
transition(parcatsViewModel.dimensionSelection).attr('transform', function (d) {
return strTranslate(d.x, 0);
});
// Update category position
transition(categorySelection).attr('transform', function (d) {
return strTranslate(0, d.y);
});
var dimLabelSelection = categorySelection.select('.dimlabel');
// ### Update dimension label
// Only the top-most display category should have the dimension label
dimLabelSelection.text(function (d, i) {
if (i === 0) {
// Add dimension label above topmost category
return d.parcatsViewModel.model.dimensions[d.model.dimensionInd].dimensionLabel;
} else {
return null;
}
});
// Update category label
// Categories in the right-most display dimension have their labels on
// the right, all others on the left
var catLabelSelection = categorySelection.select('.catlabel');
catLabelSelection.attr('text-anchor', function (d) {
if (catInRightDim(d)) {
// Place label to the right of category
return 'start';
} else {
// Place label to the left of category
return 'end';
}
}).attr('x', function (d) {
if (catInRightDim(d)) {
// Place label to the right of category
return d.width + 5;
} else {
// Place label to the left of category
return -5;
}
}).each(function (d) {
// Update attriubutes of elements
var newX;
var newAnchor;
if (catInRightDim(d)) {
// Place label to the right of category
newX = d.width + 5;
newAnchor = 'start';
} else {
// Place label to the left of category
newX = -5;
newAnchor = 'end';
}
d3.select(this).selectAll('tspan').attr('x', newX).attr('text-anchor', newAnchor);
});
// Update bands
// Initialize color band rects
var bandSelection = categorySelection.selectAll('rect.bandrect').data( /** @param {CategoryViewModel} catViewModel*/
function (catViewModel) {
return catViewModel.bands;
}, key);
var bandsSelectionEnter = bandSelection.enter().append('rect').attr('class', 'bandrect').attr('cursor', 'move').attr('stroke-opacity', 0).attr('fill', function (d) {
return d.color;
}).attr('fill-opacity', 0);
bandSelection.attr('fill', function (d) {
return d.color;
}).attr('width', function (d) {
return d.width;
}).attr('height', function (d) {
return d.height;
}).attr('y', function (d) {
return d.y;
});
styleBandsNoHover(bandsSelectionEnter);
// Raise bands to the top
bandSelection.each(function () {
Lib.raiseToTop(this);
});
// Remove unused bands
bandSelection.exit().remove();
}
/**
* Create a ParcatsViewModel traces
* @param {Object} graphDiv
* Top-level graph div element
* @param {Layout} layout
* SVG layout object
* @param {Array.} wrappedParcatsModel
* Wrapped ParcatsModel for this trace
* @return {ParcatsViewModel}
*/
function createParcatsViewModel(graphDiv, layout, wrappedParcatsModel) {
// Unwrap model
var parcatsModel = wrappedParcatsModel[0];
// Compute margin
var margin = layout.margin || {
l: 80,
r: 80,
t: 100,
b: 80
};
// Compute pixel position/extents
var trace = parcatsModel.trace;
var domain = trace.domain;
var figureWidth = layout.width;
var figureHeight = layout.height;
var traceWidth = Math.floor(figureWidth * (domain.x[1] - domain.x[0]));
var traceHeight = Math.floor(figureHeight * (domain.y[1] - domain.y[0]));
var traceX = domain.x[0] * figureWidth + margin.l;
var traceY = layout.height - domain.y[1] * layout.height + margin.t;
// Handle path shape
// -----------------
var pathShape = trace.line.shape;
// Handle hover info
// -----------------
var hoverinfoItems;
if (trace.hoverinfo === 'all') {
hoverinfoItems = ['count', 'probability'];
} else {
hoverinfoItems = (trace.hoverinfo || '').split('+');
}
// Construct parcatsViewModel
// --------------------------
var parcatsViewModel = {
trace: trace,
key: trace.uid,
model: parcatsModel,
x: traceX,
y: traceY,
width: traceWidth,
height: traceHeight,
hoveron: trace.hoveron,
hoverinfoItems: hoverinfoItems,
arrangement: trace.arrangement,
bundlecolors: trace.bundlecolors,
sortpaths: trace.sortpaths,
labelfont: trace.labelfont,
categorylabelfont: trace.tickfont,
pathShape: pathShape,
dragDimension: null,
margin: margin,
paths: [],
dimensions: [],
graphDiv: graphDiv,
traceSelection: null,
pathSelection: null,
dimensionSelection: null
};
// Update dimension view models if we have at least 1 dimension
if (parcatsModel.dimensions) {
updateDimensionViewModels(parcatsViewModel);
// Update path view models if we have at least 2 dimensions
updatePathViewModels(parcatsViewModel);
}
// Inside a categories view model
return parcatsViewModel;
}
/**
* Build the SVG string to represents a parallel categories path
* @param {Array.} leftXPositions
* Array of the x positions of the left edge of each dimension (in display order)
* @param {Array.} pathYs
* Array of the y positions of the top of the path at each dimension (in display order)
* @param {Array.} dimWidths
* Array of the widths of each dimension in display order
* @param {Number} pathHeight
* The height of the path in pixels
* @param {Number} curvature
* The curvature factor for the path. 0 results in a straight line and values greater than zero result in curved paths
* @return {string}
*/
function buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, curvature) {
// Compute the x midpoint of each path segment
var xRefPoints1 = [];
var xRefPoints2 = [];
var refInterpolator;
var d;
for (d = 0; d < dimWidths.length - 1; d++) {
refInterpolator = interpolateNumber(dimWidths[d] + leftXPositions[d], leftXPositions[d + 1]);
xRefPoints1.push(refInterpolator(curvature));
xRefPoints2.push(refInterpolator(1 - curvature));
}
// Move to top of path on left edge of left-most category
var svgD = 'M ' + leftXPositions[0] + ',' + pathYs[0];
// Horizontal line to right edge
svgD += 'l' + dimWidths[0] + ',0 ';
// Horizontal line to right edge
for (d = 1; d < dimWidths.length; d++) {
// Curve to left edge of category
svgD += 'C' + xRefPoints1[d - 1] + ',' + pathYs[d - 1] + ' ' + xRefPoints2[d - 1] + ',' + pathYs[d] + ' ' + leftXPositions[d] + ',' + pathYs[d];
// svgD += 'L' + leftXPositions[d] + ',' + pathYs[d];
// Horizontal line to right edge
svgD += 'l' + dimWidths[d] + ',0 ';
}
// Line down
svgD += 'l' + '0,' + pathHeight + ' ';
// Line to left edge of right-most category
svgD += 'l -' + dimWidths[dimWidths.length - 1] + ',0 ';
for (d = dimWidths.length - 2; d >= 0; d--) {
// Curve to right edge of category
svgD += 'C' + xRefPoints2[d] + ',' + (pathYs[d + 1] + pathHeight) + ' ' + xRefPoints1[d] + ',' + (pathYs[d] + pathHeight) + ' ' + (leftXPositions[d] + dimWidths[d]) + ',' + (pathYs[d] + pathHeight);
// svgD += 'L' + (leftXPositions[d] + dimWidths[d]) + ',' + (pathYs[d] + pathHeight);
// Horizontal line to right edge
svgD += 'l-' + dimWidths[d] + ',0 ';
}
// Close path
svgD += 'Z';
return svgD;
}
/**
* Update the path view models based on the dimension view models in a ParcatsViewModel
*
* @param {ParcatsViewModel} parcatsViewModel
* View model for trace
*/
function updatePathViewModels(parcatsViewModel) {
// Initialize an array of the y position of the top of the next path to be added to each category.
//
// nextYPositions[d][c] is the y position of the next path through category with index c of dimension with index d
var dimensionViewModels = parcatsViewModel.dimensions;
var parcatsModel = parcatsViewModel.model;
var nextYPositions = dimensionViewModels.map(function (d) {
return d.categories.map(function (c) {
return c.y;
});
});
// Array from category index to category display index for each true dimension index
var catToDisplayIndPerDim = parcatsViewModel.model.dimensions.map(function (d) {
return d.categories.map(function (c) {
return c.displayInd;
});
});
// Array from true dimension index to dimension display index
var dimToDisplayInd = parcatsViewModel.model.dimensions.map(function (d) {
return d.displayInd;
});
var displayToDimInd = parcatsViewModel.dimensions.map(function (d) {
return d.model.dimensionInd;
});
// Array of the x position of the left edge of the rectangles for each dimension
var leftXPositions = dimensionViewModels.map(function (d) {
return d.x;
});
// Compute dimension widths
var dimWidths = dimensionViewModels.map(function (d) {
return d.width;
});
// Build sorted Array of PathModel objects
var pathModels = [];
for (var p in parcatsModel.paths) {
if (parcatsModel.paths.hasOwnProperty(p)) {
pathModels.push(parcatsModel.paths[p]);
}
}
// Compute category display inds to use for sorting paths
function pathDisplayCategoryInds(pathModel) {
var dimensionInds = pathModel.categoryInds.map(function (catInd, dimInd) {
return catToDisplayIndPerDim[dimInd][catInd];
});
var displayInds = displayToDimInd.map(function (dimInd) {
return dimensionInds[dimInd];
});
return displayInds;
}
// Sort in ascending order by display index array
pathModels.sort(function (v1, v2) {
// Build display inds for each path
var sortArray1 = pathDisplayCategoryInds(v1);
var sortArray2 = pathDisplayCategoryInds(v2);
// Handle path sort order
if (parcatsViewModel.sortpaths === 'backward') {
sortArray1.reverse();
sortArray2.reverse();
}
// Append the first value index of the path to break ties
sortArray1.push(v1.valueInds[0]);
sortArray2.push(v2.valueInds[0]);
// Handle color bundling
if (parcatsViewModel.bundlecolors) {
// Prepend sort array with the raw color value
sortArray1.unshift(v1.rawColor);
sortArray2.unshift(v2.rawColor);
}
// colors equal, sort by display categories
if (sortArray1 < sortArray2) {
return -1;
}
if (sortArray1 > sortArray2) {
return 1;
}
return 0;
});
// Create path models
var pathViewModels = new Array(pathModels.length);
var totalCount = dimensionViewModels[0].model.count;
var totalHeight = dimensionViewModels[0].categories.map(function (c) {
return c.height;
}).reduce(function (v1, v2) {
return v1 + v2;
});
for (var pathNumber = 0; pathNumber < pathModels.length; pathNumber++) {
var pathModel = pathModels[pathNumber];
var pathHeight;
if (totalCount > 0) {
pathHeight = totalHeight * (pathModel.count / totalCount);
} else {
pathHeight = 0;
}
// Build path y coords
var pathYs = new Array(nextYPositions.length);
for (var d = 0; d < pathModel.categoryInds.length; d++) {
var catInd = pathModel.categoryInds[d];
var catDisplayInd = catToDisplayIndPerDim[d][catInd];
var dimDisplayInd = dimToDisplayInd[d];
// Update next y position
pathYs[dimDisplayInd] = nextYPositions[dimDisplayInd][catDisplayInd];
nextYPositions[dimDisplayInd][catDisplayInd] += pathHeight;
// Update category color information
var catViewModle = parcatsViewModel.dimensions[dimDisplayInd].categories[catDisplayInd];
var numBands = catViewModle.bands.length;
var lastCatBand = catViewModle.bands[numBands - 1];
if (lastCatBand === undefined || pathModel.rawColor !== lastCatBand.rawColor) {
// Create a new band
var bandY = lastCatBand === undefined ? 0 : lastCatBand.y + lastCatBand.height;
catViewModle.bands.push({
key: bandY,
color: pathModel.color,
rawColor: pathModel.rawColor,
height: pathHeight,
width: catViewModle.width,
count: pathModel.count,
y: bandY,
categoryViewModel: catViewModle,
parcatsViewModel: parcatsViewModel
});
} else {
// Extend current band
var currentBand = catViewModle.bands[numBands - 1];
currentBand.height += pathHeight;
currentBand.count += pathModel.count;
}
}
// build svg path
var svgD;
if (parcatsViewModel.pathShape === 'hspline') {
svgD = buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, 0.5);
} else {
svgD = buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, 0);
}
pathViewModels[pathNumber] = {
key: pathModel.valueInds[0],
model: pathModel,
height: pathHeight,
leftXs: leftXPositions,
topYs: pathYs,
dimWidths: dimWidths,
svgD: svgD,
parcatsViewModel: parcatsViewModel
};
}
parcatsViewModel.paths = pathViewModels;
// * @property key
// * Unique key for this model
// * @property {PathModel} model
// * Source path model
// * @property {Number} height
// * Height of this path (pixels)
// * @property {String} svgD
// * SVG path "d" attribute string
}
/**
* Update the dimension view models based on the dimension models in a ParcatsViewModel
*
* @param {ParcatsViewModel} parcatsViewModel
* View model for trace
*/
function updateDimensionViewModels(parcatsViewModel) {
// Compute dimension ordering
var dimensionsIndInfo = parcatsViewModel.model.dimensions.map(function (d) {
return {
displayInd: d.displayInd,
dimensionInd: d.dimensionInd
};
});
dimensionsIndInfo.sort(function (a, b) {
return a.displayInd - b.displayInd;
});
var dimensions = [];
for (var displayInd in dimensionsIndInfo) {
var dimensionInd = dimensionsIndInfo[displayInd].dimensionInd;
var dimModel = parcatsViewModel.model.dimensions[dimensionInd];
dimensions.push(createDimensionViewModel(parcatsViewModel, dimModel));
}
parcatsViewModel.dimensions = dimensions;
}
/**
* Create a parcats DimensionViewModel
*
* @param {ParcatsViewModel} parcatsViewModel
* View model for trace
* @param {DimensionModel} dimensionModel
* @return {DimensionViewModel}
*/
function createDimensionViewModel(parcatsViewModel, dimensionModel) {
// Compute dimension x position
var categoryLabelPad = 40;
var dimWidth = 16;
var numDimensions = parcatsViewModel.model.dimensions.length;
var displayInd = dimensionModel.displayInd;
// Compute x coordinate values
var dimDx;
var dimX0;
var dimX;
if (numDimensions > 1) {
dimDx = (parcatsViewModel.width - 2 * categoryLabelPad - dimWidth) / (numDimensions - 1);
} else {
dimDx = 0;
}
dimX0 = categoryLabelPad;
dimX = dimX0 + dimDx * displayInd;
// Compute categories
var categories = [];
var maxCats = parcatsViewModel.model.maxCats;
var numCats = dimensionModel.categories.length;
var catSpacing = 8;
var totalCount = dimensionModel.count;
var totalHeight = parcatsViewModel.height - catSpacing * (maxCats - 1);
var nextCatHeight;
var nextCatModel;
var nextCat;
var catInd;
var catDisplayInd;
// Compute starting Y offset
var nextCatY = (maxCats - numCats) * catSpacing / 2.0;
// Compute category ordering
var categoryIndInfo = dimensionModel.categories.map(function (c) {
return {
displayInd: c.displayInd,
categoryInd: c.categoryInd
};
});
categoryIndInfo.sort(function (a, b) {
return a.displayInd - b.displayInd;
});
for (catDisplayInd = 0; catDisplayInd < numCats; catDisplayInd++) {
catInd = categoryIndInfo[catDisplayInd].categoryInd;
nextCatModel = dimensionModel.categories[catInd];
if (totalCount > 0) {
nextCatHeight = nextCatModel.count / totalCount * totalHeight;
} else {
nextCatHeight = 0;
}
nextCat = {
key: nextCatModel.valueInds[0],
model: nextCatModel,
width: dimWidth,
height: nextCatHeight,
y: nextCatModel.dragY !== null ? nextCatModel.dragY : nextCatY,
bands: [],
parcatsViewModel: parcatsViewModel
};
nextCatY = nextCatY + nextCatHeight + catSpacing;
categories.push(nextCat);
}
return {
key: dimensionModel.dimensionInd,
x: dimensionModel.dragX !== null ? dimensionModel.dragX : dimX,
y: 0,
width: dimWidth,
model: dimensionModel,
categories: categories,
parcatsViewModel: parcatsViewModel,
dragCategoryDisplayInd: null,
dragDimensionDisplayInd: null,
initialDragDimensionDisplayInds: null,
initialDragCategoryDisplayInds: null,
dragHasMoved: null,
potentialClickBand: null
};
}
// JSDoc typedefs
// ==============
/**
* @typedef {Object} Layout
* Object containing svg layout information
*
* @property {Number} width (pixels)
* Usable width for Figure (after margins are removed)
* @property {Number} height (pixels)
* Usable height for Figure (after margins are removed)
* @property {Margin} margin
* Margin around the Figure (pixels)
*/
/**
* @typedef {Object} Margin
* Object containing padding information in pixels
*
* @property {Number} t
* Top margin
* @property {Number} r
* Right margin
* @property {Number} b
* Bottom margin
* @property {Number} l
* Left margin
*/
/**
* @typedef {Object} Font
* Object containing font information
*
* @property {Number} size: Font size
* @property {String} color: Font color
* @property {String} family: Font family
*/
/**
* @typedef {Object} ParcatsViewModel
* Object containing calculated parcats view information
*
* These are quantities that require Layout information to calculate
* @property key
* Unique key for this model
* @property {ParcatsModel} model
* Source parcats model
* @property {Array.} dimensions
* Array of dimension view models
* @property {Number} width
* Width for this trace (pixels)
* @property {Number} height
* Height for this trace (pixels)
* @property {Number} x
* X position of this trace with respect to the Figure (pixels)
* @property {Number} y
* Y position of this trace with respect to the Figure (pixels)
* @property {String} hoveron
* Hover interaction mode. One of: 'category', 'color', or 'dimension'
* @property {Array.} hoverinfoItems
* Info to display on hover. Array with a combination of 'counts' and/or 'probabilities', or 'none', or 'skip'
* @property {String} arrangement
* Category arrangement. One of: 'perpendicular', 'freeform', or 'fixed'
* @property {Boolean} bundlecolors
* Whether paths should be sorted so that like colors are bundled together as they pass through categories
* @property {String} sortpaths
* If 'forward' then sort paths based on dimensions from left to right. If 'backward' sort based on dimensions
* from right to left
* @property {Font} labelfont
* Font for the dimension labels
* @property {Font} categorylabelfont
* Font for the category labels
* @property {String} pathShape
* The shape of the paths. Either 'linear' or 'hspline'.
* @property {DimensionViewModel|null} dragDimension
* Dimension currently being dragged. Null if no drag in progress
* @property {Margin} margin
* Margin around the Figure
* @property {Object} graphDiv
* Top-level graph div element
* @property {Object} traceSelection
* D3 selection of this view models trace group element
* @property {Object} pathSelection
* D3 selection of this view models path elements
* @property {Object} dimensionSelection
* D3 selection of this view models dimension group element
*/
/**
* @typedef {Object} DimensionViewModel
* Object containing calculated parcats dimension view information
*
* These are quantities that require Layout information to calculate
* @property key
* Unique key for this model
* @property {DimensionModel} model
* Source dimension model
* @property {Number} x
* X position of the center of this dimension with respect to the Figure (pixels)
* @property {Number} y
* Y position of the top of this dimension with respect to the Figure (pixels)
* @property {Number} width
* Width of categories in this dimension (pixels)
* @property {ParcatsViewModel} parcatsViewModel
* The parent trace's view model
* @property {Array.} categories
* Dimensions category view models
* @property {Number|null} dragCategoryDisplayInd
* Display index of category currently being dragged. null if no category is being dragged
* @property {Number|null} dragDimensionDisplayInd
* Display index of the dimension being dragged. null if no dimension is being dragged
* @property {Array.|null} initialDragDimensionDisplayInds
* Dimensions display indexes at the beginning of the current drag. null if no dimension is being dragged
* @property {Array.|null} initialDragCategoryDisplayInds
* Category display indexes for the at the beginning of the current drag. null if no category is being dragged
* @property {HTMLElement} potentialClickBand
* Band under mouse when current drag began. If no drag movement takes place then a click will be emitted for this
* band. Null if not drag in progress.
* @property {Boolean} dragHasMoved
* True if there is an active drag and the drag has moved. If drag doesn't move before being ended then
* this may be interpreted as a click. Null if no drag in progress
*/
/**
* @typedef {Object} CategoryViewModel
* Object containing calculated parcats category view information
*
* These are quantities that require Layout information to calculate
* @property key
* Unique key for this model
* @property {CategoryModel} model
* Source category model
* @property {Number} width
* Width for this category (pixels)
* @property {Number} height
* Height for this category (pixels)
* @property {Number} y
* Y position of this cateogry with respect to the Figure (pixels)
* @property {Array.} bands
* Array of color bands inside the category
* @property {ParcatsViewModel} parcatsViewModel
* The parent trace's view model
*/
/**
* @typedef {Object} CategoryBandViewModel
* Object containing calculated category band information. A category band is a region inside a category covering
* paths of a single color
*
* @property key
* Unique key for this model
* @property color
* Band color
* @property rawColor
* Raw color value for band
* @property {Number} width
* Band width
* @property {Number} height
* Band height
* @property {Number} y
* Y position of top of the band with respect to the category
* @property {Number} count
* The number of samples represented by the band
* @property {CategoryViewModel} categoryViewModel
* The parent categorie's view model
* @property {ParcatsViewModel} parcatsViewModel
* The parent trace's view model
*/
/**
* @typedef {Object} PathViewModel
* Object containing calculated parcats path view information
*
* These are quantities that require Layout information to calculate
* @property key
* Unique key for this model
* @property {PathModel} model
* Source path model
* @property {Number} height
* Height of this path (pixels)
* @property {Array.} leftXs
* The x position of the left edge of each display dimension
* @property {Array.} topYs
* The y position of the top of the path for each display dimension
* @property {Array.} dimWidths
* The width of each display dimension
* @property {String} svgD
* SVG path "d" attribute string
* @property {ParcatsViewModel} parcatsViewModel
* The parent trace's view model
*/
/***/ }),
/***/ 60268:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var parcats = __webpack_require__(51036);
/**
* Create / update parcat traces
*
* @param {Object} graphDiv
* @param {Array.} parcatsModels
*/
module.exports = function plot(graphDiv, parcatsModels, transitionOpts, makeOnCompleteCallback) {
var fullLayout = graphDiv._fullLayout;
var svg = fullLayout._paper;
var size = fullLayout._size;
parcats(graphDiv, svg, parcatsModels, {
width: size.w,
height: size.h,
margin: {
t: size.t,
r: size.r,
b: size.b,
l: size.l
}
}, transitionOpts, makeOnCompleteCallback);
};
/***/ }),
/***/ 82296:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorScaleAttrs = __webpack_require__(49084);
var axesAttrs = __webpack_require__(94724);
var fontAttrs = __webpack_require__(25376);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
var templatedArray = (__webpack_require__(31780).templatedArray);
module.exports = {
domain: domainAttrs({
name: 'parcoords',
trace: true,
editType: 'plot'
}),
labelangle: {
valType: 'angle',
dflt: 0,
editType: 'plot'
},
labelside: {
valType: 'enumerated',
values: ['top', 'bottom'],
dflt: 'top',
editType: 'plot'
},
labelfont: fontAttrs({
editType: 'plot'
}),
tickfont: fontAttrs({
autoShadowDflt: true,
editType: 'plot'
}),
rangefont: fontAttrs({
editType: 'plot'
}),
dimensions: templatedArray('dimension', {
label: {
valType: 'string',
editType: 'plot'
},
// TODO: better way to determine ordinal vs continuous axes,
// so users can use tickvals/ticktext with a continuous axis.
tickvals: extendFlat({}, axesAttrs.tickvals, {
editType: 'plot'
}),
ticktext: extendFlat({}, axesAttrs.ticktext, {
editType: 'plot'
}),
tickformat: extendFlat({}, axesAttrs.tickformat, {
editType: 'plot'
}),
visible: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
range: {
valType: 'info_array',
items: [{
valType: 'number',
editType: 'plot'
}, {
valType: 'number',
editType: 'plot'
}],
editType: 'plot'
},
constraintrange: {
valType: 'info_array',
freeLength: true,
dimensions: '1-2',
items: [{
valType: 'any',
editType: 'plot'
}, {
valType: 'any',
editType: 'plot'
}],
editType: 'plot'
},
multiselect: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
values: {
valType: 'data_array',
editType: 'calc'
},
editType: 'calc'
}),
line: extendFlat({
editType: 'calc'
}, colorScaleAttrs('line', {
// the default autocolorscale isn't quite usable for parcoords due to context ambiguity around 0 (grey, off-white)
// autocolorscale therefore defaults to false too, to avoid being overridden by the blue-white-red autocolor palette
colorscaleDflt: 'Viridis',
autoColorDflt: false,
editTypeOverride: 'calc'
})),
unselected: {
line: {
color: {
valType: 'color',
dflt: '#7f7f7f',
editType: 'plot'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 'auto',
editType: 'plot'
},
editType: 'plot'
},
editType: 'plot'
}
};
/***/ }),
/***/ 71864:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var c = __webpack_require__(30140);
var d3 = __webpack_require__(33428);
var keyFun = (__webpack_require__(71688).keyFun);
var repeat = (__webpack_require__(71688).repeat);
var sortAsc = (__webpack_require__(3400).sorterAsc);
var strTranslate = (__webpack_require__(3400).strTranslate);
var snapRatio = c.bar.snapRatio;
function snapOvershoot(v, vAdjacent) {
return v * (1 - snapRatio) + vAdjacent * snapRatio;
}
var snapClose = c.bar.snapClose;
function closeToCovering(v, vAdjacent) {
return v * (1 - snapClose) + vAdjacent * snapClose;
}
// snap for the low end of a range on an ordinal scale
// on an ordinal scale, always show some overshoot from the exact value,
// so it's clear we're covering it
// find the interval we're in, and snap to 1/4 the distance to the next
// these two could be unified at a slight loss of readability / perf
function ordinalScaleSnap(isHigh, a, v, existingRanges) {
if (overlappingExisting(v, existingRanges)) return v;
var dir = isHigh ? -1 : 1;
var first = 0;
var last = a.length - 1;
if (dir < 0) {
var tmp = first;
first = last;
last = tmp;
}
var aHere = a[first];
var aPrev = aHere;
for (var i = first; dir * i < dir * last; i += dir) {
var nextI = i + dir;
var aNext = a[nextI];
// very close to the previous - snap down to it
if (dir * v < dir * closeToCovering(aHere, aNext)) return snapOvershoot(aHere, aPrev);
if (dir * v < dir * aNext || nextI === last) return snapOvershoot(aNext, aHere);
aPrev = aHere;
aHere = aNext;
}
}
function overlappingExisting(v, existingRanges) {
for (var i = 0; i < existingRanges.length; i++) {
if (v >= existingRanges[i][0] && v <= existingRanges[i][1]) return true;
}
return false;
}
function barHorizontalSetup(selection) {
selection.attr('x', -c.bar.captureWidth / 2).attr('width', c.bar.captureWidth);
}
function backgroundBarHorizontalSetup(selection) {
selection.attr('visibility', 'visible').style('visibility', 'visible').attr('fill', 'yellow').attr('opacity', 0);
}
function setHighlight(d) {
if (!d.brush.filterSpecified) {
return '0,' + d.height;
}
var pixelRanges = unitToPx(d.brush.filter.getConsolidated(), d.height);
var dashArray = [0]; // we start with a 0 length selection as filter ranges are inclusive, not exclusive
var p, sectionHeight, iNext;
var currentGap = pixelRanges.length ? pixelRanges[0][0] : null;
for (var i = 0; i < pixelRanges.length; i++) {
p = pixelRanges[i];
sectionHeight = p[1] - p[0];
dashArray.push(currentGap);
dashArray.push(sectionHeight);
iNext = i + 1;
if (iNext < pixelRanges.length) {
currentGap = pixelRanges[iNext][0] - p[1];
}
}
dashArray.push(d.height);
// d.height is added at the end to ensure that (1) we have an even number of dasharray points, MDN page says
// "If an odd number of values is provided, then the list of values is repeated to yield an even number of values."
// and (2) it's _at least_ as long as the full height (even if range is minuscule and at the bottom) though this
// may not be necessary, maybe duplicating the last point would do too. But no harm in a longer dasharray than line.
return dashArray;
}
function unitToPx(unitRanges, height) {
return unitRanges.map(function (pr) {
return pr.map(function (v) {
return Math.max(0, v * height);
}).sort(sortAsc);
});
}
// is the cursor over the north, middle, or south of a bar?
// the end handles extend over the last 10% of the bar
function getRegion(fPix, y) {
var pad = c.bar.handleHeight;
if (y > fPix[1] + pad || y < fPix[0] - pad) return;
if (y >= 0.9 * fPix[1] + 0.1 * fPix[0]) return 'n';
if (y <= 0.9 * fPix[0] + 0.1 * fPix[1]) return 's';
return 'ns';
}
function clearCursor() {
d3.select(document.body).style('cursor', null);
}
function styleHighlight(selection) {
// stroke-dasharray is used to minimize the number of created DOM nodes, because the requirement calls for up to
// 1000 individual selections on an axis, and there can be 60 axes per parcoords, and multiple parcoords per
// dashboard. The technique is similar to https://codepen.io/monfera/pen/rLYqWR and using a `polyline` with
// multiple sections, or a `path` element via its `d` attribute would also be DOM-sparing alternatives.
selection.attr('stroke-dasharray', setHighlight);
}
function renderHighlight(root, tweenCallback) {
var bar = d3.select(root).selectAll('.highlight, .highlight-shadow');
var barToStyle = tweenCallback ? bar.transition().duration(c.bar.snapDuration).each('end', tweenCallback) : bar;
styleHighlight(barToStyle);
}
function getInterval(d, y) {
var b = d.brush;
var active = b.filterSpecified;
var closestInterval = NaN;
var out = {};
var i;
if (active) {
var height = d.height;
var intervals = b.filter.getConsolidated();
var pixIntervals = unitToPx(intervals, height);
var hoveredInterval = NaN;
var previousInterval = NaN;
var nextInterval = NaN;
for (i = 0; i <= pixIntervals.length; i++) {
var p = pixIntervals[i];
if (p && p[0] <= y && y <= p[1]) {
// over a bar
hoveredInterval = i;
break;
} else {
// between bars, or before/after the first/last bar
previousInterval = i ? i - 1 : NaN;
if (p && p[0] > y) {
nextInterval = i;
break; // no point continuing as intervals are non-overlapping and sorted; could use log search
}
}
}
closestInterval = hoveredInterval;
if (isNaN(closestInterval)) {
if (isNaN(previousInterval) || isNaN(nextInterval)) {
closestInterval = isNaN(previousInterval) ? nextInterval : previousInterval;
} else {
closestInterval = y - pixIntervals[previousInterval][1] < pixIntervals[nextInterval][0] - y ? previousInterval : nextInterval;
}
}
if (!isNaN(closestInterval)) {
var fPix = pixIntervals[closestInterval];
var region = getRegion(fPix, y);
if (region) {
out.interval = intervals[closestInterval];
out.intervalPix = fPix;
out.region = region;
}
}
}
if (d.ordinal && !out.region) {
var a = d.unitTickvals;
var unitLocation = d.unitToPaddedPx.invert(y);
for (i = 0; i < a.length; i++) {
var rangei = [a[Math.max(i - 1, 0)] * 0.25 + a[i] * 0.75, a[Math.min(i + 1, a.length - 1)] * 0.25 + a[i] * 0.75];
if (unitLocation >= rangei[0] && unitLocation <= rangei[1]) {
out.clickableOrdinalRange = rangei;
break;
}
}
}
return out;
}
function dragstart(lThis, d) {
d3.event.sourceEvent.stopPropagation();
var y = d.height - d3.mouse(lThis)[1] - 2 * c.verticalPadding;
var unitLocation = d.unitToPaddedPx.invert(y);
var b = d.brush;
var interval = getInterval(d, y);
var unitRange = interval.interval;
var s = b.svgBrush;
s.wasDragged = false; // we start assuming there won't be a drag - useful for reset
s.grabbingBar = interval.region === 'ns';
if (s.grabbingBar) {
var pixelRange = unitRange.map(d.unitToPaddedPx);
s.grabPoint = y - pixelRange[0] - c.verticalPadding;
s.barLength = pixelRange[1] - pixelRange[0];
}
s.clickableOrdinalRange = interval.clickableOrdinalRange;
s.stayingIntervals = d.multiselect && b.filterSpecified ? b.filter.getConsolidated() : [];
if (unitRange) {
s.stayingIntervals = s.stayingIntervals.filter(function (int2) {
return int2[0] !== unitRange[0] && int2[1] !== unitRange[1];
});
}
s.startExtent = interval.region ? unitRange[interval.region === 's' ? 1 : 0] : unitLocation;
d.parent.inBrushDrag = true;
s.brushStartCallback();
}
function drag(lThis, d) {
d3.event.sourceEvent.stopPropagation();
var y = d.height - d3.mouse(lThis)[1] - 2 * c.verticalPadding;
var s = d.brush.svgBrush;
s.wasDragged = true;
s._dragging = true;
if (s.grabbingBar) {
// moving the bar
s.newExtent = [y - s.grabPoint, y + s.barLength - s.grabPoint].map(d.unitToPaddedPx.invert);
} else {
// south/north drag or new bar creation
s.newExtent = [s.startExtent, d.unitToPaddedPx.invert(y)].sort(sortAsc);
}
d.brush.filterSpecified = true;
s.extent = s.stayingIntervals.concat([s.newExtent]);
s.brushCallback(d);
renderHighlight(lThis.parentNode);
}
function dragend(lThis, d) {
var brush = d.brush;
var filter = brush.filter;
var s = brush.svgBrush;
if (!s._dragging) {
// i.e. click
// mock zero drag
mousemove(lThis, d);
drag(lThis, d);
// remember it is a click not a drag
d.brush.svgBrush.wasDragged = false;
}
s._dragging = false;
var e = d3.event;
e.sourceEvent.stopPropagation();
var grabbingBar = s.grabbingBar;
s.grabbingBar = false;
s.grabLocation = undefined;
d.parent.inBrushDrag = false;
clearCursor(); // instead of clearing, a nicer thing would be to set it according to current location
if (!s.wasDragged) {
// a click+release on the same spot (ie. w/o dragging) means a bar or full reset
s.wasDragged = undefined; // logic-wise unneeded, just shows `wasDragged` has no longer a meaning
if (s.clickableOrdinalRange) {
if (brush.filterSpecified && d.multiselect) {
s.extent.push(s.clickableOrdinalRange);
} else {
s.extent = [s.clickableOrdinalRange];
brush.filterSpecified = true;
}
} else if (grabbingBar) {
s.extent = s.stayingIntervals;
if (s.extent.length === 0) {
brushClear(brush);
}
} else {
brushClear(brush);
}
s.brushCallback(d);
renderHighlight(lThis.parentNode);
s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []);
return; // no need to fuse intervals or snap to ordinals, so we can bail early
}
var mergeIntervals = function () {
// Key piece of logic: once the button is released, possibly overlapping intervals will be fused:
// Here it's done immediately on click release while on ordinal snap transition it's done at the end
filter.set(filter.getConsolidated());
};
if (d.ordinal) {
var a = d.unitTickvals;
if (a[a.length - 1] < a[0]) a.reverse();
s.newExtent = [ordinalScaleSnap(0, a, s.newExtent[0], s.stayingIntervals), ordinalScaleSnap(1, a, s.newExtent[1], s.stayingIntervals)];
var hasNewExtent = s.newExtent[1] > s.newExtent[0];
s.extent = s.stayingIntervals.concat(hasNewExtent ? [s.newExtent] : []);
if (!s.extent.length) {
brushClear(brush);
}
s.brushCallback(d);
if (hasNewExtent) {
// merging intervals post the snap tween
renderHighlight(lThis.parentNode, mergeIntervals);
} else {
// if no new interval, don't animate, just redraw the highlight immediately
mergeIntervals();
renderHighlight(lThis.parentNode);
}
} else {
mergeIntervals(); // merging intervals immediately
}
s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []);
}
function mousemove(lThis, d) {
var y = d.height - d3.mouse(lThis)[1] - 2 * c.verticalPadding;
var interval = getInterval(d, y);
var cursor = 'crosshair';
if (interval.clickableOrdinalRange) cursor = 'pointer';else if (interval.region) cursor = interval.region + '-resize';
d3.select(document.body).style('cursor', cursor);
}
function attachDragBehavior(selection) {
// There's some fiddling with pointer cursor styling so that the cursor preserves its shape while dragging a brush
// even if the cursor strays from the interacting bar, which is bound to happen as bars are thin and the user
// will inevitably leave the hotspot strip. In this regard, it does something similar to what the D3 brush would do.
selection.on('mousemove', function (d) {
d3.event.preventDefault();
if (!d.parent.inBrushDrag) mousemove(this, d);
}).on('mouseleave', function (d) {
if (!d.parent.inBrushDrag) clearCursor();
}).call(d3.behavior.drag().on('dragstart', function (d) {
dragstart(this, d);
}).on('drag', function (d) {
drag(this, d);
}).on('dragend', function (d) {
dragend(this, d);
}));
}
function startAsc(a, b) {
return a[0] - b[0];
}
function renderAxisBrush(axisBrush, paperColor, gd) {
var isStatic = gd._context.staticPlot;
var background = axisBrush.selectAll('.background').data(repeat);
background.enter().append('rect').classed('background', true).call(barHorizontalSetup).call(backgroundBarHorizontalSetup).style('pointer-events', isStatic ? 'none' : 'auto') // parent pointer events are disabled; we must have it to register events
.attr('transform', strTranslate(0, c.verticalPadding));
background.call(attachDragBehavior).attr('height', function (d) {
return d.height - c.verticalPadding;
});
var highlightShadow = axisBrush.selectAll('.highlight-shadow').data(repeat); // we have a set here, can't call it `extent`
highlightShadow.enter().append('line').classed('highlight-shadow', true).attr('x', -c.bar.width / 2).attr('stroke-width', c.bar.width + c.bar.strokeWidth).attr('stroke', paperColor).attr('opacity', c.bar.strokeOpacity).attr('stroke-linecap', 'butt');
highlightShadow.attr('y1', function (d) {
return d.height;
}).call(styleHighlight);
var highlight = axisBrush.selectAll('.highlight').data(repeat); // we have a set here, can't call it `extent`
highlight.enter().append('line').classed('highlight', true).attr('x', -c.bar.width / 2).attr('stroke-width', c.bar.width - c.bar.strokeWidth).attr('stroke', c.bar.fillColor).attr('opacity', c.bar.fillOpacity).attr('stroke-linecap', 'butt');
highlight.attr('y1', function (d) {
return d.height;
}).call(styleHighlight);
}
function ensureAxisBrush(axisOverlays, paperColor, gd) {
var axisBrush = axisOverlays.selectAll('.' + c.cn.axisBrush).data(repeat, keyFun);
axisBrush.enter().append('g').classed(c.cn.axisBrush, true);
renderAxisBrush(axisBrush, paperColor, gd);
}
function getBrushExtent(brush) {
return brush.svgBrush.extent.map(function (e) {
return e.slice();
});
}
function brushClear(brush) {
brush.filterSpecified = false;
brush.svgBrush.extent = [[-Infinity, Infinity]];
}
function axisBrushMoved(callback) {
return function axisBrushMoved(dimension) {
var brush = dimension.brush;
var extent = getBrushExtent(brush);
var newExtent = extent.slice();
brush.filter.set(newExtent);
callback();
};
}
function dedupeRealRanges(intervals) {
// Fuses elements of intervals if they overlap, yielding discontiguous intervals, results.length <= intervals.length
// Currently uses closed intervals, ie. dedupeRealRanges([[400, 800], [300, 400]]) -> [300, 800]
var queue = intervals.slice();
var result = [];
var currentInterval;
var current = queue.shift();
while (current) {
// [].shift === undefined, so we don't descend into an empty array
currentInterval = current.slice();
while ((current = queue.shift()) && current[0] <= /* right-open interval would need `<` */currentInterval[1]) {
currentInterval[1] = Math.max(currentInterval[1], current[1]);
}
result.push(currentInterval);
}
if (result.length === 1 && result[0][0] > result[0][1]) {
// discard result
result = [];
}
return result;
}
function makeFilter() {
var filter = [];
var consolidated;
var bounds;
return {
set: function (a) {
filter = a.map(function (d) {
return d.slice().sort(sortAsc);
}).sort(startAsc);
// handle unselected case
if (filter.length === 1 && filter[0][0] === -Infinity && filter[0][1] === Infinity) {
filter = [[0, -1]];
}
consolidated = dedupeRealRanges(filter);
bounds = filter.reduce(function (p, n) {
return [Math.min(p[0], n[0]), Math.max(p[1], n[1])];
}, [Infinity, -Infinity]);
},
get: function () {
return filter.slice();
},
getConsolidated: function () {
return consolidated;
},
getBounds: function () {
return bounds;
}
};
}
function makeBrush(state, rangeSpecified, initialRange, brushStartCallback, brushCallback, brushEndCallback) {
var filter = makeFilter();
filter.set(initialRange);
return {
filter: filter,
filterSpecified: rangeSpecified,
// there's a difference between not filtering and filtering a non-proper subset
svgBrush: {
extent: [],
// this is where the svgBrush writes contents into
brushStartCallback: brushStartCallback,
brushCallback: axisBrushMoved(brushCallback),
brushEndCallback: brushEndCallback
}
};
}
// for use by supplyDefaults, but it needed tons of pieces from here so
// seemed to make more sense just to put the whole routine here
function cleanRanges(ranges, dimension) {
if (Array.isArray(ranges[0])) {
ranges = ranges.map(function (ri) {
return ri.sort(sortAsc);
});
if (!dimension.multiselect) ranges = [ranges[0]];else ranges = dedupeRealRanges(ranges.sort(startAsc));
} else ranges = [ranges.sort(sortAsc)];
// ordinal snapping
if (dimension.tickvals) {
var sortedTickVals = dimension.tickvals.slice().sort(sortAsc);
ranges = ranges.map(function (ri) {
var rSnapped = [ordinalScaleSnap(0, sortedTickVals, ri[0], []), ordinalScaleSnap(1, sortedTickVals, ri[1], [])];
if (rSnapped[1] > rSnapped[0]) return rSnapped;
}).filter(function (ri) {
return ri;
});
if (!ranges.length) return;
}
return ranges.length > 1 ? ranges : ranges[0];
}
module.exports = {
makeBrush: makeBrush,
ensureAxisBrush: ensureAxisBrush,
cleanRanges: cleanRanges
};
/***/ }),
/***/ 61664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(82296),
supplyDefaults: __webpack_require__(60664),
calc: __webpack_require__(95044),
colorbar: {
container: 'line',
min: 'cmin',
max: 'cmax'
},
moduleType: 'trace',
name: 'parcoords',
basePlotModule: __webpack_require__(19976),
categories: ['gl', 'regl', 'noOpacity', 'noHover'],
meta: {}
};
/***/ }),
/***/ 19976:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var getModuleCalcData = (__webpack_require__(84888)/* .getModuleCalcData */ ._M);
var parcoordsPlot = __webpack_require__(24196);
var xmlnsNamespaces = __webpack_require__(9616);
exports.name = 'parcoords';
exports.plot = function (gd) {
var calcData = getModuleCalcData(gd.calcdata, 'parcoords')[0];
if (calcData.length) parcoordsPlot(gd, calcData);
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var hadParcoords = oldFullLayout._has && oldFullLayout._has('parcoords');
var hasParcoords = newFullLayout._has && newFullLayout._has('parcoords');
if (hadParcoords && !hasParcoords) {
oldFullLayout._paperdiv.selectAll('.parcoords').remove();
oldFullLayout._glimages.selectAll('*').remove();
}
};
exports.toSVG = function (gd) {
var imageRoot = gd._fullLayout._glimages;
var root = d3.select(gd).selectAll('.svg-container');
var canvases = root.filter(function (d, i) {
return i === root.size() - 1;
}).selectAll('.gl-canvas-context, .gl-canvas-focus');
function canvasToImage() {
var canvas = this;
var imageData = canvas.toDataURL('image/png');
var image = imageRoot.append('svg:image');
image.attr({
xmlns: xmlnsNamespaces.svg,
'xlink:href': imageData,
preserveAspectRatio: 'none',
x: 0,
y: 0,
width: canvas.style.width,
height: canvas.style.height
});
}
canvases.each(canvasToImage);
// Chrome / Safari bug workaround - browser apparently loses connection to the defined pattern
// Without the workaround, these browsers 'lose' the filter brush styling (color etc.) after a snapshot
// on a subsequent interaction.
// Firefox works fine without this workaround
window.setTimeout(function () {
d3.selectAll('#filterBarPattern').attr('id', 'filterBarPattern');
}, 60);
};
/***/ }),
/***/ 95044:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var Colorscale = __webpack_require__(8932);
var wrap = (__webpack_require__(71688).wrap);
module.exports = function calc(gd, trace) {
var lineColor;
var cscale;
if (Colorscale.hasColorscale(trace, 'line') && isArrayOrTypedArray(trace.line.color)) {
lineColor = trace.line.color;
cscale = Colorscale.extractOpts(trace.line).colorscale;
Colorscale.calc(gd, trace, {
vals: lineColor,
containerStr: 'line',
cLetter: 'c'
});
} else {
lineColor = constHalf(trace._length);
cscale = [[0, trace.line.color], [1, trace.line.color]];
}
return wrap({
lineColor: lineColor,
cscale: cscale
});
};
function constHalf(len) {
var out = new Array(len);
for (var i = 0; i < len; i++) {
out[i] = 0.5;
}
return out;
}
/***/ }),
/***/ 30140:
/***/ (function(module) {
"use strict";
module.exports = {
maxDimensionCount: 60,
// this cannot be increased without WebGL code refactoring
overdrag: 45,
verticalPadding: 2,
// otherwise, horizontal lines on top or bottom are of lower width
tickDistance: 50,
canvasPixelRatio: 1,
blockLineCount: 5000,
layers: ['contextLineLayer', 'focusLineLayer', 'pickLineLayer'],
axisTitleOffset: 28,
axisExtentOffset: 10,
bar: {
width: 4,
// Visible width of the filter bar
captureWidth: 10,
// Mouse-sensitive width for interaction (Fitts law)
fillColor: 'magenta',
// Color of the filter bar fill
fillOpacity: 1,
// Filter bar fill opacity
snapDuration: 150,
// tween duration in ms for brush snap for ordinal axes
snapRatio: 0.25,
// ratio of bar extension relative to the distance between two adjacent ordinal values
snapClose: 0.01,
// fraction of inter-value distance to snap to the closer one, even if you're not over it
strokeOpacity: 1,
// Filter bar side stroke opacity
strokeWidth: 1,
// Filter bar side stroke width in pixels
handleHeight: 8,
// Height of the filter bar vertical resize areas on top and bottom
handleOpacity: 1,
// Opacity of the filter bar vertical resize areas on top and bottom
handleOverlap: 0 // A larger than 0 value causes overlaps with the filter bar, represented as pixels
},
cn: {
axisExtentText: 'axis-extent-text',
parcoordsLineLayers: 'parcoords-line-layers',
parcoordsLineLayer: 'parcoords-lines',
parcoords: 'parcoords',
parcoordsControlView: 'parcoords-control-view',
yAxis: 'y-axis',
axisOverlays: 'axis-overlays',
axis: 'axis',
axisHeading: 'axis-heading',
axisTitle: 'axis-title',
axisExtent: 'axis-extent',
axisExtentTop: 'axis-extent-top',
axisExtentTopText: 'axis-extent-top-text',
axisExtentBottom: 'axis-extent-bottom',
axisExtentBottomText: 'axis-extent-bottom-text',
axisBrush: 'axis-brush'
},
id: {
filterBarPattern: 'filter-bar-pattern'
}
};
/***/ }),
/***/ 60664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var colorscaleDefaults = __webpack_require__(27260);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var handleArrayContainerDefaults = __webpack_require__(51272);
var Axes = __webpack_require__(54460);
var attributes = __webpack_require__(82296);
var axisBrush = __webpack_require__(71864);
var maxDimensionCount = (__webpack_require__(30140).maxDimensionCount);
var mergeLength = __webpack_require__(26284);
function handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
var lineColor = coerce('line.color', defaultColor);
if (hasColorscale(traceIn, 'line') && Lib.isArrayOrTypedArray(lineColor)) {
if (lineColor.length) {
coerce('line.colorscale');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'line.',
cLetter: 'c'
});
// TODO: I think it would be better to keep showing lines beyond the last line color
// but I'm not sure what color to give these lines - probably black or white
// depending on the background color?
return lineColor.length;
} else {
traceOut.line.color = defaultColor;
}
}
return Infinity;
}
function dimensionDefaults(dimensionIn, dimensionOut, parentOut, opts) {
function coerce(attr, dflt) {
return Lib.coerce(dimensionIn, dimensionOut, attributes.dimensions, attr, dflt);
}
var values = coerce('values');
var visible = coerce('visible');
if (!(values && values.length)) {
visible = dimensionOut.visible = false;
}
if (visible) {
coerce('label');
coerce('tickvals');
coerce('ticktext');
coerce('tickformat');
var range = coerce('range');
dimensionOut._ax = {
_id: 'y',
type: 'linear',
showexponent: 'all',
exponentformat: 'B',
range: range
};
Axes.setConvert(dimensionOut._ax, opts.layout);
coerce('multiselect');
var constraintRange = coerce('constraintrange');
if (constraintRange) {
dimensionOut.constraintrange = axisBrush.cleanRanges(constraintRange, dimensionOut);
}
}
}
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var dimensionsIn = traceIn.dimensions;
if (Array.isArray(dimensionsIn) && dimensionsIn.length > maxDimensionCount) {
Lib.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment');
dimensionsIn.splice(maxDimensionCount);
}
var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
name: 'dimensions',
layout: layout,
handleItemDefaults: dimensionDefaults
});
var len = handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
handleDomainDefaults(traceOut, layout, coerce);
if (!Array.isArray(dimensions) || !dimensions.length) {
traceOut.visible = false;
}
mergeLength(traceOut, dimensions, 'values', len);
// make default font size 10px (default is 12),
// scale linearly with global font size
var fontDflt = Lib.extendFlat({}, layout.font, {
size: Math.round(layout.font.size / 1.2)
});
Lib.coerceFont(coerce, 'labelfont', fontDflt);
Lib.coerceFont(coerce, 'tickfont', fontDflt, {
autoShadowDflt: true
});
Lib.coerceFont(coerce, 'rangefont', fontDflt);
coerce('labelangle');
coerce('labelside');
coerce('unselected.line.color');
coerce('unselected.line.opacity');
};
/***/ }),
/***/ 95724:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isTypedArray = (__webpack_require__(3400).isTypedArray);
exports.convertTypedArray = function (a) {
return isTypedArray(a) ? Array.prototype.slice.call(a) : a;
};
exports.isOrdinal = function (dimension) {
return !!dimension.tickvals;
};
exports.isVisible = function (dimension) {
return dimension.visible || !('visible' in dimension);
};
/***/ }),
/***/ 51352:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var vertexShaderSource = ['precision highp float;', '', 'varying vec4 fragColor;', '', 'attribute vec4 p01_04, p05_08, p09_12, p13_16,', ' p17_20, p21_24, p25_28, p29_32,', ' p33_36, p37_40, p41_44, p45_48,', ' p49_52, p53_56, p57_60, colors;', '', 'uniform mat4 dim0A, dim1A, dim0B, dim1B, dim0C, dim1C, dim0D, dim1D,', ' loA, hiA, loB, hiB, loC, hiC, loD, hiD;', '', 'uniform vec2 resolution, viewBoxPos, viewBoxSize;', 'uniform float maskHeight;', 'uniform float drwLayer; // 0: context, 1: focus, 2: pick', 'uniform vec4 contextColor;', 'uniform sampler2D maskTexture, palette;', '', 'bool isPick = (drwLayer > 1.5);', 'bool isContext = (drwLayer < 0.5);', '', 'const vec4 ZEROS = vec4(0.0, 0.0, 0.0, 0.0);', 'const vec4 UNITS = vec4(1.0, 1.0, 1.0, 1.0);', '', 'float val(mat4 p, mat4 v) {', ' return dot(matrixCompMult(p, v) * UNITS, UNITS);', '}', '', 'float axisY(float ratio, mat4 A, mat4 B, mat4 C, mat4 D) {', ' float y1 = val(A, dim0A) + val(B, dim0B) + val(C, dim0C) + val(D, dim0D);', ' float y2 = val(A, dim1A) + val(B, dim1B) + val(C, dim1C) + val(D, dim1D);', ' return y1 * (1.0 - ratio) + y2 * ratio;', '}', '', 'int iMod(int a, int b) {', ' return a - b * (a / b);', '}', '', 'bool fOutside(float p, float lo, float hi) {', ' return (lo < hi) && (lo > p || p > hi);', '}', '', 'bool vOutside(vec4 p, vec4 lo, vec4 hi) {', ' return (', ' fOutside(p[0], lo[0], hi[0]) ||', ' fOutside(p[1], lo[1], hi[1]) ||', ' fOutside(p[2], lo[2], hi[2]) ||', ' fOutside(p[3], lo[3], hi[3])', ' );', '}', '', 'bool mOutside(mat4 p, mat4 lo, mat4 hi) {', ' return (', ' vOutside(p[0], lo[0], hi[0]) ||', ' vOutside(p[1], lo[1], hi[1]) ||', ' vOutside(p[2], lo[2], hi[2]) ||', ' vOutside(p[3], lo[3], hi[3])', ' );', '}', '', 'bool outsideBoundingBox(mat4 A, mat4 B, mat4 C, mat4 D) {', ' return mOutside(A, loA, hiA) ||', ' mOutside(B, loB, hiB) ||', ' mOutside(C, loC, hiC) ||', ' mOutside(D, loD, hiD);', '}', '', 'bool outsideRasterMask(mat4 A, mat4 B, mat4 C, mat4 D) {', ' mat4 pnts[4];', ' pnts[0] = A;', ' pnts[1] = B;', ' pnts[2] = C;', ' pnts[3] = D;', '', ' for(int i = 0; i < 4; ++i) {', ' for(int j = 0; j < 4; ++j) {', ' for(int k = 0; k < 4; ++k) {', ' if(0 == iMod(', ' int(255.0 * texture2D(maskTexture,', ' vec2(', ' (float(i * 2 + j / 2) + 0.5) / 8.0,', ' (pnts[i][j][k] * (maskHeight - 1.0) + 1.0) / maskHeight', ' ))[3]', ' ) / int(pow(2.0, float(iMod(j * 4 + k, 8)))),', ' 2', ' )) return true;', ' }', ' }', ' }', ' return false;', '}', '', 'vec4 position(bool isContext, float v, mat4 A, mat4 B, mat4 C, mat4 D) {', ' float x = 0.5 * sign(v) + 0.5;', ' float y = axisY(x, A, B, C, D);', ' float z = 1.0 - abs(v);', '', ' z += isContext ? 0.0 : 2.0 * float(', ' outsideBoundingBox(A, B, C, D) ||', ' outsideRasterMask(A, B, C, D)', ' );', '', ' return vec4(', ' 2.0 * (vec2(x, y) * viewBoxSize + viewBoxPos) / resolution - 1.0,', ' z,', ' 1.0', ' );', '}', '', 'void main() {', ' mat4 A = mat4(p01_04, p05_08, p09_12, p13_16);', ' mat4 B = mat4(p17_20, p21_24, p25_28, p29_32);', ' mat4 C = mat4(p33_36, p37_40, p41_44, p45_48);', ' mat4 D = mat4(p49_52, p53_56, p57_60, ZEROS);', '', ' float v = colors[3];', '', ' gl_Position = position(isContext, v, A, B, C, D);', '', ' fragColor =', ' isContext ? vec4(contextColor) :', ' isPick ? vec4(colors.rgb, 1.0) : texture2D(palette, vec2(abs(v), 0.5));', '}'].join('\n');
var fragmentShaderSource = ['precision highp float;', '', 'varying vec4 fragColor;', '', 'void main() {', ' gl_FragColor = fragColor;', '}'].join('\n');
var maxDim = (__webpack_require__(30140).maxDimensionCount);
var Lib = __webpack_require__(3400);
// don't change; otherwise near/far plane lines are lost
var depthLimitEpsilon = 1e-6;
// precision of multiselect is the full range divided into this many parts
var maskHeight = 2048;
var dummyPixel = new Uint8Array(4);
var dataPixel = new Uint8Array(4);
var paletteTextureConfig = {
shape: [256, 1],
format: 'rgba',
type: 'uint8',
mag: 'nearest',
min: 'nearest'
};
function ensureDraw(regl) {
regl.read({
x: 0,
y: 0,
width: 1,
height: 1,
data: dummyPixel
});
}
function clear(regl, x, y, width, height) {
var gl = regl._gl;
gl.enable(gl.SCISSOR_TEST);
gl.scissor(x, y, width, height);
regl.clear({
color: [0, 0, 0, 0],
depth: 1
}); // clearing is done in scissored panel only
}
function renderBlock(regl, glAes, renderState, blockLineCount, sampleCount, item) {
var rafKey = item.key;
function render(blockNumber) {
var count = Math.min(blockLineCount, sampleCount - blockNumber * blockLineCount);
if (blockNumber === 0) {
// stop drawing possibly stale glyphs before clearing
window.cancelAnimationFrame(renderState.currentRafs[rafKey]);
delete renderState.currentRafs[rafKey];
clear(regl, item.scissorX, item.scissorY, item.scissorWidth, item.viewBoxSize[1]);
}
if (renderState.clearOnly) {
return;
}
item.count = 2 * count;
item.offset = 2 * blockNumber * blockLineCount;
glAes(item);
if (blockNumber * blockLineCount + count < sampleCount) {
renderState.currentRafs[rafKey] = window.requestAnimationFrame(function () {
render(blockNumber + 1);
});
}
renderState.drawCompleted = false;
}
if (!renderState.drawCompleted) {
ensureDraw(regl);
renderState.drawCompleted = true;
}
// start with rendering item 0; recursion handles the rest
render(0);
}
function adjustDepth(d) {
// WebGL matrix operations use floats with limited precision, potentially causing a number near a border of [0, 1]
// to end up slightly outside the border. With an epsilon, we reduce the chance that a line gets clipped by the
// near or the far plane.
return Math.max(depthLimitEpsilon, Math.min(1 - depthLimitEpsilon, d));
}
function palette(unitToColor, opacity) {
var result = new Array(256);
for (var i = 0; i < 256; i++) {
result[i] = unitToColor(i / 255).concat(opacity);
}
return result;
}
// Maps the sample index [0...sampleCount - 1] to a range of [0, 1] as the shader expects colors in the [0, 1] range.
// but first it shifts the sample index by 0, 8 or 16 bits depending on rgbIndex [0..2]
// with the end result that each line will be of a unique color, making it possible for the pick handler
// to uniquely identify which line is hovered over (bijective mapping).
// The inverse, i.e. readPixel is invoked from 'parcoords.js'
function calcPickColor(i, rgbIndex) {
return (i >>> 8 * rgbIndex) % 256 / 255;
}
function makePoints(sampleCount, dims, color) {
var points = new Array(sampleCount * (maxDim + 4));
var n = 0;
for (var i = 0; i < sampleCount; i++) {
for (var k = 0; k < maxDim; k++) {
points[n++] = k < dims.length ? dims[k].paddedUnitValues[i] : 0.5;
}
points[n++] = calcPickColor(i, 2);
points[n++] = calcPickColor(i, 1);
points[n++] = calcPickColor(i, 0);
points[n++] = adjustDepth(color[i]);
}
return points;
}
function makeVecAttr(vecIndex, sampleCount, points) {
var pointPairs = new Array(sampleCount * 8);
var n = 0;
for (var i = 0; i < sampleCount; i++) {
for (var j = 0; j < 2; j++) {
for (var k = 0; k < 4; k++) {
var q = vecIndex * 4 + k;
var v = points[i * 64 + q];
if (q === 63 && j === 0) {
v *= -1;
}
pointPairs[n++] = v;
}
}
}
return pointPairs;
}
function pad2(num) {
var s = '0' + num;
return s.substr(s.length - 2);
}
function getAttrName(i) {
return i < maxDim ? 'p' + pad2(i + 1) + '_' + pad2(i + 4) : 'colors';
}
function setAttributes(attributes, sampleCount, points) {
for (var i = 0; i <= maxDim; i += 4) {
attributes[getAttrName(i)](makeVecAttr(i / 4, sampleCount, points));
}
}
function emptyAttributes(regl) {
var attributes = {};
for (var i = 0; i <= maxDim; i += 4) {
attributes[getAttrName(i)] = regl.buffer({
usage: 'dynamic',
type: 'float',
data: new Uint8Array(0)
});
}
return attributes;
}
function makeItem(model, leftmost, rightmost, itemNumber, i0, i1, x, y, panelSizeX, panelSizeY, crossfilterDimensionIndex, drwLayer, constraints, plotGlPixelRatio) {
var dims = [[], []];
for (var k = 0; k < 64; k++) {
dims[0][k] = k === i0 ? 1 : 0;
dims[1][k] = k === i1 ? 1 : 0;
}
x *= plotGlPixelRatio;
y *= plotGlPixelRatio;
panelSizeX *= plotGlPixelRatio;
panelSizeY *= plotGlPixelRatio;
var overdrag = model.lines.canvasOverdrag * plotGlPixelRatio;
var domain = model.domain;
var canvasWidth = model.canvasWidth * plotGlPixelRatio;
var canvasHeight = model.canvasHeight * plotGlPixelRatio;
var padL = model.pad.l * plotGlPixelRatio;
var padB = model.pad.b * plotGlPixelRatio;
var layoutHeight = model.layoutHeight * plotGlPixelRatio;
var layoutWidth = model.layoutWidth * plotGlPixelRatio;
var deselectedLinesColor = model.deselectedLines.color;
var deselectedLinesOpacity = model.deselectedLines.opacity;
var itemModel = Lib.extendFlat({
key: crossfilterDimensionIndex,
resolution: [canvasWidth, canvasHeight],
viewBoxPos: [x + overdrag, y],
viewBoxSize: [panelSizeX, panelSizeY],
i0: i0,
i1: i1,
dim0A: dims[0].slice(0, 16),
dim0B: dims[0].slice(16, 32),
dim0C: dims[0].slice(32, 48),
dim0D: dims[0].slice(48, 64),
dim1A: dims[1].slice(0, 16),
dim1B: dims[1].slice(16, 32),
dim1C: dims[1].slice(32, 48),
dim1D: dims[1].slice(48, 64),
drwLayer: drwLayer,
contextColor: [deselectedLinesColor[0] / 255, deselectedLinesColor[1] / 255, deselectedLinesColor[2] / 255, deselectedLinesOpacity !== 'auto' ? deselectedLinesColor[3] * deselectedLinesOpacity : Math.max(1 / 255, Math.pow(1 / model.lines.color.length, 1 / 3))],
scissorX: (itemNumber === leftmost ? 0 : x + overdrag) + (padL - overdrag) + layoutWidth * domain.x[0],
scissorWidth: (itemNumber === rightmost ? canvasWidth - x + overdrag : panelSizeX + 0.5) + (itemNumber === leftmost ? x + overdrag : 0),
scissorY: y + padB + layoutHeight * domain.y[0],
scissorHeight: panelSizeY,
viewportX: padL - overdrag + layoutWidth * domain.x[0],
viewportY: padB + layoutHeight * domain.y[0],
viewportWidth: canvasWidth,
viewportHeight: canvasHeight
}, constraints);
return itemModel;
}
function expandedPixelRange(bounds) {
var dh = maskHeight - 1;
var a = Math.max(0, Math.floor(bounds[0] * dh), 0);
var b = Math.min(dh, Math.ceil(bounds[1] * dh), dh);
return [Math.min(a, b), Math.max(a, b)];
}
module.exports = function (canvasGL, d) {
// context & pick describe which canvas we're talking about - won't change with new data
var isContext = d.context;
var isPick = d.pick;
var regl = d.regl;
var gl = regl._gl;
var supportedLineWidth = gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE);
// ensure here that plotGlPixelRatio is within supported range; otherwise regl throws error
var plotGlPixelRatio = Math.max(supportedLineWidth[0], Math.min(supportedLineWidth[1], d.viewModel.plotGlPixelRatio));
var renderState = {
currentRafs: {},
drawCompleted: true,
clearOnly: false
};
// state to be set by update and used later
var model;
var vm;
var initialDims;
var sampleCount;
var attributes = emptyAttributes(regl);
var maskTexture;
var paletteTexture = regl.texture(paletteTextureConfig);
var prevAxisOrder = [];
update(d);
var glAes = regl({
profile: false,
blend: {
enable: isContext,
func: {
srcRGB: 'src alpha',
dstRGB: 'one minus src alpha',
srcAlpha: 1,
dstAlpha: 1 // 'one minus src alpha'
},
equation: {
rgb: 'add',
alpha: 'add'
},
color: [0, 0, 0, 0]
},
depth: {
enable: !isContext,
mask: true,
func: 'less',
range: [0, 1]
},
// for polygons
cull: {
enable: true,
face: 'back'
},
scissor: {
enable: true,
box: {
x: regl.prop('scissorX'),
y: regl.prop('scissorY'),
width: regl.prop('scissorWidth'),
height: regl.prop('scissorHeight')
}
},
viewport: {
x: regl.prop('viewportX'),
y: regl.prop('viewportY'),
width: regl.prop('viewportWidth'),
height: regl.prop('viewportHeight')
},
dither: false,
vert: vertexShaderSource,
frag: fragmentShaderSource,
primitive: 'lines',
lineWidth: plotGlPixelRatio,
attributes: attributes,
uniforms: {
resolution: regl.prop('resolution'),
viewBoxPos: regl.prop('viewBoxPos'),
viewBoxSize: regl.prop('viewBoxSize'),
dim0A: regl.prop('dim0A'),
dim1A: regl.prop('dim1A'),
dim0B: regl.prop('dim0B'),
dim1B: regl.prop('dim1B'),
dim0C: regl.prop('dim0C'),
dim1C: regl.prop('dim1C'),
dim0D: regl.prop('dim0D'),
dim1D: regl.prop('dim1D'),
loA: regl.prop('loA'),
hiA: regl.prop('hiA'),
loB: regl.prop('loB'),
hiB: regl.prop('hiB'),
loC: regl.prop('loC'),
hiC: regl.prop('hiC'),
loD: regl.prop('loD'),
hiD: regl.prop('hiD'),
palette: paletteTexture,
contextColor: regl.prop('contextColor'),
maskTexture: regl.prop('maskTexture'),
drwLayer: regl.prop('drwLayer'),
maskHeight: regl.prop('maskHeight')
},
offset: regl.prop('offset'),
count: regl.prop('count')
});
function update(dNew) {
model = dNew.model;
vm = dNew.viewModel;
initialDims = vm.dimensions.slice();
sampleCount = initialDims[0] ? initialDims[0].values.length : 0;
var lines = model.lines;
var color = isPick ? lines.color.map(function (_, i) {
return i / lines.color.length;
}) : lines.color;
var points = makePoints(sampleCount, initialDims, color);
setAttributes(attributes, sampleCount, points);
if (!isContext && !isPick) {
paletteTexture = regl.texture(Lib.extendFlat({
data: palette(model.unitToColor, 255)
}, paletteTextureConfig));
}
}
function makeConstraints(isContext) {
var i, j, k;
var limits = [[], []];
for (k = 0; k < 64; k++) {
var p = !isContext && k < initialDims.length ? initialDims[k].brush.filter.getBounds() : [-Infinity, Infinity];
limits[0][k] = p[0];
limits[1][k] = p[1];
}
var len = maskHeight * 8;
var mask = new Array(len);
for (i = 0; i < len; i++) {
mask[i] = 255;
}
if (!isContext) {
for (i = 0; i < initialDims.length; i++) {
var u = i % 8;
var v = (i - u) / 8;
var bitMask = Math.pow(2, u);
var dim = initialDims[i];
var ranges = dim.brush.filter.get();
if (ranges.length < 2) continue; // bail if the bounding box based filter is sufficient
var prevEnd = expandedPixelRange(ranges[0])[1];
for (j = 1; j < ranges.length; j++) {
var nextRange = expandedPixelRange(ranges[j]);
for (k = prevEnd + 1; k < nextRange[0]; k++) {
mask[k * 8 + v] &= ~bitMask;
}
prevEnd = Math.max(prevEnd, nextRange[1]);
}
}
}
var textureData = {
// 8 units x 8 bits = 64 bits, just sufficient for the almost 64 dimensions we support
shape: [8, maskHeight],
format: 'alpha',
type: 'uint8',
mag: 'nearest',
min: 'nearest',
data: mask
};
if (maskTexture) maskTexture(textureData);else maskTexture = regl.texture(textureData);
return {
maskTexture: maskTexture,
maskHeight: maskHeight,
loA: limits[0].slice(0, 16),
loB: limits[0].slice(16, 32),
loC: limits[0].slice(32, 48),
loD: limits[0].slice(48, 64),
hiA: limits[1].slice(0, 16),
hiB: limits[1].slice(16, 32),
hiC: limits[1].slice(32, 48),
hiD: limits[1].slice(48, 64)
};
}
function renderGLParcoords(panels, setChanged, clearOnly) {
var panelCount = panels.length;
var i;
var leftmost;
var rightmost;
var lowestX = Infinity;
var highestX = -Infinity;
for (i = 0; i < panelCount; i++) {
if (panels[i].dim0.canvasX < lowestX) {
lowestX = panels[i].dim0.canvasX;
leftmost = i;
}
if (panels[i].dim1.canvasX > highestX) {
highestX = panels[i].dim1.canvasX;
rightmost = i;
}
}
if (panelCount === 0) {
// clear canvas here, as the panel iteration below will not enter the loop body
clear(regl, 0, 0, model.canvasWidth, model.canvasHeight);
}
var constraints = makeConstraints(isContext);
for (i = 0; i < panelCount; i++) {
var p = panels[i];
var i0 = p.dim0.crossfilterDimensionIndex;
var i1 = p.dim1.crossfilterDimensionIndex;
var x = p.canvasX;
var y = p.canvasY;
var nextX = x + p.panelSizeX;
var plotGlPixelRatio = p.plotGlPixelRatio;
if (setChanged || !prevAxisOrder[i0] || prevAxisOrder[i0][0] !== x || prevAxisOrder[i0][1] !== nextX) {
prevAxisOrder[i0] = [x, nextX];
var item = makeItem(model, leftmost, rightmost, i, i0, i1, x, y, p.panelSizeX, p.panelSizeY, p.dim0.crossfilterDimensionIndex, isContext ? 0 : isPick ? 2 : 1, constraints, plotGlPixelRatio);
renderState.clearOnly = clearOnly;
var blockLineCount = setChanged ? model.lines.blockLineCount : sampleCount;
renderBlock(regl, glAes, renderState, blockLineCount, sampleCount, item);
}
}
}
function readPixel(canvasX, canvasY) {
regl.read({
x: canvasX,
y: canvasY,
width: 1,
height: 1,
data: dataPixel
});
return dataPixel;
}
function readPixels(canvasX, canvasY, width, height) {
var pixelArray = new Uint8Array(4 * width * height);
regl.read({
x: canvasX,
y: canvasY,
width: width,
height: height,
data: pixelArray
});
return pixelArray;
}
function destroy() {
canvasGL.style['pointer-events'] = 'none';
paletteTexture.destroy();
if (maskTexture) maskTexture.destroy();
for (var k in attributes) attributes[k].destroy();
}
return {
render: renderGLParcoords,
readPixel: readPixel,
readPixels: readPixels,
destroy: destroy,
update: update
};
};
/***/ }),
/***/ 26284:
/***/ (function(module) {
"use strict";
/**
* mergeLength: set trace length as the minimum of all dimension data lengths
* and propagates this length into each dimension
*
* @param {object} traceOut: the fullData trace
* @param {Array(object)} dimensions: array of dimension objects
* @param {string} dataAttr: the attribute of each dimension containing the data
* @param {integer} len: an already-existing length from other attributes
*/
module.exports = function (traceOut, dimensions, dataAttr, len) {
if (!len) len = Infinity;
var i, dimi;
for (i = 0; i < dimensions.length; i++) {
dimi = dimensions[i];
if (dimi.visible) len = Math.min(len, dimi[dataAttr].length);
}
if (len === Infinity) len = 0;
traceOut._length = len;
for (i = 0; i < dimensions.length; i++) {
dimi = dimensions[i];
if (dimi.visible) dimi._length = len;
}
return len;
};
/***/ }),
/***/ 36336:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var numberFormat = Lib.numberFormat;
var rgba = __webpack_require__(96824);
var Axes = __webpack_require__(54460);
var strRotate = Lib.strRotate;
var strTranslate = Lib.strTranslate;
var svgTextUtils = __webpack_require__(72736);
var Drawing = __webpack_require__(43616);
var Colorscale = __webpack_require__(8932);
var gup = __webpack_require__(71688);
var keyFun = gup.keyFun;
var repeat = gup.repeat;
var unwrap = gup.unwrap;
var helpers = __webpack_require__(95724);
var c = __webpack_require__(30140);
var brush = __webpack_require__(71864);
var lineLayerMaker = __webpack_require__(51352);
function findExtreme(fn, values, len) {
return Lib.aggNums(fn, null, values, len);
}
function findExtremes(values, len) {
return fixExtremes(findExtreme(Math.min, values, len), findExtreme(Math.max, values, len));
}
function dimensionExtent(dimension) {
var range = dimension.range;
return range ? fixExtremes(range[0], range[1]) : findExtremes(dimension.values, dimension._length);
}
function fixExtremes(lo, hi) {
if (isNaN(lo) || !isFinite(lo)) {
lo = 0;
}
if (isNaN(hi) || !isFinite(hi)) {
hi = 0;
}
// avoid a degenerate (zero-width) domain
if (lo === hi) {
if (lo === 0) {
// no use to multiplying zero, so add/subtract in this case
lo -= 1;
hi += 1;
} else {
// this keeps the range in the order of magnitude of the data
lo *= 0.9;
hi *= 1.1;
}
}
return [lo, hi];
}
function toText(formatter, texts) {
if (texts) {
return function (v, i) {
var text = texts[i];
if (text === null || text === undefined) return formatter(v);
return text;
};
}
return formatter;
}
function domainScale(height, padding, dimension, tickvals, ticktext) {
var extent = dimensionExtent(dimension);
if (tickvals) {
return d3.scale.ordinal().domain(tickvals.map(toText(numberFormat(dimension.tickformat), ticktext))).range(tickvals.map(function (d) {
var unitVal = (d - extent[0]) / (extent[1] - extent[0]);
return height - padding + unitVal * (2 * padding - height);
}));
}
return d3.scale.linear().domain(extent).range([height - padding, padding]);
}
function unitToPaddedPx(height, padding) {
return d3.scale.linear().range([padding, height - padding]);
}
function domainToPaddedUnitScale(dimension, padFraction) {
return d3.scale.linear().domain(dimensionExtent(dimension)).range([padFraction, 1 - padFraction]);
}
function ordinalScale(dimension) {
if (!dimension.tickvals) return;
var extent = dimensionExtent(dimension);
return d3.scale.ordinal().domain(dimension.tickvals).range(dimension.tickvals.map(function (d) {
return (d - extent[0]) / (extent[1] - extent[0]);
}));
}
function unitToColorScale(cscale) {
var colorStops = cscale.map(function (d) {
return d[0];
});
var colorTuples = cscale.map(function (d) {
var RGBA = rgba(d[1]);
return d3.rgb('rgb(' + RGBA[0] + ',' + RGBA[1] + ',' + RGBA[2] + ')');
});
var prop = function (n) {
return function (o) {
return o[n];
};
};
// We can't use d3 color interpolation as we may have non-uniform color palette raster
// (various color stop distances).
var polylinearUnitScales = 'rgb'.split('').map(function (key) {
return d3.scale.linear().clamp(true).domain(colorStops).range(colorTuples.map(prop(key)));
});
return function (d) {
return polylinearUnitScales.map(function (s) {
return s(d);
});
};
}
function someFiltersActive(view) {
return view.dimensions.some(function (p) {
return p.brush.filterSpecified;
});
}
function model(layout, d, i) {
var cd0 = unwrap(d);
var trace = cd0.trace;
var lineColor = helpers.convertTypedArray(cd0.lineColor);
var line = trace.line;
var deselectedLines = {
color: rgba(trace.unselected.line.color),
opacity: trace.unselected.line.opacity
};
var cOpts = Colorscale.extractOpts(line);
var cscale = cOpts.reversescale ? Colorscale.flipScale(cd0.cscale) : cd0.cscale;
var domain = trace.domain;
var dimensions = trace.dimensions;
var width = layout.width;
var labelAngle = trace.labelangle;
var labelSide = trace.labelside;
var labelFont = trace.labelfont;
var tickFont = trace.tickfont;
var rangeFont = trace.rangefont;
var lines = Lib.extendDeepNoArrays({}, line, {
color: lineColor.map(d3.scale.linear().domain(dimensionExtent({
values: lineColor,
range: [cOpts.min, cOpts.max],
_length: trace._length
}))),
blockLineCount: c.blockLineCount,
canvasOverdrag: c.overdrag * c.canvasPixelRatio
});
var groupWidth = Math.floor(width * (domain.x[1] - domain.x[0]));
var groupHeight = Math.floor(layout.height * (domain.y[1] - domain.y[0]));
var pad = layout.margin || {
l: 80,
r: 80,
t: 100,
b: 80
};
var rowContentWidth = groupWidth;
var rowHeight = groupHeight;
return {
key: i,
colCount: dimensions.filter(helpers.isVisible).length,
dimensions: dimensions,
tickDistance: c.tickDistance,
unitToColor: unitToColorScale(cscale),
lines: lines,
deselectedLines: deselectedLines,
labelAngle: labelAngle,
labelSide: labelSide,
labelFont: labelFont,
tickFont: tickFont,
rangeFont: rangeFont,
layoutWidth: width,
layoutHeight: layout.height,
domain: domain,
translateX: domain.x[0] * width,
translateY: layout.height - domain.y[1] * layout.height,
pad: pad,
canvasWidth: rowContentWidth * c.canvasPixelRatio + 2 * lines.canvasOverdrag,
canvasHeight: rowHeight * c.canvasPixelRatio,
width: rowContentWidth,
height: rowHeight,
canvasPixelRatio: c.canvasPixelRatio
};
}
function viewModel(state, callbacks, model) {
var width = model.width;
var height = model.height;
var dimensions = model.dimensions;
var canvasPixelRatio = model.canvasPixelRatio;
var xScale = function (d) {
return width * d / Math.max(1, model.colCount - 1);
};
var unitPad = c.verticalPadding / height;
var _unitToPaddedPx = unitToPaddedPx(height, c.verticalPadding);
var vm = {
key: model.key,
xScale: xScale,
model: model,
inBrushDrag: false // consider factoring it out and putting it in a centralized global-ish gesture state object
};
var uniqueKeys = {};
vm.dimensions = dimensions.filter(helpers.isVisible).map(function (dimension, i) {
var domainToPaddedUnit = domainToPaddedUnitScale(dimension, unitPad);
var foundKey = uniqueKeys[dimension.label];
uniqueKeys[dimension.label] = (foundKey || 0) + 1;
var key = dimension.label + (foundKey ? '__' + foundKey : '');
var specifiedConstraint = dimension.constraintrange;
var filterRangeSpecified = specifiedConstraint && specifiedConstraint.length;
if (filterRangeSpecified && !isArrayOrTypedArray(specifiedConstraint[0])) {
specifiedConstraint = [specifiedConstraint];
}
var filterRange = filterRangeSpecified ? specifiedConstraint.map(function (d) {
return d.map(domainToPaddedUnit);
}) : [[-Infinity, Infinity]];
var brushMove = function () {
var p = vm;
p.focusLayer && p.focusLayer.render(p.panels, true);
var filtersActive = someFiltersActive(p);
if (!state.contextShown() && filtersActive) {
p.contextLayer && p.contextLayer.render(p.panels, true);
state.contextShown(true);
} else if (state.contextShown() && !filtersActive) {
p.contextLayer && p.contextLayer.render(p.panels, true, true);
state.contextShown(false);
}
};
var truncatedValues = dimension.values;
if (truncatedValues.length > dimension._length) {
truncatedValues = truncatedValues.slice(0, dimension._length);
}
var tickvals = dimension.tickvals;
var ticktext;
function makeTickItem(v, i) {
return {
val: v,
text: ticktext[i]
};
}
function sortTickItem(a, b) {
return a.val - b.val;
}
if (isArrayOrTypedArray(tickvals) && tickvals.length) {
if (Lib.isTypedArray(tickvals)) tickvals = Array.from(tickvals);
ticktext = dimension.ticktext;
// ensure ticktext and tickvals have same length
if (!isArrayOrTypedArray(ticktext) || !ticktext.length) {
ticktext = tickvals.map(numberFormat(dimension.tickformat));
} else if (ticktext.length > tickvals.length) {
ticktext = ticktext.slice(0, tickvals.length);
} else if (tickvals.length > ticktext.length) {
tickvals = tickvals.slice(0, ticktext.length);
}
// check if we need to sort tickvals/ticktext
for (var j = 1; j < tickvals.length; j++) {
if (tickvals[j] < tickvals[j - 1]) {
var tickItems = tickvals.map(makeTickItem).sort(sortTickItem);
for (var k = 0; k < tickvals.length; k++) {
tickvals[k] = tickItems[k].val;
ticktext[k] = tickItems[k].text;
}
break;
}
}
} else tickvals = undefined;
truncatedValues = helpers.convertTypedArray(truncatedValues);
return {
key: key,
label: dimension.label,
tickFormat: dimension.tickformat,
tickvals: tickvals,
ticktext: ticktext,
ordinal: helpers.isOrdinal(dimension),
multiselect: dimension.multiselect,
xIndex: i,
crossfilterDimensionIndex: i,
visibleIndex: dimension._index,
height: height,
values: truncatedValues,
paddedUnitValues: truncatedValues.map(domainToPaddedUnit),
unitTickvals: tickvals && tickvals.map(domainToPaddedUnit),
xScale: xScale,
x: xScale(i),
canvasX: xScale(i) * canvasPixelRatio,
unitToPaddedPx: _unitToPaddedPx,
domainScale: domainScale(height, c.verticalPadding, dimension, tickvals, ticktext),
ordinalScale: ordinalScale(dimension),
parent: vm,
model: model,
brush: brush.makeBrush(state, filterRangeSpecified, filterRange, function () {
state.linePickActive(false);
}, brushMove, function (f) {
vm.focusLayer.render(vm.panels, true);
vm.pickLayer && vm.pickLayer.render(vm.panels, true);
state.linePickActive(true);
if (callbacks && callbacks.filterChanged) {
var invScale = domainToPaddedUnit.invert;
// update gd.data as if a Plotly.restyle were fired
var newRanges = f.map(function (r) {
return r.map(invScale).sort(Lib.sorterAsc);
}).sort(function (a, b) {
return a[0] - b[0];
});
callbacks.filterChanged(vm.key, dimension._index, newRanges);
}
})
};
});
return vm;
}
function styleExtentTexts(selection) {
selection.classed(c.cn.axisExtentText, true).attr('text-anchor', 'middle').style('cursor', 'default');
}
function parcoordsInteractionState() {
var linePickActive = true;
var contextShown = false;
return {
linePickActive: function (val) {
return arguments.length ? linePickActive = !!val : linePickActive;
},
contextShown: function (val) {
return arguments.length ? contextShown = !!val : contextShown;
}
};
}
function calcTilt(angle, position) {
var dir = position === 'top' ? 1 : -1;
var radians = angle * Math.PI / 180;
var dx = Math.sin(radians);
var dy = Math.cos(radians);
return {
dir: dir,
dx: dx,
dy: dy,
degrees: angle
};
}
function updatePanelLayout(yAxis, vm, plotGlPixelRatio) {
var panels = vm.panels || (vm.panels = []);
var data = yAxis.data();
for (var i = 0; i < data.length - 1; i++) {
var p = panels[i] || (panels[i] = {});
var dim0 = data[i];
var dim1 = data[i + 1];
p.dim0 = dim0;
p.dim1 = dim1;
p.canvasX = dim0.canvasX;
p.panelSizeX = dim1.canvasX - dim0.canvasX;
p.panelSizeY = vm.model.canvasHeight;
p.y = 0;
p.canvasY = 0;
p.plotGlPixelRatio = plotGlPixelRatio;
}
}
function calcAllTicks(cd) {
for (var i = 0; i < cd.length; i++) {
for (var j = 0; j < cd[i].length; j++) {
var trace = cd[i][j].trace;
var dimensions = trace.dimensions;
for (var k = 0; k < dimensions.length; k++) {
var values = dimensions[k].values;
var dim = dimensions[k]._ax;
if (dim) {
if (!dim.range) {
dim.range = findExtremes(values, trace._length);
} else {
dim.range = fixExtremes(dim.range[0], dim.range[1]);
}
if (!dim.dtick) {
dim.dtick = 0.01 * (Math.abs(dim.range[1] - dim.range[0]) || 1);
}
dim.tickformat = dimensions[k].tickformat;
Axes.calcTicks(dim);
dim.cleanRange();
}
}
}
}
}
function linearFormat(dim, v) {
return Axes.tickText(dim._ax, v, false).text;
}
function extremeText(d, isTop) {
if (d.ordinal) return '';
var domain = d.domainScale.domain();
var v = domain[isTop ? domain.length - 1 : 0];
return linearFormat(d.model.dimensions[d.visibleIndex], v);
}
module.exports = function parcoords(gd, cdModule, layout, callbacks) {
var isStatic = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
var svg = fullLayout._toppaper;
var glContainer = fullLayout._glcontainer;
var plotGlPixelRatio = gd._context.plotGlPixelRatio;
var paperColor = gd._fullLayout.paper_bgcolor;
calcAllTicks(cdModule);
var state = parcoordsInteractionState();
var vm = cdModule.filter(function (d) {
return unwrap(d).trace.visible;
}).map(model.bind(0, layout)).map(viewModel.bind(0, state, callbacks));
glContainer.each(function (d, i) {
return Lib.extendFlat(d, vm[i]);
});
var glLayers = glContainer.selectAll('.gl-canvas').each(function (d) {
// FIXME: figure out how to handle multiple instances
d.viewModel = vm[0];
d.viewModel.plotGlPixelRatio = plotGlPixelRatio;
d.viewModel.paperColor = paperColor;
d.model = d.viewModel ? d.viewModel.model : null;
});
var lastHovered = null;
var pickLayer = glLayers.filter(function (d) {
return d.pick;
});
// emit hover / unhover event
pickLayer.style('pointer-events', isStatic ? 'none' : 'auto').on('mousemove', function (d) {
if (state.linePickActive() && d.lineLayer && callbacks && callbacks.hover) {
var event = d3.event;
var cw = this.width;
var ch = this.height;
var pointer = d3.mouse(this);
var x = pointer[0];
var y = pointer[1];
if (x < 0 || y < 0 || x >= cw || y >= ch) {
return;
}
var pixel = d.lineLayer.readPixel(x, ch - 1 - y);
var found = pixel[3] !== 0;
// inverse of the calcPickColor in `lines.js`; detailed comment there
var curveNumber = found ? pixel[2] + 256 * (pixel[1] + 256 * pixel[0]) : null;
var eventData = {
x: x,
y: y,
clientX: event.clientX,
clientY: event.clientY,
dataIndex: d.model.key,
curveNumber: curveNumber
};
if (curveNumber !== lastHovered) {
// don't unnecessarily repeat the same hit (or miss)
if (found) {
callbacks.hover(eventData);
} else if (callbacks.unhover) {
callbacks.unhover(eventData);
}
lastHovered = curveNumber;
}
}
});
glLayers.style('opacity', function (d) {
return d.pick ? 0 : 1;
});
svg.style('background', 'rgba(255, 255, 255, 0)');
var controlOverlay = svg.selectAll('.' + c.cn.parcoords).data(vm, keyFun);
controlOverlay.exit().remove();
controlOverlay.enter().append('g').classed(c.cn.parcoords, true).style('shape-rendering', 'crispEdges').style('pointer-events', 'none');
controlOverlay.attr('transform', function (d) {
return strTranslate(d.model.translateX, d.model.translateY);
});
var parcoordsControlView = controlOverlay.selectAll('.' + c.cn.parcoordsControlView).data(repeat, keyFun);
parcoordsControlView.enter().append('g').classed(c.cn.parcoordsControlView, true);
parcoordsControlView.attr('transform', function (d) {
return strTranslate(d.model.pad.l, d.model.pad.t);
});
var yAxis = parcoordsControlView.selectAll('.' + c.cn.yAxis).data(function (p) {
return p.dimensions;
}, keyFun);
yAxis.enter().append('g').classed(c.cn.yAxis, true);
parcoordsControlView.each(function (p) {
updatePanelLayout(yAxis, p, plotGlPixelRatio);
});
glLayers.each(function (d) {
if (d.viewModel) {
if (!d.lineLayer || callbacks) {
// recreate in case of having callbacks e.g. restyle. Should we test for callback to be a restyle?
d.lineLayer = lineLayerMaker(this, d);
} else d.lineLayer.update(d);
if (d.key || d.key === 0) d.viewModel[d.key] = d.lineLayer;
var setChanged = !d.context ||
// don't update background
callbacks; // unless there is a callback on the context layer. Should we test the callback?
d.lineLayer.render(d.viewModel.panels, setChanged);
}
});
yAxis.attr('transform', function (d) {
return strTranslate(d.xScale(d.xIndex), 0);
});
// drag column for reordering columns
yAxis.call(d3.behavior.drag().origin(function (d) {
return d;
}).on('drag', function (d) {
var p = d.parent;
state.linePickActive(false);
d.x = Math.max(-c.overdrag, Math.min(d.model.width + c.overdrag, d3.event.x));
d.canvasX = d.x * d.model.canvasPixelRatio;
yAxis.sort(function (a, b) {
return a.x - b.x;
}).each(function (e, i) {
e.xIndex = i;
e.x = d === e ? e.x : e.xScale(e.xIndex);
e.canvasX = e.x * e.model.canvasPixelRatio;
});
updatePanelLayout(yAxis, p, plotGlPixelRatio);
yAxis.filter(function (e) {
return Math.abs(d.xIndex - e.xIndex) !== 0;
}).attr('transform', function (d) {
return strTranslate(d.xScale(d.xIndex), 0);
});
d3.select(this).attr('transform', strTranslate(d.x, 0));
yAxis.each(function (e, i0, i1) {
if (i1 === d.parent.key) p.dimensions[i0] = e;
});
p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p));
p.focusLayer.render && p.focusLayer.render(p.panels);
}).on('dragend', function (d) {
var p = d.parent;
d.x = d.xScale(d.xIndex);
d.canvasX = d.x * d.model.canvasPixelRatio;
updatePanelLayout(yAxis, p, plotGlPixelRatio);
d3.select(this).attr('transform', function (d) {
return strTranslate(d.x, 0);
});
p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p));
p.focusLayer && p.focusLayer.render(p.panels);
p.pickLayer && p.pickLayer.render(p.panels, true);
state.linePickActive(true);
if (callbacks && callbacks.axesMoved) {
callbacks.axesMoved(p.key, p.dimensions.map(function (e) {
return e.crossfilterDimensionIndex;
}));
}
}));
yAxis.exit().remove();
var axisOverlays = yAxis.selectAll('.' + c.cn.axisOverlays).data(repeat, keyFun);
axisOverlays.enter().append('g').classed(c.cn.axisOverlays, true);
axisOverlays.selectAll('.' + c.cn.axis).remove();
var axis = axisOverlays.selectAll('.' + c.cn.axis).data(repeat, keyFun);
axis.enter().append('g').classed(c.cn.axis, true);
axis.each(function (d) {
var wantedTickCount = d.model.height / d.model.tickDistance;
var scale = d.domainScale;
var sdom = scale.domain();
d3.select(this).call(d3.svg.axis().orient('left').tickSize(4).outerTickSize(2).ticks(wantedTickCount, d.tickFormat) // works for continuous scales only...
.tickValues(d.ordinal ?
// and this works for ordinal scales
sdom : null).tickFormat(function (v) {
return helpers.isOrdinal(d) ? v : linearFormat(d.model.dimensions[d.visibleIndex], v);
}).scale(scale));
Drawing.font(axis.selectAll('text'), d.model.tickFont);
});
axis.selectAll('.domain, .tick>line').attr('fill', 'none').attr('stroke', 'black').attr('stroke-opacity', 0.25).attr('stroke-width', '1px');
axis.selectAll('text').style('cursor', 'default');
var axisHeading = axisOverlays.selectAll('.' + c.cn.axisHeading).data(repeat, keyFun);
axisHeading.enter().append('g').classed(c.cn.axisHeading, true);
var axisTitle = axisHeading.selectAll('.' + c.cn.axisTitle).data(repeat, keyFun);
axisTitle.enter().append('text').classed(c.cn.axisTitle, true).attr('text-anchor', 'middle').style('cursor', 'ew-resize').style('pointer-events', isStatic ? 'none' : 'auto');
axisTitle.text(function (d) {
return d.label;
}).each(function (d) {
var e = d3.select(this);
Drawing.font(e, d.model.labelFont);
svgTextUtils.convertToTspans(e, gd);
}).attr('transform', function (d) {
var tilt = calcTilt(d.model.labelAngle, d.model.labelSide);
var r = c.axisTitleOffset;
return (tilt.dir > 0 ? '' : strTranslate(0, 2 * r + d.model.height)) + strRotate(tilt.degrees) + strTranslate(-r * tilt.dx, -r * tilt.dy);
}).attr('text-anchor', function (d) {
var tilt = calcTilt(d.model.labelAngle, d.model.labelSide);
var adx = Math.abs(tilt.dx);
var ady = Math.abs(tilt.dy);
if (2 * adx > ady) {
return tilt.dir * tilt.dx < 0 ? 'start' : 'end';
} else {
return 'middle';
}
});
var axisExtent = axisOverlays.selectAll('.' + c.cn.axisExtent).data(repeat, keyFun);
axisExtent.enter().append('g').classed(c.cn.axisExtent, true);
var axisExtentTop = axisExtent.selectAll('.' + c.cn.axisExtentTop).data(repeat, keyFun);
axisExtentTop.enter().append('g').classed(c.cn.axisExtentTop, true);
axisExtentTop.attr('transform', strTranslate(0, -c.axisExtentOffset));
var axisExtentTopText = axisExtentTop.selectAll('.' + c.cn.axisExtentTopText).data(repeat, keyFun);
axisExtentTopText.enter().append('text').classed(c.cn.axisExtentTopText, true).call(styleExtentTexts);
axisExtentTopText.text(function (d) {
return extremeText(d, true);
}).each(function (d) {
Drawing.font(d3.select(this), d.model.rangeFont);
});
var axisExtentBottom = axisExtent.selectAll('.' + c.cn.axisExtentBottom).data(repeat, keyFun);
axisExtentBottom.enter().append('g').classed(c.cn.axisExtentBottom, true);
axisExtentBottom.attr('transform', function (d) {
return strTranslate(0, d.model.height + c.axisExtentOffset);
});
var axisExtentBottomText = axisExtentBottom.selectAll('.' + c.cn.axisExtentBottomText).data(repeat, keyFun);
axisExtentBottomText.enter().append('text').classed(c.cn.axisExtentBottomText, true).attr('dy', '0.75em').call(styleExtentTexts);
axisExtentBottomText.text(function (d) {
return extremeText(d, false);
}).each(function (d) {
Drawing.font(d3.select(this), d.model.rangeFont);
});
brush.ensureAxisBrush(axisOverlays, paperColor, gd);
};
/***/ }),
/***/ 38488:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var plot = __webpack_require__(24196);
var reglPrecompiled = __webpack_require__(10992);
Object.assign(plot.reglPrecompiled, reglPrecompiled);
module.exports = plot;
/***/ }),
/***/ 24196:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var parcoords = __webpack_require__(36336);
var prepareRegl = __webpack_require__(5048);
var isVisible = (__webpack_require__(95724).isVisible);
var reglPrecompiled = {};
function newIndex(visibleIndices, orig, dim) {
var origIndex = orig.indexOf(dim);
var currentIndex = visibleIndices.indexOf(origIndex);
if (currentIndex === -1) {
// invisible dimensions initially go to the end
currentIndex += orig.length;
}
return currentIndex;
}
function sorter(visibleIndices, orig) {
return function sorter(d1, d2) {
return newIndex(visibleIndices, orig, d1) - newIndex(visibleIndices, orig, d2);
};
}
var exports = module.exports = function plot(gd, cdModule) {
var fullLayout = gd._fullLayout;
var success = prepareRegl(gd, [], reglPrecompiled);
if (!success) return;
var currentDims = {};
var initialDims = {};
var fullIndices = {};
var inputIndices = {};
var size = fullLayout._size;
cdModule.forEach(function (d, i) {
var trace = d[0].trace;
fullIndices[i] = trace.index;
var iIn = inputIndices[i] = trace._fullInput.index;
currentDims[i] = gd.data[iIn].dimensions;
initialDims[i] = gd.data[iIn].dimensions.slice();
});
var filterChanged = function (i, initialDimIndex, newRanges) {
// Have updated `constraintrange` data on `gd.data` and raise `Plotly.restyle` event
// without having to incur heavy UI blocking due to an actual `Plotly.restyle` call
var dim = initialDims[i][initialDimIndex];
var newConstraints = newRanges.map(function (r) {
return r.slice();
});
// Store constraint range in preGUI
// This one doesn't work if it's stored in pieces in _storeDirectGUIEdit
// because it's an array of variable dimensionality. So store the whole
// thing at once manually.
var aStr = 'dimensions[' + initialDimIndex + '].constraintrange';
var preGUI = fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid];
if (preGUI[aStr] === undefined) {
var initialVal = dim.constraintrange;
preGUI[aStr] = initialVal || null;
}
var fullDimension = gd._fullData[fullIndices[i]].dimensions[initialDimIndex];
if (!newConstraints.length) {
delete dim.constraintrange;
delete fullDimension.constraintrange;
newConstraints = null;
} else {
if (newConstraints.length === 1) newConstraints = newConstraints[0];
dim.constraintrange = newConstraints;
fullDimension.constraintrange = newConstraints.slice();
// wrap in another array for restyle event data
newConstraints = [newConstraints];
}
var restyleData = {};
restyleData[aStr] = newConstraints;
gd.emit('plotly_restyle', [restyleData, [inputIndices[i]]]);
};
var hover = function (eventData) {
gd.emit('plotly_hover', eventData);
};
var unhover = function (eventData) {
gd.emit('plotly_unhover', eventData);
};
var axesMoved = function (i, visibleIndices) {
// Have updated order data on `gd.data` and raise `Plotly.restyle` event
// without having to incur heavy UI blocking due to an actual `Plotly.restyle` call
// drag&drop sorting of the visible dimensions
var orig = sorter(visibleIndices, initialDims[i].filter(isVisible));
currentDims[i].sort(orig);
// invisible dimensions are not interpreted in the context of drag&drop sorting as an invisible dimension
// cannot be dragged; they're interspersed into their original positions by this subsequent merging step
initialDims[i].filter(function (d) {
return !isVisible(d);
}).sort(function (d) {
// subsequent splicing to be done left to right, otherwise indices may be incorrect
return initialDims[i].indexOf(d);
}).forEach(function (d) {
currentDims[i].splice(currentDims[i].indexOf(d), 1); // remove from the end
currentDims[i].splice(initialDims[i].indexOf(d), 0, d); // insert at original index
});
// TODO: we can't really store this part of the interaction state
// directly as below, since it incudes data arrays. If we want to
// persist column order we may have to do something special for this
// case to just store the order itself.
// Registry.call('_storeDirectGUIEdit',
// gd.data[inputIndices[i]],
// fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid],
// {dimensions: currentDims[i]}
// );
gd.emit('plotly_restyle', [{
dimensions: [currentDims[i]]
}, [inputIndices[i]]]);
};
parcoords(gd, cdModule, {
// layout
width: size.w,
height: size.h,
margin: {
t: size.t,
r: size.r,
b: size.b,
l: size.l
}
}, {
// callbacks
filterChanged: filterChanged,
hover: hover,
unhover: unhover,
axesMoved: axesMoved
});
};
exports.reglPrecompiled = reglPrecompiled;
/***/ }),
/***/ 10992:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var v0 = __webpack_require__(9128);
var v1 = __webpack_require__(70888);
var v2 = __webpack_require__(81504);
var v3 = __webpack_require__(55556);
/* eslint-disable quote-props */
module.exports = {
'453a70fefa48db31713162aeb1ac438cb8579f54504f3b23acf32128df3dfd45': v0,
'30680f8f6712ef1af5cf7547e0af35b036fb300c67b07967cf448492ff4de4d0': v1,
'a3970baf1d8cac9305ee830c7026550387343d4dde2353dd86a4d082c97d3470': v2,
'3fd666968f3ce90d1c048b7a9aab515f3ce387a5401a10f8b66121c9469d1c0d': v3
};
/***/ }),
/***/ 19960:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var index = __webpack_require__(61664);
index.plot = __webpack_require__(38488);
module.exports = index;
/***/ }),
/***/ 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;
var weight = helpers.castOption(trace.outsidetextfont.weight, pt.pts) || helpers.castOption(trace.textfont.weight, pt.pts) || layoutFont.weight;
var style = helpers.castOption(trace.outsidetextfont.style, pt.pts) || helpers.castOption(trace.textfont.style, pt.pts) || layoutFont.style;
var variant = helpers.castOption(trace.outsidetextfont.variant, pt.pts) || helpers.castOption(trace.textfont.variant, pt.pts) || layoutFont.variant;
var textcase = helpers.castOption(trace.outsidetextfont.textcase, pt.pts) || helpers.castOption(trace.textfont.textcase, pt.pts) || layoutFont.textcase;
var lineposition = helpers.castOption(trace.outsidetextfont.lineposition, pt.pts) || helpers.castOption(trace.textfont.lineposition, pt.pts) || layoutFont.lineposition;
var shadow = helpers.castOption(trace.outsidetextfont.shadow, pt.pts) || helpers.castOption(trace.textfont.shadow, pt.pts) || layoutFont.shadow;
return {
color: color,
family: family,
size: size,
weight: weight,
style: style,
variant: variant,
textcase: textcase,
lineposition: lineposition,
shadow: shadow
};
}
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;
var weight = helpers.castOption(trace.insidetextfont.weight, pt.pts) || helpers.castOption(trace.textfont.weight, pt.pts) || layoutFont.weight;
var style = helpers.castOption(trace.insidetextfont.style, pt.pts) || helpers.castOption(trace.textfont.style, pt.pts) || layoutFont.style;
var variant = helpers.castOption(trace.insidetextfont.variant, pt.pts) || helpers.castOption(trace.textfont.variant, pt.pts) || layoutFont.variant;
var textcase = helpers.castOption(trace.insidetextfont.textcase, pt.pts) || helpers.castOption(trace.textfont.textcase, pt.pts) || layoutFont.textcase;
var lineposition = helpers.castOption(trace.insidetextfont.lineposition, pt.pts) || helpers.castOption(trace.textfont.lineposition, pt.pts) || layoutFont.lineposition;
var shadow = helpers.castOption(trace.insidetextfont.shadow, pt.pts) || helpers.castOption(trace.textfont.shadow, pt.pts) || layoutFont.shadow;
return {
color: customColor || Color.contrast(pt.color),
family: family,
size: size,
weight: weight,
style: style,
variant: variant,
textcase: textcase,
lineposition: lineposition,
shadow: shadow
};
}
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);
};
/***/ }),
/***/ 35484:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterglAttrs = __webpack_require__(52904);
module.exports = {
x: scatterglAttrs.x,
y: scatterglAttrs.y,
xy: {
valType: 'data_array',
editType: 'calc'
},
indices: {
valType: 'data_array',
editType: 'calc'
},
xbounds: {
valType: 'data_array',
editType: 'calc'
},
ybounds: {
valType: 'data_array',
editType: 'calc'
},
text: scatterglAttrs.text,
marker: {
color: {
valType: 'color',
arrayOk: false,
editType: 'calc'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1,
arrayOk: false,
editType: 'calc'
},
blend: {
valType: 'boolean',
dflt: null,
editType: 'calc'
},
sizemin: {
valType: 'number',
min: 0.1,
max: 2,
dflt: 0.5,
editType: 'calc'
},
sizemax: {
valType: 'number',
min: 0.1,
dflt: 20,
editType: 'calc'
},
border: {
color: {
valType: 'color',
arrayOk: false,
editType: 'calc'
},
arearatio: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
editType: 'calc'
},
editType: 'calc'
},
editType: 'calc'
},
transforms: undefined
};
/***/ }),
/***/ 11072:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createPointCloudRenderer = (__webpack_require__(67792).gl_pointcloud2d);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var str2RGBArray = __webpack_require__(43080);
var findExtremes = (__webpack_require__(19280).findExtremes);
var getTraceColor = __webpack_require__(44928);
function Pointcloud(scene, uid) {
this.scene = scene;
this.uid = uid;
this.type = 'pointcloud';
this.pickXData = [];
this.pickYData = [];
this.xData = [];
this.yData = [];
this.textLabels = [];
this.color = 'rgb(0, 0, 0)';
this.name = '';
this.hoverinfo = 'all';
this.idToIndex = new Int32Array(0);
this.bounds = [0, 0, 0, 0];
this.pointcloudOptions = {
positions: new Float32Array(0),
idToIndex: this.idToIndex,
sizemin: 0.5,
sizemax: 12,
color: [0, 0, 0, 1],
areaRatio: 1,
borderColor: [0, 0, 0, 1]
};
this.pointcloud = createPointCloudRenderer(scene.glplot, this.pointcloudOptions);
this.pointcloud._trace = this; // scene2d requires this prop
}
var proto = Pointcloud.prototype;
proto.handlePick = function (pickResult) {
var index = this.idToIndex[pickResult.pointId];
// prefer the readout from XY, if present
return {
trace: this,
dataCoord: pickResult.dataCoord,
traceCoord: this.pickXYData ? [this.pickXYData[index * 2], this.pickXYData[index * 2 + 1]] : [this.pickXData[index], this.pickYData[index]],
textLabel: isArrayOrTypedArray(this.textLabels) ? this.textLabels[index] : this.textLabels,
color: this.color,
name: this.name,
pointIndex: index,
hoverinfo: this.hoverinfo
};
};
proto.update = function (options) {
this.index = options.index;
this.textLabels = options.text;
this.name = options.name;
this.hoverinfo = options.hoverinfo;
this.bounds = [Infinity, Infinity, -Infinity, -Infinity];
this.updateFast(options);
this.color = getTraceColor(options, {});
};
proto.updateFast = function (options) {
var x = this.xData = this.pickXData = options.x;
var y = this.yData = this.pickYData = options.y;
var xy = this.pickXYData = options.xy;
var userBounds = options.xbounds && options.ybounds;
var index = options.indices;
var len;
var idToIndex;
var positions;
var bounds = this.bounds;
var xx, yy, i;
if (xy) {
positions = xy;
// dividing xy.length by 2 and truncating to integer if xy.length was not even
len = xy.length >>> 1;
if (userBounds) {
bounds[0] = options.xbounds[0];
bounds[2] = options.xbounds[1];
bounds[1] = options.ybounds[0];
bounds[3] = options.ybounds[1];
} else {
for (i = 0; i < len; i++) {
xx = positions[i * 2];
yy = positions[i * 2 + 1];
if (xx < bounds[0]) bounds[0] = xx;
if (xx > bounds[2]) bounds[2] = xx;
if (yy < bounds[1]) bounds[1] = yy;
if (yy > bounds[3]) bounds[3] = yy;
}
}
if (index) {
idToIndex = index;
} else {
idToIndex = new Int32Array(len);
for (i = 0; i < len; i++) {
idToIndex[i] = i;
}
}
} else {
len = x.length;
positions = new Float32Array(2 * len);
idToIndex = new Int32Array(len);
for (i = 0; i < len; i++) {
xx = x[i];
yy = y[i];
idToIndex[i] = i;
positions[i * 2] = xx;
positions[i * 2 + 1] = yy;
if (xx < bounds[0]) bounds[0] = xx;
if (xx > bounds[2]) bounds[2] = xx;
if (yy < bounds[1]) bounds[1] = yy;
if (yy > bounds[3]) bounds[3] = yy;
}
}
this.idToIndex = idToIndex;
this.pointcloudOptions.idToIndex = idToIndex;
this.pointcloudOptions.positions = positions;
var markerColor = str2RGBArray(options.marker.color);
var borderColor = str2RGBArray(options.marker.border.color);
var opacity = options.opacity * options.marker.opacity;
markerColor[3] *= opacity;
this.pointcloudOptions.color = markerColor;
// detect blending from the number of points, if undefined
// because large data with blending hits performance
var blend = options.marker.blend;
if (blend === null) {
var maxPoints = 100;
blend = x.length < maxPoints || y.length < maxPoints;
}
this.pointcloudOptions.blend = blend;
borderColor[3] *= opacity;
this.pointcloudOptions.borderColor = borderColor;
var markerSizeMin = options.marker.sizemin;
var markerSizeMax = Math.max(options.marker.sizemax, options.marker.sizemin);
this.pointcloudOptions.sizeMin = markerSizeMin;
this.pointcloudOptions.sizeMax = markerSizeMax;
this.pointcloudOptions.areaRatio = options.marker.border.arearatio;
this.pointcloud.update(this.pointcloudOptions);
// add item for autorange routine
var xa = this.scene.xaxis;
var ya = this.scene.yaxis;
var pad = markerSizeMax / 2 || 0.5;
options._extremes[xa._id] = findExtremes(xa, [bounds[0], bounds[2]], {
ppad: pad
});
options._extremes[ya._id] = findExtremes(ya, [bounds[1], bounds[3]], {
ppad: pad
});
};
proto.dispose = function () {
this.pointcloud.dispose();
};
function createPointcloud(scene, data) {
var plot = new Pointcloud(scene, data.uid);
plot.update(data);
return plot;
}
module.exports = createPointcloud;
/***/ }),
/***/ 41904:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(35484);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
coerce('x');
coerce('y');
coerce('xbounds');
coerce('ybounds');
if (traceIn.xy && traceIn.xy instanceof Float32Array) {
traceOut.xy = traceIn.xy;
}
if (traceIn.indices && traceIn.indices instanceof Int32Array) {
traceOut.indices = traceIn.indices;
}
coerce('text');
coerce('marker.color', defaultColor);
coerce('marker.opacity');
coerce('marker.blend');
coerce('marker.sizemin');
coerce('marker.sizemax');
coerce('marker.border.color', defaultColor);
coerce('marker.border.arearatio');
// disable 1D transforms - that would defeat the purpose of this trace type, performance!
traceOut._length = null;
};
/***/ }),
/***/ 156:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var deprecationWarning = ['*pointcloud* trace is deprecated!', 'Please consider switching to the *scattergl* trace type.'].join(' ');
module.exports = {
attributes: __webpack_require__(35484),
supplyDefaults: __webpack_require__(41904),
// reuse the Scatter3D 'dummy' calc step so that legends know what to do
calc: __webpack_require__(41484),
plot: __webpack_require__(11072),
moduleType: 'trace',
name: 'pointcloud',
basePlotModule: __webpack_require__(39952),
categories: ['gl', 'gl2d', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 41440:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fontAttrs = __webpack_require__(25376);
var baseAttrs = __webpack_require__(45464);
var colorAttrs = __webpack_require__(22548);
var fxAttrs = __webpack_require__(55756);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var colorAttributes = __webpack_require__(49084);
var templatedArray = (__webpack_require__(31780).templatedArray);
var descriptionOnlyNumbers = (__webpack_require__(29736).descriptionOnlyNumbers);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var attrs = module.exports = overrideAll({
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: [],
arrayOk: false
}),
hoverlabel: fxAttrs.hoverlabel,
domain: domainAttrs({
name: 'sankey',
trace: true
}),
orientation: {
valType: 'enumerated',
values: ['v', 'h'],
dflt: 'h'
},
valueformat: {
valType: 'string',
dflt: '.3s',
description: descriptionOnlyNumbers('value')
},
valuesuffix: {
valType: 'string',
dflt: ''
},
arrangement: {
valType: 'enumerated',
values: ['snap', 'perpendicular', 'freeform', 'fixed'],
dflt: 'snap'
},
textfont: fontAttrs({
autoShadowDflt: true
}),
// Remove top-level customdata
customdata: undefined,
node: {
label: {
valType: 'data_array',
dflt: []
},
groups: {
valType: 'info_array',
impliedEdits: {
x: [],
y: []
},
dimensions: 2,
freeLength: true,
dflt: [],
items: {
valType: 'number',
editType: 'calc'
}
},
x: {
valType: 'data_array',
dflt: []
},
y: {
valType: 'data_array',
dflt: []
},
color: {
valType: 'color',
arrayOk: true
},
customdata: {
valType: 'data_array',
editType: 'calc'
},
line: {
color: {
valType: 'color',
dflt: colorAttrs.defaultLine,
arrayOk: true
},
width: {
valType: 'number',
min: 0,
dflt: 0.5,
arrayOk: true
}
},
pad: {
valType: 'number',
arrayOk: false,
min: 0,
dflt: 20
},
thickness: {
valType: 'number',
arrayOk: false,
min: 1,
dflt: 20
},
hoverinfo: {
valType: 'enumerated',
values: ['all', 'none', 'skip'],
dflt: 'all'
},
hoverlabel: fxAttrs.hoverlabel,
// needs editType override,
hovertemplate: hovertemplateAttrs({}, {
keys: ['value', 'label']
}),
align: {
valType: 'enumerated',
values: ['justify', 'left', 'right', 'center'],
dflt: 'justify'
}
},
link: {
arrowlen: {
valType: 'number',
min: 0,
dflt: 0
},
label: {
valType: 'data_array',
dflt: []
},
color: {
valType: 'color',
arrayOk: true
},
hovercolor: {
valType: 'color',
arrayOk: true
},
customdata: {
valType: 'data_array',
editType: 'calc'
},
line: {
color: {
valType: 'color',
dflt: colorAttrs.defaultLine,
arrayOk: true
},
width: {
valType: 'number',
min: 0,
dflt: 0,
arrayOk: true
}
},
source: {
valType: 'data_array',
dflt: []
},
target: {
valType: 'data_array',
dflt: []
},
value: {
valType: 'data_array',
dflt: []
},
hoverinfo: {
valType: 'enumerated',
values: ['all', 'none', 'skip'],
dflt: 'all'
},
hoverlabel: fxAttrs.hoverlabel,
// needs editType override,
hovertemplate: hovertemplateAttrs({}, {
keys: ['value', 'label']
}),
colorscales: templatedArray('concentrationscales', {
editType: 'calc',
label: {
valType: 'string',
editType: 'calc',
dflt: ''
},
cmax: {
valType: 'number',
editType: 'calc',
dflt: 1
},
cmin: {
valType: 'number',
editType: 'calc',
dflt: 0
},
colorscale: extendFlat(colorAttributes().colorscale, {
dflt: [[0, 'white'], [1, 'black']]
})
})
}
}, 'calc', 'nested');
attrs.transforms = undefined;
/***/ }),
/***/ 10760:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var overrideAll = (__webpack_require__(67824).overrideAll);
var getModuleCalcData = (__webpack_require__(84888)/* .getModuleCalcData */ ._M);
var plot = __webpack_require__(59596);
var fxAttrs = __webpack_require__(65460);
var setCursor = __webpack_require__(93972);
var dragElement = __webpack_require__(86476);
var prepSelect = (__webpack_require__(22676).prepSelect);
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var SANKEY = 'sankey';
exports.name = SANKEY;
exports.baseLayoutAttrOverrides = overrideAll({
hoverlabel: fxAttrs.hoverlabel
}, 'plot', 'nested');
exports.plot = function (gd) {
var calcData = getModuleCalcData(gd.calcdata, SANKEY)[0];
plot(gd, calcData);
exports.updateFx(gd);
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var hadPlot = oldFullLayout._has && oldFullLayout._has(SANKEY);
var hasPlot = newFullLayout._has && newFullLayout._has(SANKEY);
if (hadPlot && !hasPlot) {
oldFullLayout._paperdiv.selectAll('.sankey').remove();
oldFullLayout._paperdiv.selectAll('.bgsankey').remove();
}
};
exports.updateFx = function (gd) {
for (var i = 0; i < gd._fullData.length; i++) {
subplotUpdateFx(gd, i);
}
};
function subplotUpdateFx(gd, index) {
var trace = gd._fullData[index];
var fullLayout = gd._fullLayout;
var dragMode = fullLayout.dragmode;
var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
var bgRect = trace._bgRect;
if (!bgRect) return;
if (dragMode === 'pan' || dragMode === 'zoom') return;
setCursor(bgRect, cursor);
var xaxis = {
_id: 'x',
c2p: Lib.identity,
_offset: trace._sankey.translateX,
_length: trace._sankey.width
};
var yaxis = {
_id: 'y',
c2p: Lib.identity,
_offset: trace._sankey.translateY,
_length: trace._sankey.height
};
// Note: dragOptions is needed to be declared for all dragmodes because
// it's the object that holds persistent selection state.
var dragOptions = {
gd: gd,
element: bgRect.node(),
plotinfo: {
id: index,
xaxis: xaxis,
yaxis: yaxis,
fillRangeItems: Lib.noop
},
subplot: index,
// create mock x/y axes for hover routine
xaxes: [xaxis],
yaxes: [yaxis],
doneFnCompleted: function (selection) {
var traceNow = gd._fullData[index];
var newGroups;
var oldGroups = traceNow.node.groups.slice();
var newGroup = [];
function findNode(pt) {
var nodes = traceNow._sankey.graph.nodes;
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].pointNumber === pt) return nodes[i];
}
}
for (var j = 0; j < selection.length; j++) {
var node = findNode(selection[j].pointNumber);
if (!node) continue;
// If the node represents a group
if (node.group) {
// Add all its children to the current selection
for (var k = 0; k < node.childrenNodes.length; k++) {
newGroup.push(node.childrenNodes[k].pointNumber);
}
// Flag group for removal from existing list of groups
oldGroups[node.pointNumber - traceNow.node._count] = false;
} else {
newGroup.push(node.pointNumber);
}
}
newGroups = oldGroups.filter(Boolean).concat([newGroup]);
Registry.call('_guiRestyle', gd, {
'node.groups': [newGroups]
}, index);
}
};
dragOptions.prepFn = function (e, startX, startY) {
prepSelect(e, startX, startY, dragOptions, dragMode);
};
dragElement.init(dragOptions);
}
/***/ }),
/***/ 48068:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var tarjan = __webpack_require__(78484);
var Lib = __webpack_require__(3400);
var wrap = (__webpack_require__(71688).wrap);
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var isIndex = Lib.isIndex;
var Colorscale = __webpack_require__(8932);
function convertToD3Sankey(trace) {
var nodeSpec = trace.node;
var linkSpec = trace.link;
var links = [];
var hasLinkColorArray = isArrayOrTypedArray(linkSpec.color);
var hasLinkHoverColorArray = isArrayOrTypedArray(linkSpec.hovercolor);
var hasLinkCustomdataArray = isArrayOrTypedArray(linkSpec.customdata);
var linkedNodes = {};
var components = {};
var componentCount = linkSpec.colorscales.length;
var i;
for (i = 0; i < componentCount; i++) {
var cscale = linkSpec.colorscales[i];
var specs = Colorscale.extractScale(cscale, {
cLetter: 'c'
});
var scale = Colorscale.makeColorScaleFunc(specs);
components[cscale.label] = scale;
}
var maxNodeId = 0;
for (i = 0; i < linkSpec.value.length; i++) {
if (linkSpec.source[i] > maxNodeId) maxNodeId = linkSpec.source[i];
if (linkSpec.target[i] > maxNodeId) maxNodeId = linkSpec.target[i];
}
var nodeCount = maxNodeId + 1;
trace.node._count = nodeCount;
// Group nodes
var j;
var groups = trace.node.groups;
var groupLookup = {};
for (i = 0; i < groups.length; i++) {
var group = groups[i];
// Build a lookup table to quickly find in which group a node is
for (j = 0; j < group.length; j++) {
var nodeIndex = group[j];
var groupIndex = nodeCount + i;
if (groupLookup.hasOwnProperty(nodeIndex)) {
Lib.warn('Node ' + nodeIndex + ' is already part of a group.');
} else {
groupLookup[nodeIndex] = groupIndex;
}
}
}
// Process links
var groupedLinks = {
source: [],
target: []
};
for (i = 0; i < linkSpec.value.length; i++) {
var val = linkSpec.value[i];
// remove negative values, but keep zeros with special treatment
var source = linkSpec.source[i];
var target = linkSpec.target[i];
if (!(val > 0 && isIndex(source, nodeCount) && isIndex(target, nodeCount))) {
continue;
}
// Remove links that are within the same group
if (groupLookup.hasOwnProperty(source) && groupLookup.hasOwnProperty(target) && groupLookup[source] === groupLookup[target]) {
continue;
}
// if link targets a node in the group, relink target to that group
if (groupLookup.hasOwnProperty(target)) {
target = groupLookup[target];
}
// if link originates from a node in a group, relink source to that group
if (groupLookup.hasOwnProperty(source)) {
source = groupLookup[source];
}
source = +source;
target = +target;
linkedNodes[source] = linkedNodes[target] = true;
var label = '';
if (linkSpec.label && linkSpec.label[i]) label = linkSpec.label[i];
var concentrationscale = null;
if (label && components.hasOwnProperty(label)) concentrationscale = components[label];
links.push({
pointNumber: i,
label: label,
color: hasLinkColorArray ? linkSpec.color[i] : linkSpec.color,
hovercolor: hasLinkHoverColorArray ? linkSpec.hovercolor[i] : linkSpec.hovercolor,
customdata: hasLinkCustomdataArray ? linkSpec.customdata[i] : linkSpec.customdata,
concentrationscale: concentrationscale,
source: source,
target: target,
value: +val
});
groupedLinks.source.push(source);
groupedLinks.target.push(target);
}
// Process nodes
var totalCount = nodeCount + groups.length;
var hasNodeColorArray = isArrayOrTypedArray(nodeSpec.color);
var hasNodeCustomdataArray = isArrayOrTypedArray(nodeSpec.customdata);
var nodes = [];
for (i = 0; i < totalCount; i++) {
if (!linkedNodes[i]) continue;
var l = nodeSpec.label[i];
nodes.push({
group: i > nodeCount - 1,
childrenNodes: [],
pointNumber: i,
label: l,
color: hasNodeColorArray ? nodeSpec.color[i] : nodeSpec.color,
customdata: hasNodeCustomdataArray ? nodeSpec.customdata[i] : nodeSpec.customdata
});
}
// Check if we have circularity on the resulting graph
var circular = false;
if (circularityPresent(totalCount, groupedLinks.source, groupedLinks.target)) {
circular = true;
}
return {
circular: circular,
links: links,
nodes: nodes,
// Data structure for groups
groups: groups,
groupLookup: groupLookup
};
}
function circularityPresent(nodeLen, sources, targets) {
var nodes = Lib.init2dArray(nodeLen, 0);
for (var i = 0; i < Math.min(sources.length, targets.length); i++) {
if (Lib.isIndex(sources[i], nodeLen) && Lib.isIndex(targets[i], nodeLen)) {
if (sources[i] === targets[i]) {
return true; // self-link which is also a scc of one
}
nodes[sources[i]].push(targets[i]);
}
}
var scc = tarjan(nodes);
// Tarján's strongly connected components algorithm coded by Mikola Lysenko
// returns at least one non-singular component if there's circularity in the graph
return scc.components.some(function (c) {
return c.length > 1;
});
}
module.exports = function calc(gd, trace) {
var result = convertToD3Sankey(trace);
return wrap({
circular: result.circular,
_nodes: result.nodes,
_links: result.links,
// Data structure for grouping
_groups: result.groups,
_groupLookup: result.groupLookup
});
};
/***/ }),
/***/ 11820:
/***/ (function(module) {
"use strict";
module.exports = {
nodeTextOffsetHorizontal: 4,
nodeTextOffsetVertical: 3,
nodePadAcross: 10,
sankeyIterations: 50,
forceIterations: 5,
forceTicksPerFrame: 10,
duration: 500,
ease: 'linear',
cn: {
sankey: 'sankey',
sankeyLinks: 'sankey-links',
sankeyLink: 'sankey-link',
sankeyNodeSet: 'sankey-node-set',
sankeyNode: 'sankey-node',
nodeRect: 'node-rect',
nodeLabel: 'node-label'
}
};
/***/ }),
/***/ 47140:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(41440);
var Color = __webpack_require__(76308);
var tinycolor = __webpack_require__(49760);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var handleHoverLabelDefaults = __webpack_require__(16132);
var Template = __webpack_require__(31780);
var handleArrayContainerDefaults = __webpack_require__(51272);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var hoverlabelDefault = Lib.extendDeep(layout.hoverlabel, traceIn.hoverlabel);
// node attributes
var nodeIn = traceIn.node;
var nodeOut = Template.newContainer(traceOut, 'node');
function coerceNode(attr, dflt) {
return Lib.coerce(nodeIn, nodeOut, attributes.node, attr, dflt);
}
coerceNode('label');
coerceNode('groups');
coerceNode('x');
coerceNode('y');
coerceNode('pad');
coerceNode('thickness');
coerceNode('line.color');
coerceNode('line.width');
coerceNode('hoverinfo', traceIn.hoverinfo);
handleHoverLabelDefaults(nodeIn, nodeOut, coerceNode, hoverlabelDefault);
coerceNode('hovertemplate');
coerceNode('align');
var colors = layout.colorway;
var defaultNodePalette = function (i) {
return colors[i % colors.length];
};
coerceNode('color', nodeOut.label.map(function (d, i) {
return Color.addOpacity(defaultNodePalette(i), 0.8);
}));
coerceNode('customdata');
// link attributes
var linkIn = traceIn.link || {};
var linkOut = Template.newContainer(traceOut, 'link');
function coerceLink(attr, dflt) {
return Lib.coerce(linkIn, linkOut, attributes.link, attr, dflt);
}
coerceLink('label');
coerceLink('arrowlen');
coerceLink('source');
coerceLink('target');
coerceLink('value');
coerceLink('line.color');
coerceLink('line.width');
coerceLink('hoverinfo', traceIn.hoverinfo);
handleHoverLabelDefaults(linkIn, linkOut, coerceLink, hoverlabelDefault);
coerceLink('hovertemplate');
var darkBG = tinycolor(layout.paper_bgcolor).getLuminance() < 0.333;
var defaultLinkColor = darkBG ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.2)';
var linkColor = coerceLink('color', defaultLinkColor);
function makeDefaultHoverColor(_linkColor) {
var tc = tinycolor(_linkColor);
if (!tc.isValid()) {
// hopefully the user-specified color is valid, but if not that can be caught elsewhere
return _linkColor;
}
var alpha = tc.getAlpha();
if (alpha <= 0.8) {
tc.setAlpha(alpha + 0.2);
} else {
tc = darkBG ? tc.brighten() : tc.darken();
}
return tc.toRgbString();
}
coerceLink('hovercolor', Array.isArray(linkColor) ? linkColor.map(makeDefaultHoverColor) : makeDefaultHoverColor(linkColor));
coerceLink('customdata');
handleArrayContainerDefaults(linkIn, linkOut, {
name: 'colorscales',
handleItemDefaults: concentrationscalesDefaults
});
handleDomainDefaults(traceOut, layout, coerce);
coerce('orientation');
coerce('valueformat');
coerce('valuesuffix');
var dfltArrangement;
if (nodeOut.x.length && nodeOut.y.length) {
dfltArrangement = 'freeform';
}
coerce('arrangement', dfltArrangement);
Lib.coerceFont(coerce, 'textfont', layout.font, {
autoShadowDflt: true
});
// disable 1D transforms - arrays here are 1D but their lengths/meanings
// don't match, between nodes and links
traceOut._length = null;
};
function concentrationscalesDefaults(In, Out) {
function coerce(attr, dflt) {
return Lib.coerce(In, Out, attributes.link.colorscales, attr, dflt);
}
coerce('label');
coerce('cmin');
coerce('cmax');
coerce('colorscale');
}
/***/ }),
/***/ 45499:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(41440),
supplyDefaults: __webpack_require__(47140),
calc: __webpack_require__(48068),
plot: __webpack_require__(59596),
moduleType: 'trace',
name: 'sankey',
basePlotModule: __webpack_require__(10760),
selectPoints: __webpack_require__(81128),
categories: ['noOpacity'],
meta: {}
};
/***/ }),
/***/ 59596:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var numberFormat = Lib.numberFormat;
var render = __webpack_require__(83248);
var Fx = __webpack_require__(93024);
var Color = __webpack_require__(76308);
var cn = (__webpack_require__(11820).cn);
var _ = Lib._;
function renderableValuePresent(d) {
return d !== '';
}
function ownTrace(selection, d) {
return selection.filter(function (s) {
return s.key === d.traceId;
});
}
function makeTranslucent(element, alpha) {
d3.select(element).select('path').style('fill-opacity', alpha);
d3.select(element).select('rect').style('fill-opacity', alpha);
}
function makeTextContrasty(element) {
d3.select(element).select('text.name').style('fill', 'black');
}
function relatedLinks(d) {
return function (l) {
return d.node.sourceLinks.indexOf(l.link) !== -1 || d.node.targetLinks.indexOf(l.link) !== -1;
};
}
function relatedNodes(l) {
return function (d) {
return d.node.sourceLinks.indexOf(l.link) !== -1 || d.node.targetLinks.indexOf(l.link) !== -1;
};
}
function nodeHoveredStyle(sankeyNode, d, sankey) {
if (d && sankey) {
ownTrace(sankey, d).selectAll('.' + cn.sankeyLink).filter(relatedLinks(d)).call(linkHoveredStyle.bind(0, d, sankey, false));
}
}
function nodeNonHoveredStyle(sankeyNode, d, sankey) {
if (d && sankey) {
ownTrace(sankey, d).selectAll('.' + cn.sankeyLink).filter(relatedLinks(d)).call(linkNonHoveredStyle.bind(0, d, sankey, false));
}
}
function linkHoveredStyle(d, sankey, visitNodes, sankeyLink) {
sankeyLink.style('fill', function (l) {
if (!l.link.concentrationscale) {
return l.tinyColorHoverHue;
}
}).style('fill-opacity', function (l) {
if (!l.link.concentrationscale) {
return l.tinyColorHoverAlpha;
}
});
sankeyLink.each(function (curLink) {
var label = curLink.link.label;
if (label !== '') {
ownTrace(sankey, d).selectAll('.' + cn.sankeyLink).filter(function (l) {
return l.link.label === label;
}).style('fill', function (l) {
if (!l.link.concentrationscale) {
return l.tinyColorHoverHue;
}
}).style('fill-opacity', function (l) {
if (!l.link.concentrationscale) {
return l.tinyColorHoverAlpha;
}
});
}
});
if (visitNodes) {
ownTrace(sankey, d).selectAll('.' + cn.sankeyNode).filter(relatedNodes(d)).call(nodeHoveredStyle);
}
}
function linkNonHoveredStyle(d, sankey, visitNodes, sankeyLink) {
sankeyLink.style('fill', function (l) {
return l.tinyColorHue;
}).style('fill-opacity', function (l) {
return l.tinyColorAlpha;
});
sankeyLink.each(function (curLink) {
var label = curLink.link.label;
if (label !== '') {
ownTrace(sankey, d).selectAll('.' + cn.sankeyLink).filter(function (l) {
return l.link.label === label;
}).style('fill', function (l) {
return l.tinyColorHue;
}).style('fill-opacity', function (l) {
return l.tinyColorAlpha;
});
}
});
if (visitNodes) {
ownTrace(sankey, d).selectAll(cn.sankeyNode).filter(relatedNodes(d)).call(nodeNonHoveredStyle);
}
}
// does not support array values for now
function castHoverOption(trace, attr) {
var labelOpts = trace.hoverlabel || {};
var val = Lib.nestedProperty(labelOpts, attr).get();
return Array.isArray(val) ? false : val;
}
module.exports = function plot(gd, calcData) {
var fullLayout = gd._fullLayout;
var svg = fullLayout._paper;
var size = fullLayout._size;
// stash initial view
for (var i = 0; i < gd._fullData.length; i++) {
if (!gd._fullData[i].visible) continue;
if (gd._fullData[i].type !== cn.sankey) continue;
if (!gd._fullData[i]._viewInitial) {
var node = gd._fullData[i].node;
gd._fullData[i]._viewInitial = {
node: {
groups: node.groups.slice(),
x: node.x.slice(),
y: node.y.slice()
}
};
}
}
var linkSelect = function (element, d) {
var evt = d.link;
evt.originalEvent = d3.event;
gd._hoverdata = [evt];
Fx.click(gd, {
target: true
});
};
var linkHover = function (element, d, sankey) {
if (gd._fullLayout.hovermode === false) return;
d3.select(element).call(linkHoveredStyle.bind(0, d, sankey, true));
if (d.link.trace.link.hoverinfo !== 'skip') {
d.link.fullData = d.link.trace;
gd.emit('plotly_hover', {
event: d3.event,
points: [d.link]
});
}
};
var sourceLabel = _(gd, 'source:') + ' ';
var targetLabel = _(gd, 'target:') + ' ';
var concentrationLabel = _(gd, 'concentration:') + ' ';
var incomingLabel = _(gd, 'incoming flow count:') + ' ';
var outgoingLabel = _(gd, 'outgoing flow count:') + ' ';
var linkHoverFollow = function (element, d) {
if (gd._fullLayout.hovermode === false) return;
var obj = d.link.trace.link;
if (obj.hoverinfo === 'none' || obj.hoverinfo === 'skip') return;
var hoverItems = [];
function hoverCenterPosition(link) {
var hoverCenterX, hoverCenterY;
if (link.circular) {
hoverCenterX = (link.circularPathData.leftInnerExtent + link.circularPathData.rightInnerExtent) / 2;
hoverCenterY = link.circularPathData.verticalFullExtent;
} else {
hoverCenterX = (link.source.x1 + link.target.x0) / 2;
hoverCenterY = (link.y0 + link.y1) / 2;
}
var center = [hoverCenterX, hoverCenterY];
if (link.trace.orientation === 'v') center.reverse();
center[0] += d.parent.translateX;
center[1] += d.parent.translateY;
return center;
}
// For each related links, create a hoverItem
var anchorIndex = 0;
for (var i = 0; i < d.flow.links.length; i++) {
var link = d.flow.links[i];
if (gd._fullLayout.hovermode === 'closest' && d.link.pointNumber !== link.pointNumber) continue;
if (d.link.pointNumber === link.pointNumber) anchorIndex = i;
link.fullData = link.trace;
obj = d.link.trace.link;
var hoverCenter = hoverCenterPosition(link);
var hovertemplateLabels = {
valueLabel: numberFormat(d.valueFormat)(link.value) + d.valueSuffix
};
hoverItems.push({
x: hoverCenter[0],
y: hoverCenter[1],
name: hovertemplateLabels.valueLabel,
text: [link.label || '', sourceLabel + link.source.label, targetLabel + link.target.label, link.concentrationscale ? concentrationLabel + numberFormat('%0.2f')(link.flow.labelConcentration) : ''].filter(renderableValuePresent).join(' '),
color: castHoverOption(obj, 'bgcolor') || Color.addOpacity(link.color, 1),
borderColor: castHoverOption(obj, 'bordercolor'),
fontFamily: castHoverOption(obj, 'font.family'),
fontSize: castHoverOption(obj, 'font.size'),
fontColor: castHoverOption(obj, 'font.color'),
fontWeight: castHoverOption(obj, 'font.weight'),
fontStyle: castHoverOption(obj, 'font.style'),
fontVariant: castHoverOption(obj, 'font.variant'),
fontTextcase: castHoverOption(obj, 'font.textcase'),
fontLineposition: castHoverOption(obj, 'font.lineposition'),
fontShadow: castHoverOption(obj, 'font.shadow'),
nameLength: castHoverOption(obj, 'namelength'),
textAlign: castHoverOption(obj, 'align'),
idealAlign: d3.event.x < hoverCenter[0] ? 'right' : 'left',
hovertemplate: obj.hovertemplate,
hovertemplateLabels: hovertemplateLabels,
eventData: [link]
});
}
var tooltips = Fx.loneHover(hoverItems, {
container: fullLayout._hoverlayer.node(),
outerContainer: fullLayout._paper.node(),
gd: gd,
anchorIndex: anchorIndex
});
tooltips.each(function () {
var tooltip = this;
if (!d.link.concentrationscale) {
makeTranslucent(tooltip, 0.65);
}
makeTextContrasty(tooltip);
});
};
var linkUnhover = function (element, d, sankey) {
if (gd._fullLayout.hovermode === false) return;
d3.select(element).call(linkNonHoveredStyle.bind(0, d, sankey, true));
if (d.link.trace.link.hoverinfo !== 'skip') {
d.link.fullData = d.link.trace;
gd.emit('plotly_unhover', {
event: d3.event,
points: [d.link]
});
}
Fx.loneUnhover(fullLayout._hoverlayer.node());
};
var nodeSelect = function (element, d, sankey) {
var evt = d.node;
evt.originalEvent = d3.event;
gd._hoverdata = [evt];
d3.select(element).call(nodeNonHoveredStyle, d, sankey);
Fx.click(gd, {
target: true
});
};
var nodeHover = function (element, d, sankey) {
if (gd._fullLayout.hovermode === false) return;
d3.select(element).call(nodeHoveredStyle, d, sankey);
if (d.node.trace.node.hoverinfo !== 'skip') {
d.node.fullData = d.node.trace;
gd.emit('plotly_hover', {
event: d3.event,
points: [d.node]
});
}
};
var nodeHoverFollow = function (element, d) {
if (gd._fullLayout.hovermode === false) return;
var obj = d.node.trace.node;
if (obj.hoverinfo === 'none' || obj.hoverinfo === 'skip') return;
var nodeRect = d3.select(element).select('.' + cn.nodeRect);
var rootBBox = gd._fullLayout._paperdiv.node().getBoundingClientRect();
var boundingBox = nodeRect.node().getBoundingClientRect();
var hoverCenterX0 = boundingBox.left - 2 - rootBBox.left;
var hoverCenterX1 = boundingBox.right + 2 - rootBBox.left;
var hoverCenterY = boundingBox.top + boundingBox.height / 4 - rootBBox.top;
var hovertemplateLabels = {
valueLabel: numberFormat(d.valueFormat)(d.node.value) + d.valueSuffix
};
d.node.fullData = d.node.trace;
gd._fullLayout._calcInverseTransform(gd);
var scaleX = gd._fullLayout._invScaleX;
var scaleY = gd._fullLayout._invScaleY;
var tooltip = Fx.loneHover({
x0: scaleX * hoverCenterX0,
x1: scaleX * hoverCenterX1,
y: scaleY * hoverCenterY,
name: numberFormat(d.valueFormat)(d.node.value) + d.valueSuffix,
text: [d.node.label, incomingLabel + d.node.targetLinks.length, outgoingLabel + d.node.sourceLinks.length].filter(renderableValuePresent).join(' '),
color: castHoverOption(obj, 'bgcolor') || d.tinyColorHue,
borderColor: castHoverOption(obj, 'bordercolor'),
fontFamily: castHoverOption(obj, 'font.family'),
fontSize: castHoverOption(obj, 'font.size'),
fontColor: castHoverOption(obj, 'font.color'),
fontWeight: castHoverOption(obj, 'font.weight'),
fontStyle: castHoverOption(obj, 'font.style'),
fontVariant: castHoverOption(obj, 'font.variant'),
fontTextcase: castHoverOption(obj, 'font.textcase'),
fontLineposition: castHoverOption(obj, 'font.lineposition'),
fontShadow: castHoverOption(obj, 'font.shadow'),
nameLength: castHoverOption(obj, 'namelength'),
textAlign: castHoverOption(obj, 'align'),
idealAlign: 'left',
hovertemplate: obj.hovertemplate,
hovertemplateLabels: hovertemplateLabels,
eventData: [d.node]
}, {
container: fullLayout._hoverlayer.node(),
outerContainer: fullLayout._paper.node(),
gd: gd
});
makeTranslucent(tooltip, 0.85);
makeTextContrasty(tooltip);
};
var nodeUnhover = function (element, d, sankey) {
if (gd._fullLayout.hovermode === false) return;
d3.select(element).call(nodeNonHoveredStyle, d, sankey);
if (d.node.trace.node.hoverinfo !== 'skip') {
d.node.fullData = d.node.trace;
gd.emit('plotly_unhover', {
event: d3.event,
points: [d.node]
});
}
Fx.loneUnhover(fullLayout._hoverlayer.node());
};
render(gd, svg, calcData, {
width: size.w,
height: size.h,
margin: {
t: size.t,
r: size.r,
b: size.b,
l: size.l
}
}, {
linkEvents: {
hover: linkHover,
follow: linkHoverFollow,
unhover: linkUnhover,
select: linkSelect
},
nodeEvents: {
hover: nodeHover,
follow: nodeHoverFollow,
unhover: nodeUnhover,
select: nodeSelect
}
});
};
/***/ }),
/***/ 83248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3Force = __webpack_require__(49812);
var interpolateNumber = (__webpack_require__(67756)/* .interpolateNumber */ .Gz);
var d3 = __webpack_require__(33428);
var d3Sankey = __webpack_require__(26800);
var d3SankeyCircular = __webpack_require__(48932);
var c = __webpack_require__(11820);
var tinycolor = __webpack_require__(49760);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var strRotate = Lib.strRotate;
var gup = __webpack_require__(71688);
var keyFun = gup.keyFun;
var repeat = gup.repeat;
var unwrap = gup.unwrap;
var svgTextUtils = __webpack_require__(72736);
var Registry = __webpack_require__(24040);
var alignmentConstants = __webpack_require__(84284);
var CAP_SHIFT = alignmentConstants.CAP_SHIFT;
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var TEXTPAD = 3;
// view models
function sankeyModel(layout, d, traceIndex) {
var calcData = unwrap(d);
var trace = calcData.trace;
var domain = trace.domain;
var horizontal = trace.orientation === 'h';
var nodePad = trace.node.pad;
var nodeThickness = trace.node.thickness;
var nodeAlign = {
justify: d3Sankey.sankeyJustify,
left: d3Sankey.sankeyLeft,
right: d3Sankey.sankeyRight,
center: d3Sankey.sankeyCenter
}[trace.node.align];
var width = layout.width * (domain.x[1] - domain.x[0]);
var height = layout.height * (domain.y[1] - domain.y[0]);
var nodes = calcData._nodes;
var links = calcData._links;
var circular = calcData.circular;
// Select Sankey generator
var sankey;
if (circular) {
sankey = d3SankeyCircular.sankeyCircular().circularLinkGap(0);
} else {
sankey = d3Sankey.sankey();
}
sankey.iterations(c.sankeyIterations).size(horizontal ? [width, height] : [height, width]).nodeWidth(nodeThickness).nodePadding(nodePad).nodeId(function (d) {
return d.pointNumber;
}).nodeAlign(nodeAlign).nodes(nodes).links(links);
var graph = sankey();
if (sankey.nodePadding() < nodePad) {
Lib.warn('node.pad was reduced to ', sankey.nodePadding(), ' to fit within the figure.');
}
// Counters for nested loops
var i, j, k;
// Create transient nodes for animations
for (var nodePointNumber in calcData._groupLookup) {
var groupIndex = parseInt(calcData._groupLookup[nodePointNumber]);
// Find node representing groupIndex
var groupingNode;
for (i = 0; i < graph.nodes.length; i++) {
if (graph.nodes[i].pointNumber === groupIndex) {
groupingNode = graph.nodes[i];
break;
}
}
// If groupinNode is undefined, no links are targeting this group
if (!groupingNode) continue;
var child = {
pointNumber: parseInt(nodePointNumber),
x0: groupingNode.x0,
x1: groupingNode.x1,
y0: groupingNode.y0,
y1: groupingNode.y1,
partOfGroup: true,
sourceLinks: [],
targetLinks: []
};
graph.nodes.unshift(child);
groupingNode.childrenNodes.unshift(child);
}
function computeLinkConcentrations() {
for (i = 0; i < graph.nodes.length; i++) {
var node = graph.nodes[i];
// Links connecting the same two nodes are part of a flow
var flows = {};
var flowKey;
var link;
for (j = 0; j < node.targetLinks.length; j++) {
link = node.targetLinks[j];
flowKey = link.source.pointNumber + ':' + link.target.pointNumber;
if (!flows.hasOwnProperty(flowKey)) flows[flowKey] = [];
flows[flowKey].push(link);
}
// Compute statistics for each flow
var keys = Object.keys(flows);
for (j = 0; j < keys.length; j++) {
flowKey = keys[j];
var flowLinks = flows[flowKey];
// Find the total size of the flow and total size per label
var total = 0;
var totalPerLabel = {};
for (k = 0; k < flowLinks.length; k++) {
link = flowLinks[k];
if (!totalPerLabel[link.label]) totalPerLabel[link.label] = 0;
totalPerLabel[link.label] += link.value;
total += link.value;
}
// Find the ratio of the link's value and the size of the flow
for (k = 0; k < flowLinks.length; k++) {
link = flowLinks[k];
link.flow = {
value: total,
labelConcentration: totalPerLabel[link.label] / total,
concentration: link.value / total,
links: flowLinks
};
if (link.concentrationscale) {
link.color = tinycolor(link.concentrationscale(link.flow.labelConcentration));
}
}
}
// Gather statistics of all links at current node
var totalOutflow = 0;
for (j = 0; j < node.sourceLinks.length; j++) {
totalOutflow += node.sourceLinks[j].value;
}
for (j = 0; j < node.sourceLinks.length; j++) {
link = node.sourceLinks[j];
link.concentrationOut = link.value / totalOutflow;
}
var totalInflow = 0;
for (j = 0; j < node.targetLinks.length; j++) {
totalInflow += node.targetLinks[j].value;
}
for (j = 0; j < node.targetLinks.length; j++) {
link = node.targetLinks[j];
link.concenrationIn = link.value / totalInflow;
}
}
}
computeLinkConcentrations();
// Push any overlapping nodes down.
function resolveCollisionsTopToBottom(columns) {
columns.forEach(function (nodes) {
var node;
var dy;
var y = 0;
var n = nodes.length;
var i;
nodes.sort(function (a, b) {
return a.y0 - b.y0;
});
for (i = 0; i < n; ++i) {
node = nodes[i];
if (node.y0 >= y) {
// No overlap
} else {
dy = y - node.y0;
if (dy > 1e-6) node.y0 += dy, node.y1 += dy;
}
y = node.y1 + nodePad;
}
});
}
// Group nodes into columns based on their x position
function snapToColumns(nodes) {
// Sort nodes by x position
var orderedNodes = nodes.map(function (n, i) {
return {
x0: n.x0,
index: i
};
}).sort(function (a, b) {
return a.x0 - b.x0;
});
var columns = [];
var colNumber = -1;
var colX; // Position of column
var lastX = -Infinity; // Position of last node
var dx;
for (i = 0; i < orderedNodes.length; i++) {
var node = nodes[orderedNodes[i].index];
// If the node does not overlap with the last one
if (node.x0 > lastX + nodeThickness) {
// Start a new column
colNumber += 1;
colX = node.x0;
}
lastX = node.x0;
// Add node to its associated column
if (!columns[colNumber]) columns[colNumber] = [];
columns[colNumber].push(node);
// Change node's x position to align it with its column
dx = colX - node.x0;
node.x0 += dx, node.x1 += dx;
}
return columns;
}
// Force node position
if (trace.node.x.length && trace.node.y.length) {
for (i = 0; i < Math.min(trace.node.x.length, trace.node.y.length, graph.nodes.length); i++) {
if (trace.node.x[i] && trace.node.y[i]) {
var pos = [trace.node.x[i] * width, trace.node.y[i] * height];
graph.nodes[i].x0 = pos[0] - nodeThickness / 2;
graph.nodes[i].x1 = pos[0] + nodeThickness / 2;
var nodeHeight = graph.nodes[i].y1 - graph.nodes[i].y0;
graph.nodes[i].y0 = pos[1] - nodeHeight / 2;
graph.nodes[i].y1 = pos[1] + nodeHeight / 2;
}
}
if (trace.arrangement === 'snap') {
nodes = graph.nodes;
var columns = snapToColumns(nodes);
resolveCollisionsTopToBottom(columns);
}
// Update links
sankey.update(graph);
}
return {
circular: circular,
key: traceIndex,
trace: trace,
guid: Lib.randstr(),
horizontal: horizontal,
width: width,
height: height,
nodePad: trace.node.pad,
nodeLineColor: trace.node.line.color,
nodeLineWidth: trace.node.line.width,
linkLineColor: trace.link.line.color,
linkLineWidth: trace.link.line.width,
linkArrowLength: trace.link.arrowlen,
valueFormat: trace.valueformat,
valueSuffix: trace.valuesuffix,
textFont: trace.textfont,
translateX: domain.x[0] * layout.width + layout.margin.l,
translateY: layout.height - domain.y[1] * layout.height + layout.margin.t,
dragParallel: horizontal ? height : width,
dragPerpendicular: horizontal ? width : height,
arrangement: trace.arrangement,
sankey: sankey,
graph: graph,
forceLayouts: {},
interactionState: {
dragInProgress: false,
hovered: false
}
};
}
function linkModel(d, l, i) {
var tc = tinycolor(l.color);
var htc = tinycolor(l.hovercolor);
var basicKey = l.source.label + '|' + l.target.label;
var key = basicKey + '__' + i;
// for event data
l.trace = d.trace;
l.curveNumber = d.trace.index;
return {
circular: d.circular,
key: key,
traceId: d.key,
pointNumber: l.pointNumber,
link: l,
tinyColorHue: Color.tinyRGB(tc),
tinyColorAlpha: tc.getAlpha(),
tinyColorHoverHue: Color.tinyRGB(htc),
tinyColorHoverAlpha: htc.getAlpha(),
linkPath: linkPath,
linkLineColor: d.linkLineColor,
linkLineWidth: d.linkLineWidth,
linkArrowLength: d.linkArrowLength,
valueFormat: d.valueFormat,
valueSuffix: d.valueSuffix,
sankey: d.sankey,
parent: d,
interactionState: d.interactionState,
flow: l.flow
};
}
function createCircularClosedPathString(link, arrowLen) {
// Using coordinates computed by d3-sankey-circular
var pathString = '';
var offset = link.width / 2;
var coords = link.circularPathData;
if (link.circularLinkType === 'top') {
// Top path
pathString =
// start at the left of the target node
'M ' + (coords.targetX - arrowLen) + ' ' + (coords.targetY + offset) + ' ' + 'L' + (coords.rightInnerExtent - arrowLen) + ' ' + (coords.targetY + offset) + 'A' + (coords.rightLargeArcRadius + offset) + ' ' + (coords.rightSmallArcRadius + offset) + ' 0 0 1 ' + (coords.rightFullExtent - offset - arrowLen) + ' ' + (coords.targetY - coords.rightSmallArcRadius) + 'L' + (coords.rightFullExtent - offset - arrowLen) + ' ' + coords.verticalRightInnerExtent + 'A' + (coords.rightLargeArcRadius + offset) + ' ' + (coords.rightLargeArcRadius + offset) + ' 0 0 1 ' + (coords.rightInnerExtent - arrowLen) + ' ' + (coords.verticalFullExtent - offset) + 'L' + coords.leftInnerExtent + ' ' + (coords.verticalFullExtent - offset) + 'A' + (coords.leftLargeArcRadius + offset) + ' ' + (coords.leftLargeArcRadius + offset) + ' 0 0 1 ' + (coords.leftFullExtent + offset) + ' ' + coords.verticalLeftInnerExtent + 'L' + (coords.leftFullExtent + offset) + ' ' + (coords.sourceY - coords.leftSmallArcRadius) + 'A' + (coords.leftLargeArcRadius + offset) + ' ' + (coords.leftSmallArcRadius + offset) + ' 0 0 1 ' + coords.leftInnerExtent + ' ' + (coords.sourceY + offset) + 'L' + coords.sourceX + ' ' + (coords.sourceY + offset) +
// Walking back
'L' + coords.sourceX + ' ' + (coords.sourceY - offset) + 'L' + coords.leftInnerExtent + ' ' + (coords.sourceY - offset) + 'A' + (coords.leftLargeArcRadius - offset) + ' ' + (coords.leftSmallArcRadius - offset) + ' 0 0 0 ' + (coords.leftFullExtent - offset) + ' ' + (coords.sourceY - coords.leftSmallArcRadius) + 'L' + (coords.leftFullExtent - offset) + ' ' + coords.verticalLeftInnerExtent + 'A' + (coords.leftLargeArcRadius - offset) + ' ' + (coords.leftLargeArcRadius - offset) + ' 0 0 0 ' + coords.leftInnerExtent + ' ' + (coords.verticalFullExtent + offset) + 'L' + (coords.rightInnerExtent - arrowLen) + ' ' + (coords.verticalFullExtent + offset) + 'A' + (coords.rightLargeArcRadius - offset) + ' ' + (coords.rightLargeArcRadius - offset) + ' 0 0 0 ' + (coords.rightFullExtent + offset - arrowLen) + ' ' + coords.verticalRightInnerExtent + 'L' + (coords.rightFullExtent + offset - arrowLen) + ' ' + (coords.targetY - coords.rightSmallArcRadius) + 'A' + (coords.rightLargeArcRadius - offset) + ' ' + (coords.rightSmallArcRadius - offset) + ' 0 0 0 ' + (coords.rightInnerExtent - arrowLen) + ' ' + (coords.targetY - offset) + 'L' + (coords.targetX - arrowLen) + ' ' + (coords.targetY - offset) + (arrowLen > 0 ? 'L' + coords.targetX + ' ' + coords.targetY : '') + 'Z';
} else {
// Bottom path
pathString =
// start at the left of the target node
'M ' + (coords.targetX - arrowLen) + ' ' + (coords.targetY - offset) + ' ' + 'L' + (coords.rightInnerExtent - arrowLen) + ' ' + (coords.targetY - offset) + 'A' + (coords.rightLargeArcRadius + offset) + ' ' + (coords.rightSmallArcRadius + offset) + ' 0 0 0 ' + (coords.rightFullExtent - offset - arrowLen) + ' ' + (coords.targetY + coords.rightSmallArcRadius) + 'L' + (coords.rightFullExtent - offset - arrowLen) + ' ' + coords.verticalRightInnerExtent + 'A' + (coords.rightLargeArcRadius + offset) + ' ' + (coords.rightLargeArcRadius + offset) + ' 0 0 0 ' + (coords.rightInnerExtent - arrowLen) + ' ' + (coords.verticalFullExtent + offset) + 'L' + coords.leftInnerExtent + ' ' + (coords.verticalFullExtent + offset) + 'A' + (coords.leftLargeArcRadius + offset) + ' ' + (coords.leftLargeArcRadius + offset) + ' 0 0 0 ' + (coords.leftFullExtent + offset) + ' ' + coords.verticalLeftInnerExtent + 'L' + (coords.leftFullExtent + offset) + ' ' + (coords.sourceY + coords.leftSmallArcRadius) + 'A' + (coords.leftLargeArcRadius + offset) + ' ' + (coords.leftSmallArcRadius + offset) + ' 0 0 0 ' + coords.leftInnerExtent + ' ' + (coords.sourceY - offset) + 'L' + coords.sourceX + ' ' + (coords.sourceY - offset) +
// Walking back
'L' + coords.sourceX + ' ' + (coords.sourceY + offset) + 'L' + coords.leftInnerExtent + ' ' + (coords.sourceY + offset) + 'A' + (coords.leftLargeArcRadius - offset) + ' ' + (coords.leftSmallArcRadius - offset) + ' 0 0 1 ' + (coords.leftFullExtent - offset) + ' ' + (coords.sourceY + coords.leftSmallArcRadius) + 'L' + (coords.leftFullExtent - offset) + ' ' + coords.verticalLeftInnerExtent + 'A' + (coords.leftLargeArcRadius - offset) + ' ' + (coords.leftLargeArcRadius - offset) + ' 0 0 1 ' + coords.leftInnerExtent + ' ' + (coords.verticalFullExtent - offset) + 'L' + (coords.rightInnerExtent - arrowLen) + ' ' + (coords.verticalFullExtent - offset) + 'A' + (coords.rightLargeArcRadius - offset) + ' ' + (coords.rightLargeArcRadius - offset) + ' 0 0 1 ' + (coords.rightFullExtent + offset - arrowLen) + ' ' + coords.verticalRightInnerExtent + 'L' + (coords.rightFullExtent + offset - arrowLen) + ' ' + (coords.targetY + coords.rightSmallArcRadius) + 'A' + (coords.rightLargeArcRadius - offset) + ' ' + (coords.rightSmallArcRadius - offset) + ' 0 0 1 ' + (coords.rightInnerExtent - arrowLen) + ' ' + (coords.targetY + offset) + 'L' + (coords.targetX - arrowLen) + ' ' + (coords.targetY + offset) + (arrowLen > 0 ? 'L' + coords.targetX + ' ' + coords.targetY : '') + 'Z';
}
return pathString;
}
function linkPath() {
var curvature = 0.5;
function path(d) {
var arrowLen = d.linkArrowLength;
if (d.link.circular) {
return createCircularClosedPathString(d.link, arrowLen);
} else {
var maxArrowLength = Math.abs((d.link.target.x0 - d.link.source.x1) / 2);
if (arrowLen > maxArrowLength) {
arrowLen = maxArrowLength;
}
var x0 = d.link.source.x1;
var x1 = d.link.target.x0 - arrowLen;
var xi = interpolateNumber(x0, x1);
var x2 = xi(curvature);
var x3 = xi(1 - curvature);
var y0a = d.link.y0 - d.link.width / 2;
var y0b = d.link.y0 + d.link.width / 2;
var y1a = d.link.y1 - d.link.width / 2;
var y1b = d.link.y1 + d.link.width / 2;
var start = 'M' + x0 + ',' + y0a;
var upperCurve = 'C' + x2 + ',' + y0a + ' ' + x3 + ',' + y1a + ' ' + x1 + ',' + y1a;
var lowerCurve = 'C' + x3 + ',' + y1b + ' ' + x2 + ',' + y0b + ' ' + x0 + ',' + y0b;
var rightEnd = arrowLen > 0 ? 'L' + (x1 + arrowLen) + ',' + (y1a + d.link.width / 2) : '';
rightEnd += 'L' + x1 + ',' + y1b;
return start + upperCurve + rightEnd + lowerCurve + 'Z';
}
}
return path;
}
function nodeModel(d, n) {
var tc = tinycolor(n.color);
var zoneThicknessPad = c.nodePadAcross;
var zoneLengthPad = d.nodePad / 2;
n.dx = n.x1 - n.x0;
n.dy = n.y1 - n.y0;
var visibleThickness = n.dx;
var visibleLength = Math.max(0.5, n.dy);
var key = 'node_' + n.pointNumber;
// If it's a group, it's mutable and should be unique
if (n.group) {
key = Lib.randstr();
}
// for event data
n.trace = d.trace;
n.curveNumber = d.trace.index;
return {
index: n.pointNumber,
key: key,
partOfGroup: n.partOfGroup || false,
group: n.group,
traceId: d.key,
trace: d.trace,
node: n,
nodePad: d.nodePad,
nodeLineColor: d.nodeLineColor,
nodeLineWidth: d.nodeLineWidth,
textFont: d.textFont,
size: d.horizontal ? d.height : d.width,
visibleWidth: Math.ceil(visibleThickness),
visibleHeight: visibleLength,
zoneX: -zoneThicknessPad,
zoneY: -zoneLengthPad,
zoneWidth: visibleThickness + 2 * zoneThicknessPad,
zoneHeight: visibleLength + 2 * zoneLengthPad,
labelY: d.horizontal ? n.dy / 2 + 1 : n.dx / 2 + 1,
left: n.originalLayer === 1,
sizeAcross: d.width,
forceLayouts: d.forceLayouts,
horizontal: d.horizontal,
darkBackground: tc.getBrightness() <= 128,
tinyColorHue: Color.tinyRGB(tc),
tinyColorAlpha: tc.getAlpha(),
valueFormat: d.valueFormat,
valueSuffix: d.valueSuffix,
sankey: d.sankey,
graph: d.graph,
arrangement: d.arrangement,
uniqueNodeLabelPathId: [d.guid, d.key, key].join('_'),
interactionState: d.interactionState,
figure: d
};
}
// rendering snippets
function updateNodePositions(sankeyNode) {
sankeyNode.attr('transform', function (d) {
return strTranslate(d.node.x0.toFixed(3), d.node.y0.toFixed(3));
});
}
function updateNodeShapes(sankeyNode) {
sankeyNode.call(updateNodePositions);
}
function updateShapes(sankeyNode, sankeyLink) {
sankeyNode.call(updateNodeShapes);
sankeyLink.attr('d', linkPath());
}
function sizeNode(rect) {
rect.attr('width', function (d) {
return d.node.x1 - d.node.x0;
}).attr('height', function (d) {
return d.visibleHeight;
});
}
function salientEnough(d) {
return d.link.width > 1 || d.linkLineWidth > 0;
}
function sankeyTransform(d) {
var offset = strTranslate(d.translateX, d.translateY);
return offset + (d.horizontal ? 'matrix(1 0 0 1 0 0)' : 'matrix(0 1 1 0 0 0)');
}
// event handling
function attachPointerEvents(selection, sankey, eventSet) {
selection.on('.basic', null) // remove any preexisting handlers
.on('mouseover.basic', function (d) {
if (!d.interactionState.dragInProgress && !d.partOfGroup) {
eventSet.hover(this, d, sankey);
d.interactionState.hovered = [this, d];
}
}).on('mousemove.basic', function (d) {
if (!d.interactionState.dragInProgress && !d.partOfGroup) {
eventSet.follow(this, d);
d.interactionState.hovered = [this, d];
}
}).on('mouseout.basic', function (d) {
if (!d.interactionState.dragInProgress && !d.partOfGroup) {
eventSet.unhover(this, d, sankey);
d.interactionState.hovered = false;
}
}).on('click.basic', function (d) {
if (d.interactionState.hovered) {
eventSet.unhover(this, d, sankey);
d.interactionState.hovered = false;
}
if (!d.interactionState.dragInProgress && !d.partOfGroup) {
eventSet.select(this, d, sankey);
}
});
}
function attachDragHandler(sankeyNode, sankeyLink, callbacks, gd) {
var dragBehavior = d3.behavior.drag().origin(function (d) {
return {
x: d.node.x0 + d.visibleWidth / 2,
y: d.node.y0 + d.visibleHeight / 2
};
}).on('dragstart', function (d) {
if (d.arrangement === 'fixed') return;
Lib.ensureSingle(gd._fullLayout._infolayer, 'g', 'dragcover', function (s) {
gd._fullLayout._dragCover = s;
});
Lib.raiseToTop(this);
d.interactionState.dragInProgress = d.node;
saveCurrentDragPosition(d.node);
if (d.interactionState.hovered) {
callbacks.nodeEvents.unhover.apply(0, d.interactionState.hovered);
d.interactionState.hovered = false;
}
if (d.arrangement === 'snap') {
var forceKey = d.traceId + '|' + d.key;
if (d.forceLayouts[forceKey]) {
d.forceLayouts[forceKey].alpha(1);
} else {
// make a forceLayout if needed
attachForce(sankeyNode, forceKey, d, gd);
}
startForce(sankeyNode, sankeyLink, d, forceKey, gd);
}
}).on('drag', function (d) {
if (d.arrangement === 'fixed') return;
var x = d3.event.x;
var y = d3.event.y;
if (d.arrangement === 'snap') {
d.node.x0 = x - d.visibleWidth / 2;
d.node.x1 = x + d.visibleWidth / 2;
d.node.y0 = y - d.visibleHeight / 2;
d.node.y1 = y + d.visibleHeight / 2;
} else {
if (d.arrangement === 'freeform') {
d.node.x0 = x - d.visibleWidth / 2;
d.node.x1 = x + d.visibleWidth / 2;
}
y = Math.max(0, Math.min(d.size - d.visibleHeight / 2, y));
d.node.y0 = y - d.visibleHeight / 2;
d.node.y1 = y + d.visibleHeight / 2;
}
saveCurrentDragPosition(d.node);
if (d.arrangement !== 'snap') {
d.sankey.update(d.graph);
updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
}
}).on('dragend', function (d) {
if (d.arrangement === 'fixed') return;
d.interactionState.dragInProgress = false;
for (var i = 0; i < d.node.childrenNodes.length; i++) {
d.node.childrenNodes[i].x = d.node.x;
d.node.childrenNodes[i].y = d.node.y;
}
if (d.arrangement !== 'snap') persistFinalNodePositions(d, gd);
});
sankeyNode.on('.drag', null) // remove possible previous handlers
.call(dragBehavior);
}
function attachForce(sankeyNode, forceKey, d, gd) {
// Attach force to nodes in the same column (same x coordinate)
switchToForceFormat(d.graph.nodes);
var nodes = d.graph.nodes.filter(function (n) {
return n.originalX === d.node.originalX;
})
// Filter out children
.filter(function (n) {
return !n.partOfGroup;
});
d.forceLayouts[forceKey] = d3Force.forceSimulation(nodes).alphaDecay(0).force('collide', d3Force.forceCollide().radius(function (n) {
return n.dy / 2 + d.nodePad / 2;
}).strength(1).iterations(c.forceIterations)).force('constrain', snappingForce(sankeyNode, forceKey, nodes, d, gd)).stop();
}
function startForce(sankeyNode, sankeyLink, d, forceKey, gd) {
window.requestAnimationFrame(function faster() {
var i;
for (i = 0; i < c.forceTicksPerFrame; i++) {
d.forceLayouts[forceKey].tick();
}
var nodes = d.graph.nodes;
switchToSankeyFormat(nodes);
d.sankey.update(d.graph);
updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
if (d.forceLayouts[forceKey].alpha() > 0) {
window.requestAnimationFrame(faster);
} else {
// Make sure the final x position is equal to its original value
// because the force simulation will have numerical error
var x = d.node.originalX;
d.node.x0 = x - d.visibleWidth / 2;
d.node.x1 = x + d.visibleWidth / 2;
persistFinalNodePositions(d, gd);
}
});
}
function snappingForce(sankeyNode, forceKey, nodes, d) {
return function _snappingForce() {
var maxVelocity = 0;
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if (n === d.interactionState.dragInProgress) {
// constrain node position to the dragging pointer
n.x = n.lastDraggedX;
n.y = n.lastDraggedY;
} else {
n.vx = (n.originalX - n.x) / c.forceTicksPerFrame; // snap to layer
n.y = Math.min(d.size - n.dy / 2, Math.max(n.dy / 2, n.y)); // constrain to extent
}
maxVelocity = Math.max(maxVelocity, Math.abs(n.vx), Math.abs(n.vy));
}
if (!d.interactionState.dragInProgress && maxVelocity < 0.1 && d.forceLayouts[forceKey].alpha() > 0) {
d.forceLayouts[forceKey].alpha(0); // This will stop the animation loop
}
};
}
// basic data utilities
function persistFinalNodePositions(d, gd) {
var x = [];
var y = [];
for (var i = 0; i < d.graph.nodes.length; i++) {
var nodeX = (d.graph.nodes[i].x0 + d.graph.nodes[i].x1) / 2;
var nodeY = (d.graph.nodes[i].y0 + d.graph.nodes[i].y1) / 2;
x.push(nodeX / d.figure.width);
y.push(nodeY / d.figure.height);
}
Registry.call('_guiRestyle', gd, {
'node.x': [x],
'node.y': [y]
}, d.trace.index).then(function () {
if (gd._fullLayout._dragCover) gd._fullLayout._dragCover.remove();
});
}
function persistOriginalPlace(nodes) {
var distinctLayerPositions = [];
var i;
for (i = 0; i < nodes.length; i++) {
nodes[i].originalX = (nodes[i].x0 + nodes[i].x1) / 2;
nodes[i].originalY = (nodes[i].y0 + nodes[i].y1) / 2;
if (distinctLayerPositions.indexOf(nodes[i].originalX) === -1) {
distinctLayerPositions.push(nodes[i].originalX);
}
}
distinctLayerPositions.sort(function (a, b) {
return a - b;
});
for (i = 0; i < nodes.length; i++) {
nodes[i].originalLayerIndex = distinctLayerPositions.indexOf(nodes[i].originalX);
nodes[i].originalLayer = nodes[i].originalLayerIndex / (distinctLayerPositions.length - 1);
}
}
function saveCurrentDragPosition(d) {
d.lastDraggedX = d.x0 + d.dx / 2;
d.lastDraggedY = d.y0 + d.dy / 2;
}
function sameLayer(d) {
return function (n) {
return n.node.originalX === d.node.originalX;
};
}
function switchToForceFormat(nodes) {
// force uses x, y as centers
for (var i = 0; i < nodes.length; i++) {
nodes[i].y = (nodes[i].y0 + nodes[i].y1) / 2;
nodes[i].x = (nodes[i].x0 + nodes[i].x1) / 2;
}
}
function switchToSankeyFormat(nodes) {
// sankey uses x0, x1, y0, y1
for (var i = 0; i < nodes.length; i++) {
nodes[i].y0 = nodes[i].y - nodes[i].dy / 2;
nodes[i].y1 = nodes[i].y0 + nodes[i].dy;
nodes[i].x0 = nodes[i].x - nodes[i].dx / 2;
nodes[i].x1 = nodes[i].x0 + nodes[i].dx;
}
}
// scene graph
module.exports = function (gd, svg, calcData, layout, callbacks) {
var isStatic = gd._context.staticPlot;
// To prevent animation on first render
var firstRender = false;
Lib.ensureSingle(gd._fullLayout._infolayer, 'g', 'first-render', function () {
firstRender = true;
});
// To prevent animation on dragging
var dragcover = gd._fullLayout._dragCover;
var styledData = calcData.filter(function (d) {
return unwrap(d).trace.visible;
}).map(sankeyModel.bind(null, layout));
var sankey = svg.selectAll('.' + c.cn.sankey).data(styledData, keyFun);
sankey.exit().remove();
sankey.enter().append('g').classed(c.cn.sankey, true).style('box-sizing', 'content-box').style('position', 'absolute').style('left', 0).style('shape-rendering', 'geometricPrecision').style('pointer-events', isStatic ? 'none' : 'auto').attr('transform', sankeyTransform);
sankey.each(function (d, i) {
gd._fullData[i]._sankey = d;
// Create dragbox if missing
var dragboxClassName = 'bgsankey-' + d.trace.uid + '-' + i;
Lib.ensureSingle(gd._fullLayout._draggers, 'rect', dragboxClassName);
gd._fullData[i]._bgRect = d3.select('.' + dragboxClassName);
// Style dragbox
gd._fullData[i]._bgRect.style('pointer-events', isStatic ? 'none' : 'all').attr('width', d.width).attr('height', d.height).attr('x', d.translateX).attr('y', d.translateY).classed('bgsankey', true).style({
fill: 'transparent',
'stroke-width': 0
});
});
sankey.transition().ease(c.ease).duration(c.duration).attr('transform', sankeyTransform);
var sankeyLinks = sankey.selectAll('.' + c.cn.sankeyLinks).data(repeat, keyFun);
sankeyLinks.enter().append('g').classed(c.cn.sankeyLinks, true).style('fill', 'none');
var sankeyLink = sankeyLinks.selectAll('.' + c.cn.sankeyLink).data(function (d) {
var links = d.graph.links;
return links.filter(function (l) {
return l.value;
}).map(linkModel.bind(null, d));
}, keyFun);
sankeyLink.enter().append('path').classed(c.cn.sankeyLink, true).call(attachPointerEvents, sankey, callbacks.linkEvents);
sankeyLink.style('stroke', function (d) {
return salientEnough(d) ? Color.tinyRGB(tinycolor(d.linkLineColor)) : d.tinyColorHue;
}).style('stroke-opacity', function (d) {
return salientEnough(d) ? Color.opacity(d.linkLineColor) : d.tinyColorAlpha;
}).style('fill', function (d) {
return d.tinyColorHue;
}).style('fill-opacity', function (d) {
return d.tinyColorAlpha;
}).style('stroke-width', function (d) {
return salientEnough(d) ? d.linkLineWidth : 1;
}).attr('d', linkPath());
sankeyLink.style('opacity', function () {
return gd._context.staticPlot || firstRender || dragcover ? 1 : 0;
}).transition().ease(c.ease).duration(c.duration).style('opacity', 1);
sankeyLink.exit().transition().ease(c.ease).duration(c.duration).style('opacity', 0).remove();
var sankeyNodeSet = sankey.selectAll('.' + c.cn.sankeyNodeSet).data(repeat, keyFun);
sankeyNodeSet.enter().append('g').classed(c.cn.sankeyNodeSet, true);
sankeyNodeSet.style('cursor', function (d) {
switch (d.arrangement) {
case 'fixed':
return 'default';
case 'perpendicular':
return 'ns-resize';
default:
return 'move';
}
});
var sankeyNode = sankeyNodeSet.selectAll('.' + c.cn.sankeyNode).data(function (d) {
var nodes = d.graph.nodes;
persistOriginalPlace(nodes);
return nodes.map(nodeModel.bind(null, d));
}, keyFun);
sankeyNode.enter().append('g').classed(c.cn.sankeyNode, true).call(updateNodePositions).style('opacity', function (n) {
return (gd._context.staticPlot || firstRender) && !n.partOfGroup ? 1 : 0;
});
sankeyNode.call(attachPointerEvents, sankey, callbacks.nodeEvents).call(attachDragHandler, sankeyLink, callbacks, gd); // has to be here as it binds sankeyLink
sankeyNode.transition().ease(c.ease).duration(c.duration).call(updateNodePositions).style('opacity', function (n) {
return n.partOfGroup ? 0 : 1;
});
sankeyNode.exit().transition().ease(c.ease).duration(c.duration).style('opacity', 0).remove();
var nodeRect = sankeyNode.selectAll('.' + c.cn.nodeRect).data(repeat);
nodeRect.enter().append('rect').classed(c.cn.nodeRect, true).call(sizeNode);
nodeRect.style('stroke-width', function (d) {
return d.nodeLineWidth;
}).style('stroke', function (d) {
return Color.tinyRGB(tinycolor(d.nodeLineColor));
}).style('stroke-opacity', function (d) {
return Color.opacity(d.nodeLineColor);
}).style('fill', function (d) {
return d.tinyColorHue;
}).style('fill-opacity', function (d) {
return d.tinyColorAlpha;
});
nodeRect.transition().ease(c.ease).duration(c.duration).call(sizeNode);
var nodeLabel = sankeyNode.selectAll('.' + c.cn.nodeLabel).data(repeat);
nodeLabel.enter().append('text').classed(c.cn.nodeLabel, true).style('cursor', 'default');
nodeLabel.attr('data-notex', 1) // prohibit tex interpretation until we can handle tex and regular text together
.text(function (d) {
return d.node.label;
}).each(function (d) {
var e = d3.select(this);
Drawing.font(e, d.textFont);
svgTextUtils.convertToTspans(e, gd);
}).attr('text-anchor', function (d) {
return d.horizontal && d.left ? 'end' : 'start';
}).attr('transform', function (d) {
var e = d3.select(this);
// how much to shift a multi-line label to center it vertically.
var nLines = svgTextUtils.lineCount(e);
var blockHeight = d.textFont.size * ((nLines - 1) * LINE_SPACING - CAP_SHIFT);
var posX = d.nodeLineWidth / 2 + TEXTPAD;
var posY = ((d.horizontal ? d.visibleHeight : d.visibleWidth) - blockHeight) / 2;
if (d.horizontal) {
if (d.left) {
posX = -posX;
} else {
posX += d.visibleWidth;
}
}
var flipText = d.horizontal ? '' : 'scale(-1,1)' + strRotate(90);
return strTranslate(d.horizontal ? posX : posY, d.horizontal ? posY : posX) + flipText;
});
nodeLabel.transition().ease(c.ease).duration(c.duration);
};
/***/ }),
/***/ 81128:
/***/ (function(module) {
"use strict";
module.exports = function selectPoints(searchInfo, selectionTester) {
var cd = searchInfo.cd;
var selection = [];
var fullData = cd[0].trace;
var nodes = fullData._sankey.graph.nodes;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.partOfGroup) continue; // Those are invisible
// Position of node's centroid
var pos = [(node.x0 + node.x1) / 2, (node.y0 + node.y1) / 2];
// Swap x and y if trace is vertical
if (fullData.orientation === 'v') pos.reverse();
if (selectionTester && selectionTester.contains(pos, false, i, searchInfo)) {
selection.push({
pointNumber: node.pointNumber
// TODO: add eventData
});
}
}
return selection;
};
/***/ }),
/***/ 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');
Lib.mergeArray(trace.textfont.weight, cd, 'tw');
Lib.mergeArray(trace.textfont.style, cd, 'ty');
Lib.mergeArray(trace.textfont.variant, cd, 'tv');
Lib.mergeArray(trace.textfont.textcase, cd, 'tC');
Lib.mergeArray(trace.textfont.lineposition, cd, 'tE');
Lib.mergeArray(trace.textfont.shadow, cd, 'tS');
}
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, opts);
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;
};
/***/ }),
/***/ 91592:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterAttrs = __webpack_require__(52904);
var fontAttrs = __webpack_require__(25376);
var colorAttributes = __webpack_require__(49084);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var baseAttrs = __webpack_require__(45464);
var DASHES = __webpack_require__(99168);
var MARKER_SYMBOLS = __webpack_require__(87792);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var sortObjectKeys = __webpack_require__(95376);
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
var lineAttrs = extendFlat({
width: scatterLineAttrs.width,
dash: {
valType: 'enumerated',
values: sortObjectKeys(DASHES),
dflt: 'solid'
}
}, colorAttributes('line'));
function makeProjectionAttr(axLetter) {
return {
show: {
valType: 'boolean',
dflt: false
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1
},
scale: {
valType: 'number',
min: 0,
max: 10,
dflt: 2 / 3
}
};
}
var attrs = module.exports = overrideAll({
x: scatterAttrs.x,
y: scatterAttrs.y,
z: {
valType: 'data_array'
},
text: extendFlat({}, scatterAttrs.text, {}),
texttemplate: texttemplateAttrs({}, {}),
hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
hovertemplate: hovertemplateAttrs(),
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z'),
mode: extendFlat({}, scatterAttrs.mode,
// shouldn't this be on-par with 2D?
{
dflt: 'lines+markers'
}),
surfaceaxis: {
valType: 'enumerated',
values: [-1, 0, 1, 2],
dflt: -1
},
surfacecolor: {
valType: 'color'
},
projection: {
x: makeProjectionAttr('x'),
y: makeProjectionAttr('y'),
z: makeProjectionAttr('z')
},
connectgaps: scatterAttrs.connectgaps,
line: lineAttrs,
marker: extendFlat({
// Parity with scatter.js?
symbol: {
valType: 'enumerated',
values: sortObjectKeys(MARKER_SYMBOLS),
dflt: 'circle',
arrayOk: true
},
size: extendFlat({}, scatterMarkerAttrs.size, {
dflt: 8
}),
sizeref: scatterMarkerAttrs.sizeref,
sizemin: scatterMarkerAttrs.sizemin,
sizemode: scatterMarkerAttrs.sizemode,
opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
arrayOk: false
}),
colorbar: scatterMarkerAttrs.colorbar,
line: extendFlat({
width: extendFlat({}, scatterMarkerLineAttrs.width, {
arrayOk: false
})
}, colorAttributes('marker.line'))
}, colorAttributes('marker')),
textposition: extendFlat({}, scatterAttrs.textposition, {
dflt: 'top center'
}),
textfont: fontAttrs({
noFontShadow: true,
noFontLineposition: true,
noFontTextcase: true,
editType: 'calc',
colorEditType: 'style',
arrayOk: true,
variantValues: ['normal', 'small-caps']
}),
opacity: baseAttrs.opacity,
hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
}, 'calc', 'nested');
attrs.x.editType = attrs.y.editType = attrs.z.editType = 'calc+clearAxisTypes';
/***/ }),
/***/ 41484:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var arraysToCalcdata = __webpack_require__(20148);
var calcColorscale = __webpack_require__(90136);
/**
* This is a kludge to put the array attributes into
* calcdata the way Scatter.plot does, so that legends and
* popovers know what to do with them.
*/
module.exports = function calc(gd, trace) {
var cd = [{
x: false,
y: false,
trace: trace,
t: {}
}];
arraysToCalcdata(cd, trace);
calcColorscale(gd, trace);
return cd;
};
/***/ }),
/***/ 45156:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
function calculateAxisErrors(data, params, scaleFactor, axis) {
if (!params || !params.visible) return null;
var computeError = Registry.getComponentMethod('errorbars', 'makeComputeError')(params);
var result = new Array(data.length);
for (var i = 0; i < data.length; i++) {
var errors = computeError(+data[i], i);
if (axis.type === 'log') {
var point = axis.c2l(data[i]);
var min = data[i] - errors[0];
var max = data[i] + errors[1];
result[i] = [(axis.c2l(min, true) - point) * scaleFactor, (axis.c2l(max, true) - point) * scaleFactor];
// Keep track of the lower error bound which isn't negative!
if (min > 0) {
var lower = axis.c2l(min);
if (!axis._lowerLogErrorBound) axis._lowerLogErrorBound = lower;
axis._lowerErrorBound = Math.min(axis._lowerLogErrorBound, lower);
}
} else {
result[i] = [-errors[0] * scaleFactor, errors[1] * scaleFactor];
}
}
return result;
}
function dataLength(array) {
for (var i = 0; i < array.length; i++) {
if (array[i]) return array[i].length;
}
return 0;
}
function calculateErrors(data, scaleFactor, sceneLayout) {
var errors = [calculateAxisErrors(data.x, data.error_x, scaleFactor[0], sceneLayout.xaxis), calculateAxisErrors(data.y, data.error_y, scaleFactor[1], sceneLayout.yaxis), calculateAxisErrors(data.z, data.error_z, scaleFactor[2], sceneLayout.zaxis)];
var n = dataLength(errors);
if (n === 0) return null;
var errorBounds = new Array(n);
for (var i = 0; i < n; i++) {
var bound = [[0, 0, 0], [0, 0, 0]];
for (var j = 0; j < 3; j++) {
if (errors[j]) {
for (var k = 0; k < 2; k++) {
bound[k][j] = errors[j][i][k];
}
}
}
errorBounds[i] = bound;
}
return errorBounds;
}
module.exports = calculateErrors;
/***/ }),
/***/ 41064:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createLinePlot = (__webpack_require__(67792).gl_line3d);
var createScatterPlot = (__webpack_require__(67792).gl_scatter3d);
var createErrorBars = (__webpack_require__(67792).gl_error3d);
var createMesh = (__webpack_require__(67792).gl_mesh3d);
var triangulate = (__webpack_require__(67792).delaunay_triangulate);
var Lib = __webpack_require__(3400);
var str2RgbaArray = __webpack_require__(43080);
var formatColor = (__webpack_require__(33040).formatColor);
var makeBubbleSizeFn = __webpack_require__(7152);
var DASH_PATTERNS = __webpack_require__(99168);
var MARKER_SYMBOLS = __webpack_require__(87792);
var Axes = __webpack_require__(54460);
var appendArrayPointValue = (__webpack_require__(10624).appendArrayPointValue);
var calculateError = __webpack_require__(45156);
function LineWithMarkers(scene, uid) {
this.scene = scene;
this.uid = uid;
this.linePlot = null;
this.scatterPlot = null;
this.errorBars = null;
this.textMarkers = null;
this.delaunayMesh = null;
this.color = null;
this.mode = '';
this.dataPoints = [];
this.axesBounds = [[-Infinity, -Infinity, -Infinity], [Infinity, Infinity, Infinity]];
this.textLabels = null;
this.data = null;
}
var proto = LineWithMarkers.prototype;
proto.handlePick = function (selection) {
if (selection.object && (selection.object === this.linePlot || selection.object === this.delaunayMesh || selection.object === this.textMarkers || selection.object === this.scatterPlot)) {
var ind = selection.index = selection.data.index;
if (selection.object.highlight) {
selection.object.highlight(null);
}
if (this.scatterPlot) {
selection.object = this.scatterPlot;
this.scatterPlot.highlight(selection.data);
}
selection.textLabel = '';
if (this.textLabels) {
if (Lib.isArrayOrTypedArray(this.textLabels)) {
if (this.textLabels[ind] || this.textLabels[ind] === 0) {
selection.textLabel = this.textLabels[ind];
}
} else {
selection.textLabel = this.textLabels;
}
}
selection.traceCoordinate = [this.data.x[ind], this.data.y[ind], this.data.z[ind]];
return true;
}
};
function constructDelaunay(points, color, axis) {
var u = (axis + 1) % 3;
var v = (axis + 2) % 3;
var filteredPoints = [];
var filteredIds = [];
var i;
for (i = 0; i < points.length; ++i) {
var p = points[i];
if (isNaN(p[u]) || !isFinite(p[u]) || isNaN(p[v]) || !isFinite(p[v])) {
continue;
}
filteredPoints.push([p[u], p[v]]);
filteredIds.push(i);
}
var cells = triangulate(filteredPoints);
for (i = 0; i < cells.length; ++i) {
var c = cells[i];
for (var j = 0; j < c.length; ++j) {
c[j] = filteredIds[c[j]];
}
}
return {
positions: points,
cells: cells,
meshColor: color
};
}
function calculateErrorParams(errors) {
var capSize = [0.0, 0.0, 0.0];
var color = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
var lineWidth = [1.0, 1.0, 1.0];
for (var i = 0; i < 3; i++) {
var e = errors[i];
if (e && e.copy_zstyle !== false && errors[2].visible !== false) e = errors[2];
if (!e || !e.visible) continue;
capSize[i] = e.width / 2; // ballpark rescaling
color[i] = str2RgbaArray(e.color);
lineWidth[i] = e.thickness;
}
return {
capSize: capSize,
color: color,
lineWidth: lineWidth
};
}
function parseAlignmentX(a) {
if (a === null || a === undefined) return 0;
return a.indexOf('left') > -1 ? -1 : a.indexOf('right') > -1 ? 1 : 0;
}
function parseAlignmentY(a) {
if (a === null || a === undefined) return 0;
return a.indexOf('top') > -1 ? -1 : a.indexOf('bottom') > -1 ? 1 : 0;
}
function calculateTextOffset(tp) {
// Read out text properties
var defaultAlignmentX = 0;
var defaultAlignmentY = 0;
var textOffset = [defaultAlignmentX, defaultAlignmentY];
if (Array.isArray(tp)) {
for (var i = 0; i < tp.length; i++) {
textOffset[i] = [defaultAlignmentX, defaultAlignmentY];
if (tp[i]) {
textOffset[i][0] = parseAlignmentX(tp[i]);
textOffset[i][1] = parseAlignmentY(tp[i]);
}
}
} else {
textOffset[0] = parseAlignmentX(tp);
textOffset[1] = parseAlignmentY(tp);
}
return textOffset;
}
function calculateSize(sizeIn, sizeFn) {
// rough parity with Plotly 2D markers
return sizeFn(sizeIn * 4);
}
function calculateSymbol(symbolIn) {
return MARKER_SYMBOLS[symbolIn];
}
function formatParam(paramIn, len, calculate, dflt, extraFn) {
var paramOut = null;
if (Lib.isArrayOrTypedArray(paramIn)) {
paramOut = [];
for (var i = 0; i < len; i++) {
if (paramIn[i] === undefined) paramOut[i] = dflt;else paramOut[i] = calculate(paramIn[i], extraFn);
}
} else paramOut = calculate(paramIn, Lib.identity);
return paramOut;
}
function convertPlotlyOptions(scene, data) {
var points = [];
var sceneLayout = scene.fullSceneLayout;
var scaleFactor = scene.dataScale;
var xaxis = sceneLayout.xaxis;
var yaxis = sceneLayout.yaxis;
var zaxis = sceneLayout.zaxis;
var marker = data.marker;
var line = data.line;
var x = data.x || [];
var y = data.y || [];
var z = data.z || [];
var len = x.length;
var xcalendar = data.xcalendar;
var ycalendar = data.ycalendar;
var zcalendar = data.zcalendar;
var xc, yc, zc;
var params, i;
var text;
// Convert points
for (i = 0; i < len; i++) {
// sanitize numbers and apply transforms based on axes.type
xc = xaxis.d2l(x[i], 0, xcalendar) * scaleFactor[0];
yc = yaxis.d2l(y[i], 0, ycalendar) * scaleFactor[1];
zc = zaxis.d2l(z[i], 0, zcalendar) * scaleFactor[2];
points[i] = [xc, yc, zc];
}
// convert text
if (Array.isArray(data.text)) {
text = data.text;
} else if (Lib.isTypedArray(data.text)) {
text = Array.from(data.text);
} else if (data.text !== undefined) {
text = new Array(len);
for (i = 0; i < len; i++) text[i] = data.text;
}
function formatter(axName, val) {
var ax = sceneLayout[axName];
return Axes.tickText(ax, ax.d2l(val), true).text;
}
// check texttemplate
var texttemplate = data.texttemplate;
if (texttemplate) {
var fullLayout = scene.fullLayout;
var d3locale = fullLayout._d3locale;
var isArray = Array.isArray(texttemplate);
var N = isArray ? Math.min(texttemplate.length, len) : len;
var txt = isArray ? function (i) {
return texttemplate[i];
} : function () {
return texttemplate;
};
text = new Array(N);
for (i = 0; i < N; i++) {
var d = {
x: x[i],
y: y[i],
z: z[i]
};
var labels = {
xLabel: formatter('xaxis', x[i]),
yLabel: formatter('yaxis', y[i]),
zLabel: formatter('zaxis', z[i])
};
var pointValues = {};
appendArrayPointValue(pointValues, data, i);
var meta = data._meta || {};
text[i] = Lib.texttemplateString(txt(i), labels, d3locale, pointValues, d, meta);
}
}
// Build object parameters
params = {
position: points,
mode: data.mode,
text: text
};
if ('line' in data) {
params.lineColor = formatColor(line, 1, len);
params.lineWidth = line.width;
params.lineDashes = line.dash;
}
if ('marker' in data) {
var sizeFn = makeBubbleSizeFn(data);
params.scatterColor = formatColor(marker, 1, len);
params.scatterSize = formatParam(marker.size, len, calculateSize, 20, sizeFn);
params.scatterMarker = formatParam(marker.symbol, len, calculateSymbol, '●');
params.scatterLineWidth = marker.line.width; // arrayOk === false
params.scatterLineColor = formatColor(marker.line, 1, len);
params.scatterAngle = 0;
}
if ('textposition' in data) {
params.textOffset = calculateTextOffset(data.textposition);
params.textColor = formatColor(data.textfont, 1, len);
params.textSize = formatParam(data.textfont.size, len, Lib.identity, 12);
params.textFontFamily = data.textfont.family;
params.textFontWeight = data.textfont.weight;
params.textFontStyle = data.textfont.style;
params.textFontVariant = data.textfont.variant;
params.textAngle = 0;
}
var dims = ['x', 'y', 'z'];
params.project = [false, false, false];
params.projectScale = [1, 1, 1];
params.projectOpacity = [1, 1, 1];
for (i = 0; i < 3; ++i) {
var projection = data.projection[dims[i]];
if (params.project[i] = projection.show) {
params.projectOpacity[i] = projection.opacity;
params.projectScale[i] = projection.scale;
}
}
params.errorBounds = calculateError(data, scaleFactor, sceneLayout);
var errorParams = calculateErrorParams([data.error_x, data.error_y, data.error_z]);
params.errorColor = errorParams.color;
params.errorLineWidth = errorParams.lineWidth;
params.errorCapSize = errorParams.capSize;
params.delaunayAxis = data.surfaceaxis;
params.delaunayColor = str2RgbaArray(data.surfacecolor);
return params;
}
function _arrayToColor(color) {
if (Lib.isArrayOrTypedArray(color)) {
var c = color[0];
if (Lib.isArrayOrTypedArray(c)) color = c;
return 'rgb(' + color.slice(0, 3).map(function (x) {
return Math.round(x * 255);
}) + ')';
}
return null;
}
function arrayToColor(colors) {
if (!Lib.isArrayOrTypedArray(colors)) {
return null;
}
if (colors.length === 4 && typeof colors[0] === 'number') {
return _arrayToColor(colors);
}
return colors.map(_arrayToColor);
}
proto.update = function (data) {
var gl = this.scene.glplot.gl;
var lineOptions;
var scatterOptions;
var errorOptions;
var textOptions;
var dashPattern = DASH_PATTERNS.solid;
// Save data
this.data = data;
// Run data conversion
var options = convertPlotlyOptions(this.scene, data);
if ('mode' in options) {
this.mode = options.mode;
}
if ('lineDashes' in options) {
if (options.lineDashes in DASH_PATTERNS) {
dashPattern = DASH_PATTERNS[options.lineDashes];
}
}
this.color = arrayToColor(options.scatterColor) || arrayToColor(options.lineColor);
// Save data points
this.dataPoints = options.position;
lineOptions = {
gl: this.scene.glplot.gl,
position: options.position,
color: options.lineColor,
lineWidth: options.lineWidth || 1,
dashes: dashPattern[0],
dashScale: dashPattern[1],
opacity: data.opacity,
connectGaps: data.connectgaps
};
if (this.mode.indexOf('lines') !== -1) {
if (this.linePlot) this.linePlot.update(lineOptions);else {
this.linePlot = createLinePlot(lineOptions);
this.linePlot._trace = this;
this.scene.glplot.add(this.linePlot);
}
} else if (this.linePlot) {
this.scene.glplot.remove(this.linePlot);
this.linePlot.dispose();
this.linePlot = null;
}
// N.B. marker.opacity must be a scalar for performance
var scatterOpacity = data.opacity;
if (data.marker && data.marker.opacity !== undefined) scatterOpacity *= data.marker.opacity;
scatterOptions = {
gl: this.scene.glplot.gl,
position: options.position,
color: options.scatterColor,
size: options.scatterSize,
glyph: options.scatterMarker,
opacity: scatterOpacity,
orthographic: true,
lineWidth: options.scatterLineWidth,
lineColor: options.scatterLineColor,
project: options.project,
projectScale: options.projectScale,
projectOpacity: options.projectOpacity
};
if (this.mode.indexOf('markers') !== -1) {
if (this.scatterPlot) this.scatterPlot.update(scatterOptions);else {
this.scatterPlot = createScatterPlot(scatterOptions);
this.scatterPlot._trace = this;
this.scatterPlot.highlightScale = 1;
this.scene.glplot.add(this.scatterPlot);
}
} else if (this.scatterPlot) {
this.scene.glplot.remove(this.scatterPlot);
this.scatterPlot.dispose();
this.scatterPlot = null;
}
textOptions = {
gl: this.scene.glplot.gl,
position: options.position,
glyph: options.text,
color: options.textColor,
size: options.textSize,
angle: options.textAngle,
alignment: options.textOffset,
font: options.textFontFamily,
fontWeight: options.textFontWeight,
fontStyle: options.textFontStyle,
fontVariant: options.textFontVariant,
orthographic: true,
lineWidth: 0,
project: false,
opacity: data.opacity
};
this.textLabels = data.hovertext || data.text;
if (this.mode.indexOf('text') !== -1) {
if (this.textMarkers) this.textMarkers.update(textOptions);else {
this.textMarkers = createScatterPlot(textOptions);
this.textMarkers._trace = this;
this.textMarkers.highlightScale = 1;
this.scene.glplot.add(this.textMarkers);
}
} else if (this.textMarkers) {
this.scene.glplot.remove(this.textMarkers);
this.textMarkers.dispose();
this.textMarkers = null;
}
errorOptions = {
gl: this.scene.glplot.gl,
position: options.position,
color: options.errorColor,
error: options.errorBounds,
lineWidth: options.errorLineWidth,
capSize: options.errorCapSize,
opacity: data.opacity
};
if (this.errorBars) {
if (options.errorBounds) {
this.errorBars.update(errorOptions);
} else {
this.scene.glplot.remove(this.errorBars);
this.errorBars.dispose();
this.errorBars = null;
}
} else if (options.errorBounds) {
this.errorBars = createErrorBars(errorOptions);
this.errorBars._trace = this;
this.scene.glplot.add(this.errorBars);
}
if (options.delaunayAxis >= 0) {
var delaunayOptions = constructDelaunay(options.position, options.delaunayColor, options.delaunayAxis);
delaunayOptions.opacity = data.opacity;
if (this.delaunayMesh) {
this.delaunayMesh.update(delaunayOptions);
} else {
delaunayOptions.gl = gl;
this.delaunayMesh = createMesh(delaunayOptions);
this.delaunayMesh._trace = this;
this.scene.glplot.add(this.delaunayMesh);
}
} else if (this.delaunayMesh) {
this.scene.glplot.remove(this.delaunayMesh);
this.delaunayMesh.dispose();
this.delaunayMesh = null;
}
};
proto.dispose = function () {
if (this.linePlot) {
this.scene.glplot.remove(this.linePlot);
this.linePlot.dispose();
}
if (this.scatterPlot) {
this.scene.glplot.remove(this.scatterPlot);
this.scatterPlot.dispose();
}
if (this.errorBars) {
this.scene.glplot.remove(this.errorBars);
this.errorBars.dispose();
}
if (this.textMarkers) {
this.scene.glplot.remove(this.textMarkers);
this.textMarkers.dispose();
}
if (this.delaunayMesh) {
this.scene.glplot.remove(this.delaunayMesh);
this.delaunayMesh.dispose();
}
};
function createLineWithMarkers(scene, data) {
var plot = new LineWithMarkers(scene, data.uid);
plot.update(data);
return plot;
}
module.exports = createLineWithMarkers;
/***/ }),
/***/ 83484:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var subTypes = __webpack_require__(43028);
var handleMarkerDefaults = __webpack_require__(74428);
var handleLineDefaults = __webpack_require__(66828);
var handleTextDefaults = __webpack_require__(124);
var attributes = __webpack_require__(91592);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
if (!len) {
traceOut.visible = false;
return;
}
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
coerce('xhoverformat');
coerce('yhoverformat');
coerce('zhoverformat');
coerce('mode');
if (subTypes.hasMarkers(traceOut)) {
handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
noSelect: true,
noAngle: true
});
}
if (subTypes.hasLines(traceOut)) {
coerce('connectgaps');
handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
}
if (subTypes.hasText(traceOut)) {
coerce('texttemplate');
handleTextDefaults(traceIn, traceOut, layout, coerce, {
noSelect: true,
noFontShadow: true,
noFontLineposition: true,
noFontTextcase: true
});
}
var lineColor = (traceOut.line || {}).color;
var markerColor = (traceOut.marker || {}).color;
if (coerce('surfaceaxis') >= 0) coerce('surfacecolor', lineColor || markerColor);
var dims = ['x', 'y', 'z'];
for (var i = 0; i < 3; ++i) {
var projection = 'projection.' + dims[i];
if (coerce(projection + '.show')) {
coerce(projection + '.opacity');
coerce(projection + '.scale');
}
}
var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {
axis: 'z'
});
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {
axis: 'y',
inherit: 'z'
});
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {
axis: 'x',
inherit: 'z'
});
};
function handleXYZDefaults(traceIn, traceOut, coerce, layout) {
var len = 0;
var x = coerce('x');
var y = coerce('y');
var z = coerce('z');
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);
if (x && y && z) {
// TODO: what happens if one is missing?
len = Math.min(x.length, y.length, z.length);
traceOut._length = traceOut._xlength = traceOut._ylength = traceOut._zlength = len;
}
return len;
}
/***/ }),
/***/ 3296:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
plot: __webpack_require__(41064),
attributes: __webpack_require__(91592),
markerSymbols: __webpack_require__(87792),
supplyDefaults: __webpack_require__(83484),
colorbar: [{
container: 'marker',
min: 'cmin',
max: 'cmax'
}, {
container: 'line',
min: 'cmin',
max: 'cmax'
}],
calc: __webpack_require__(41484),
moduleType: 'trace',
name: 'scatter3d',
basePlotModule: __webpack_require__(12536),
categories: ['gl3d', 'symbols', 'showLegend', 'scatter-like'],
meta: {}
};
/***/ }),
/***/ 90372:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var makeFillcolorAttr = __webpack_require__(98304);
var scatterAttrs = __webpack_require__(52904);
var baseAttrs = __webpack_require__(45464);
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);
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
module.exports = {
carpet: {
valType: 'string',
editType: 'calc'
},
a: {
valType: 'data_array',
editType: 'calc'
},
b: {
valType: 'data_array',
editType: 'calc'
},
mode: extendFlat({}, scatterAttrs.mode, {
dflt: 'markers'
}),
text: extendFlat({}, scatterAttrs.text, {}),
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['a', 'b', 'text']
}),
hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
line: {
color: scatterLineAttrs.color,
width: scatterLineAttrs.width,
dash: scatterLineAttrs.dash,
backoff: scatterLineAttrs.backoff,
shape: extendFlat({}, scatterLineAttrs.shape, {
values: ['linear', 'spline']
}),
smoothing: scatterLineAttrs.smoothing,
editType: 'calc'
},
connectgaps: scatterAttrs.connectgaps,
fill: extendFlat({}, scatterAttrs.fill, {
values: ['none', 'toself', 'tonext'],
dflt: 'none'
}),
fillcolor: makeFillcolorAttr(),
marker: extendFlat({
symbol: scatterMarkerAttrs.symbol,
opacity: scatterMarkerAttrs.opacity,
maxdisplayed: scatterMarkerAttrs.maxdisplayed,
angle: scatterMarkerAttrs.angle,
angleref: scatterMarkerAttrs.angleref,
standoff: scatterMarkerAttrs.standoff,
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', 'text', 'name']
}),
hoveron: scatterAttrs.hoveron,
hovertemplate: hovertemplateAttrs(),
zorder: scatterAttrs.zorder
};
/***/ }),
/***/ 48228:
/***/ (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 lookupCarpet = __webpack_require__(50948);
module.exports = function calc(gd, trace) {
var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
if (!carpet || !carpet.visible || carpet.visible === 'legendonly') return;
var i;
// Transfer this over from carpet before plotting since this is a necessary
// condition in order for cartesian to actually plot this trace:
trace.xaxis = carpet.xaxis;
trace.yaxis = carpet.yaxis;
// make the calcdata array
var serieslen = trace._length;
var cd = new Array(serieslen);
var a, b;
var needsCull = false;
for (i = 0; i < serieslen; i++) {
a = trace.a[i];
b = trace.b[i];
if (isNumeric(a) && isNumeric(b)) {
var xy = carpet.ab2xy(+a, +b, true);
var visible = carpet.isVisible(+a, +b);
if (!visible) needsCull = true;
cd[i] = {
x: xy[0],
y: xy[1],
a: a,
b: b,
vis: visible
};
} else cd[i] = {
x: false,
y: false
};
}
trace._needsCull = needsCull;
cd[0].carpet = carpet;
cd[0].trace = trace;
calcMarkerSize(trace, serieslen);
calcColorscale(gd, trace);
arraysToCalcdata(cd, trace);
calcSelection(cd, trace);
return cd;
};
/***/ }),
/***/ 6176:
/***/ (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__(90372);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
coerce('carpet');
// XXX: Don't hard code this
traceOut.xaxis = 'x';
traceOut.yaxis = 'y';
var a = coerce('a');
var b = coerce('b');
var len = Math.min(a.length, b.length);
if (!len) {
traceOut.visible = false;
return;
}
traceOut._length = len;
coerce('text');
coerce('texttemplate');
coerce('hovertext');
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)) {
handleTextDefaults(traceIn, traceOut, layout, coerce);
}
var dfltHoverOn = [];
if (subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
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');
}
var hoverOn = coerce('hoveron', dfltHoverOn.join('+') || 'points');
if (hoverOn !== 'fills') coerce('hovertemplate');
coerce('zorder');
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
/***/ }),
/***/ 89307:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt, trace, cd, pointNumber) {
var cdi = cd[pointNumber];
out.a = cdi.a;
out.b = cdi.b;
out.y = cdi.y;
return out;
};
/***/ }),
/***/ 52364:
/***/ (function(module) {
"use strict";
module.exports = function formatLabels(cdi, trace) {
var labels = {};
var carpet = trace._carpet;
var ij = carpet.ab2ij([cdi.a, cdi.b]);
var i0 = Math.floor(ij[0]);
var ti = ij[0] - i0;
var j0 = Math.floor(ij[1]);
var tj = ij[1] - j0;
var xy = carpet.evalxy([], i0, j0, ti, tj);
labels.yLabel = xy[1].toFixed(3);
return labels;
};
/***/ }),
/***/ 58960:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterHover = __webpack_require__(98723);
var fillText = (__webpack_require__(3400).fillText);
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];
newPointData.a = cdi.a;
newPointData.b = cdi.b;
newPointData.xLabelVal = undefined;
newPointData.yLabelVal = undefined;
// TODO: nice formatting, and label by axis title, for a, b, and c?
var trace = newPointData.trace;
var carpet = trace._carpet;
var labels = trace._module.formatLabels(cdi, trace);
newPointData.yLabel = labels.yLabel;
delete newPointData.text;
var text = [];
function textPart(ax, val) {
var prefix;
if (ax.labelprefix && ax.labelprefix.length > 0) {
prefix = ax.labelprefix.replace(/ = $/, '');
} else {
prefix = ax._hovertitle;
}
text.push(prefix + ': ' + val.toFixed(3) + ax.labelsuffix);
}
if (!trace.hovertemplate) {
var hoverinfo = cdi.hi || trace.hoverinfo;
var parts = hoverinfo.split('+');
if (parts.indexOf('all') !== -1) parts = ['a', 'b', 'text'];
if (parts.indexOf('a') !== -1) textPart(carpet.aaxis, cdi.a);
if (parts.indexOf('b') !== -1) textPart(carpet.baxis, cdi.b);
text.push('y: ' + newPointData.yLabel);
if (parts.indexOf('text') !== -1) {
fillText(cdi, trace, text);
}
newPointData.extraText = text.join(' ');
}
return scatterPointData;
};
/***/ }),
/***/ 4184:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(90372),
supplyDefaults: __webpack_require__(6176),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(52364),
calc: __webpack_require__(48228),
plot: __webpack_require__(20036),
style: (__webpack_require__(49224).style),
styleOnSelect: (__webpack_require__(49224).styleOnSelect),
hoverPoints: __webpack_require__(58960),
selectPoints: __webpack_require__(91560),
eventData: __webpack_require__(89307),
moduleType: 'trace',
name: 'scattercarpet',
basePlotModule: __webpack_require__(57952),
categories: ['svg', 'carpet', 'symbols', 'showLegend', 'carpetDependent', 'zoomScale'],
meta: {}
};
/***/ }),
/***/ 20036:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterPlot = __webpack_require__(96504);
var Axes = __webpack_require__(54460);
var Drawing = __webpack_require__(43616);
module.exports = function plot(gd, plotinfoproxy, data, layer) {
var i, trace, node;
var carpet = data[0][0].carpet;
var xaxis = Axes.getFromId(gd, carpet.xaxis || 'x');
var yaxis = Axes.getFromId(gd, carpet.yaxis || 'y');
// mimic cartesian plotinfo
var plotinfo = {
xaxis: xaxis,
yaxis: yaxis,
plot: plotinfoproxy.plot
};
for (i = 0; i < data.length; i++) {
trace = data[i][0].trace;
trace._xA = xaxis;
trace._yA = yaxis;
}
scatterPlot(gd, plotinfo, data, layer);
for (i = 0; i < data.length; i++) {
trace = data[i][0].trace;
// Note: .select is adequate but seems to mutate the node data,
// which is at least a bit surprising and causes problems elsewhere
node = layer.selectAll('g.trace' + trace.uid + ' .js-line');
// Note: it would be more efficient if this didn't need to be applied
// separately to all scattercarpet traces, but that would require
// lots of reorganization of scatter traces that is otherwise not
// necessary. That makes this a potential optimization.
Drawing.setClipUrl(node, data[i][0].carpet._clipPathId, gd);
}
};
/***/ }),
/***/ 6096:
/***/ (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 colorAttributes = __webpack_require__(49084);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
module.exports = overrideAll({
lon: {
valType: 'data_array'
},
lat: {
valType: 'data_array'
},
locations: {
valType: 'data_array'
},
locationmode: {
valType: 'enumerated',
values: ['ISO-3', 'USA-states', 'country names', 'geojson-id'],
dflt: 'ISO-3'
},
geojson: {
valType: 'any',
editType: 'calc'
},
featureidkey: {
valType: 'string',
editType: 'calc',
dflt: 'id'
},
mode: extendFlat({}, scatterAttrs.mode, {
dflt: 'markers'
}),
text: extendFlat({}, scatterAttrs.text, {}),
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['lat', 'lon', 'location', 'text']
}),
hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
textfont: scatterAttrs.textfont,
textposition: scatterAttrs.textposition,
line: {
color: scatterLineAttrs.color,
width: scatterLineAttrs.width,
dash: dash
},
connectgaps: scatterAttrs.connectgaps,
marker: extendFlat({
symbol: scatterMarkerAttrs.symbol,
opacity: scatterMarkerAttrs.opacity,
angle: scatterMarkerAttrs.angle,
angleref: extendFlat({}, scatterMarkerAttrs.angleref, {
values: ['previous', 'up', 'north']
}),
standoff: scatterMarkerAttrs.standoff,
size: scatterMarkerAttrs.size,
sizeref: scatterMarkerAttrs.sizeref,
sizemin: scatterMarkerAttrs.sizemin,
sizemode: scatterMarkerAttrs.sizemode,
colorbar: scatterMarkerAttrs.colorbar,
line: extendFlat({
width: scatterMarkerLineAttrs.width
}, colorAttributes('marker.line')),
gradient: scatterMarkerAttrs.gradient
}, colorAttributes('marker')),
fill: {
valType: 'enumerated',
values: ['none', 'toself'],
dflt: 'none'
},
fillcolor: makeFillcolorAttr(),
selected: scatterAttrs.selected,
unselected: scatterAttrs.unselected,
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['lon', 'lat', 'location', 'text', 'name']
}),
hovertemplate: hovertemplateAttrs()
}, 'calc', 'nested');
/***/ }),
/***/ 25212:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var BADNUM = (__webpack_require__(39032).BADNUM);
var calcMarkerColorscale = __webpack_require__(90136);
var arraysToCalcdata = __webpack_require__(20148);
var calcSelection = __webpack_require__(4500);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var _ = (__webpack_require__(3400)._);
function isNonBlankString(v) {
return v && typeof v === 'string';
}
module.exports = function calc(gd, trace) {
var hasLocationData = isArrayOrTypedArray(trace.locations);
var len = hasLocationData ? trace.locations.length : trace._length;
var calcTrace = new Array(len);
var isValidLoc;
if (trace.geojson) {
isValidLoc = function (v) {
return isNonBlankString(v) || isNumeric(v);
};
} else {
isValidLoc = isNonBlankString;
}
for (var i = 0; i < len; i++) {
var calcPt = calcTrace[i] = {};
if (hasLocationData) {
var loc = trace.locations[i];
calcPt.loc = isValidLoc(loc) ? loc : null;
} else {
var lon = trace.lon[i];
var lat = trace.lat[i];
if (isNumeric(lon) && isNumeric(lat)) calcPt.lonlat = [+lon, +lat];else calcPt.lonlat = [BADNUM, BADNUM];
}
}
arraysToCalcdata(calcTrace, trace);
calcMarkerColorscale(gd, trace);
calcSelection(calcTrace, trace);
if (len) {
calcTrace[0].t = {
labels: {
lat: _(gd, 'lat:') + ' ',
lon: _(gd, 'lon:') + ' '
}
};
}
return calcTrace;
};
/***/ }),
/***/ 86188:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var subTypes = __webpack_require__(43028);
var handleMarkerDefaults = __webpack_require__(74428);
var handleLineDefaults = __webpack_require__(66828);
var handleTextDefaults = __webpack_require__(124);
var handleFillColorDefaults = __webpack_require__(70840);
var attributes = __webpack_require__(6096);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var locations = coerce('locations');
var len;
if (locations && locations.length) {
var geojson = coerce('geojson');
var locationmodeDflt;
if (typeof geojson === 'string' && geojson !== '' || Lib.isPlainObject(geojson)) {
locationmodeDflt = 'geojson-id';
}
var locationMode = coerce('locationmode', locationmodeDflt);
if (locationMode === 'geojson-id') {
coerce('featureidkey');
}
len = locations.length;
} else {
var lon = coerce('lon') || [];
var lat = coerce('lat') || [];
len = Math.min(lon.length, lat.length);
}
if (!len) {
traceOut.visible = false;
return;
}
traceOut._length = len;
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
coerce('mode');
if (subTypes.hasMarkers(traceOut)) {
handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
gradient: true
});
}
if (subTypes.hasLines(traceOut)) {
handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
coerce('connectgaps');
}
if (subTypes.hasText(traceOut)) {
coerce('texttemplate');
handleTextDefaults(traceIn, traceOut, layout, coerce);
}
coerce('fill');
if (traceOut.fill !== 'none') {
handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
}
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
/***/ }),
/***/ 58544:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt, trace, cd, pointNumber) {
out.lon = pt.lon;
out.lat = pt.lat;
out.location = pt.loc ? pt.loc : null;
// include feature properties from input geojson
var cdi = cd[pointNumber];
if (cdi.fIn && cdi.fIn.properties) {
out.properties = cdi.fIn.properties;
}
return out;
};
/***/ }),
/***/ 56696:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
module.exports = function formatLabels(cdi, trace, fullLayout) {
var labels = {};
var geo = fullLayout[trace.geo]._subplot;
var ax = geo.mockAxis;
var lonlat = cdi.lonlat;
labels.lonLabel = Axes.tickText(ax, ax.c2l(lonlat[0]), true).text;
labels.latLabel = Axes.tickText(ax, ax.c2l(lonlat[1]), true).text;
return labels;
};
/***/ }),
/***/ 64292:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Fx = __webpack_require__(93024);
var BADNUM = (__webpack_require__(39032).BADNUM);
var getTraceColor = __webpack_require__(44928);
var fillText = (__webpack_require__(3400).fillText);
var attributes = __webpack_require__(6096);
module.exports = function hoverPoints(pointData, xval, yval) {
var cd = pointData.cd;
var trace = cd[0].trace;
var xa = pointData.xa;
var ya = pointData.ya;
var geo = pointData.subplot;
var isLonLatOverEdges = geo.projection.isLonLatOverEdges;
var project = geo.project;
function distFn(d) {
var lonlat = d.lonlat;
if (lonlat[0] === BADNUM) return Infinity;
if (isLonLatOverEdges(lonlat)) return Infinity;
var pt = project(lonlat);
var px = project([xval, yval]);
var dx = Math.abs(pt[0] - px[0]);
var dy = Math.abs(pt[1] - px[1]);
var rad = Math.max(3, d.mrc || 0);
// N.B. d.mrc is the calculated marker radius
// which is only set for trace with 'markers' mode.
return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad);
}
Fx.getClosest(cd, distFn, pointData);
// skip the rest (for this trace) if we didn't find a close point
if (pointData.index === false) return;
var di = cd[pointData.index];
var lonlat = di.lonlat;
var pos = [xa.c2p(lonlat), ya.c2p(lonlat)];
var rad = di.mrc || 1;
pointData.x0 = pos[0] - rad;
pointData.x1 = pos[0] + rad;
pointData.y0 = pos[1] - rad;
pointData.y1 = pos[1] + rad;
pointData.loc = di.loc;
pointData.lon = lonlat[0];
pointData.lat = lonlat[1];
var fullLayout = {};
fullLayout[trace.geo] = {
_subplot: geo
};
var labels = trace._module.formatLabels(di, trace, fullLayout);
pointData.lonLabel = labels.lonLabel;
pointData.latLabel = labels.latLabel;
pointData.color = getTraceColor(trace, di);
pointData.extraText = getExtraText(trace, di, pointData, cd[0].t.labels);
pointData.hovertemplate = trace.hovertemplate;
return [pointData];
};
function getExtraText(trace, pt, pointData, labels) {
if (trace.hovertemplate) return;
var hoverinfo = pt.hi || trace.hoverinfo;
var parts = hoverinfo === 'all' ? attributes.hoverinfo.flags : hoverinfo.split('+');
var hasLocation = parts.indexOf('location') !== -1 && Array.isArray(trace.locations);
var hasLon = parts.indexOf('lon') !== -1;
var hasLat = parts.indexOf('lat') !== -1;
var hasText = parts.indexOf('text') !== -1;
var text = [];
function format(val) {
return val + '\u00B0';
}
if (hasLocation) {
text.push(pt.loc);
} else if (hasLon && hasLat) {
text.push('(' + format(pointData.latLabel) + ', ' + format(pointData.lonLabel) + ')');
} else if (hasLon) {
text.push(labels.lon + format(pointData.lonLabel));
} else if (hasLat) {
text.push(labels.lat + format(pointData.latLabel));
}
if (hasText) {
fillText(pt, trace, text);
}
return text.join(' ');
}
/***/ }),
/***/ 36952:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(6096),
supplyDefaults: __webpack_require__(86188),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(56696),
calc: __webpack_require__(25212),
calcGeoJSON: (__webpack_require__(48691).calcGeoJSON),
plot: (__webpack_require__(48691).plot),
style: __webpack_require__(25064),
styleOnSelect: (__webpack_require__(49224).styleOnSelect),
hoverPoints: __webpack_require__(64292),
eventData: __webpack_require__(58544),
selectPoints: __webpack_require__(8796),
moduleType: 'trace',
name: 'scattergeo',
basePlotModule: __webpack_require__(10816),
categories: ['geo', 'symbols', 'showLegend', 'scatter-like'],
meta: {}
};
/***/ }),
/***/ 48691:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var getTopojsonFeatures = (__webpack_require__(59972).getTopojsonFeatures);
var geoJsonUtils = __webpack_require__(44808);
var geoUtils = __webpack_require__(27144);
var findExtremes = (__webpack_require__(19280).findExtremes);
var BADNUM = (__webpack_require__(39032).BADNUM);
var calcMarkerSize = (__webpack_require__(16356).calcMarkerSize);
var subTypes = __webpack_require__(43028);
var style = __webpack_require__(25064);
function plot(gd, geo, calcData) {
var scatterLayer = geo.layers.frontplot.select('.scatterlayer');
var gTraces = Lib.makeTraceGroups(scatterLayer, calcData, 'trace scattergeo');
function removeBADNUM(d, node) {
if (d.lonlat[0] === BADNUM) {
d3.select(node).remove();
}
}
// TODO find a way to order the inner nodes on update
gTraces.selectAll('*').remove();
gTraces.each(function (calcTrace) {
var s = d3.select(this);
var trace = calcTrace[0].trace;
if (subTypes.hasLines(trace) || trace.fill !== 'none') {
var lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);
var lineData = trace.fill !== 'none' ? geoJsonUtils.makePolygon(lineCoords) : geoJsonUtils.makeLine(lineCoords);
s.selectAll('path.js-line').data([{
geojson: lineData,
trace: trace
}]).enter().append('path').classed('js-line', true).style('stroke-miterlimit', 2);
}
if (subTypes.hasMarkers(trace)) {
s.selectAll('path.point').data(Lib.identity).enter().append('path').classed('point', true).each(function (calcPt) {
removeBADNUM(calcPt, this);
});
}
if (subTypes.hasText(trace)) {
s.selectAll('g').data(Lib.identity).enter().append('g').append('text').each(function (calcPt) {
removeBADNUM(calcPt, this);
});
}
// call style here within topojson request callback
style(gd, calcTrace);
});
}
function calcGeoJSON(calcTrace, fullLayout) {
var trace = calcTrace[0].trace;
var geoLayout = fullLayout[trace.geo];
var geo = geoLayout._subplot;
var len = trace._length;
var i, calcPt;
if (Lib.isArrayOrTypedArray(trace.locations)) {
var locationmode = trace.locationmode;
var features = locationmode === 'geojson-id' ? geoUtils.extractTraceFeature(calcTrace) : getTopojsonFeatures(trace, geo.topojson);
for (i = 0; i < len; i++) {
calcPt = calcTrace[i];
var feature = locationmode === 'geojson-id' ? calcPt.fOut : geoUtils.locationToFeature(locationmode, calcPt.loc, features);
calcPt.lonlat = feature ? feature.properties.ct : [BADNUM, BADNUM];
}
}
var opts = {
padded: true
};
var lonArray;
var latArray;
if (geoLayout.fitbounds === 'geojson' && trace.locationmode === 'geojson-id') {
var bboxGeojson = geoUtils.computeBbox(geoUtils.getTraceGeojson(trace));
lonArray = [bboxGeojson[0], bboxGeojson[2]];
latArray = [bboxGeojson[1], bboxGeojson[3]];
} else {
lonArray = new Array(len);
latArray = new Array(len);
for (i = 0; i < len; i++) {
calcPt = calcTrace[i];
lonArray[i] = calcPt.lonlat[0];
latArray[i] = calcPt.lonlat[1];
}
opts.ppad = calcMarkerSize(trace, len);
}
trace._extremes.lon = findExtremes(geoLayout.lonaxis._ax, lonArray, opts);
trace._extremes.lat = findExtremes(geoLayout.lataxis._ax, latArray, opts);
}
module.exports = {
calcGeoJSON: calcGeoJSON,
plot: plot
};
/***/ }),
/***/ 8796:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var subtypes = __webpack_require__(43028);
var BADNUM = (__webpack_require__(39032).BADNUM);
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 di, lonlat, x, y, i;
var hasOnlyLines = !subtypes.hasMarkers(trace) && !subtypes.hasText(trace);
if (hasOnlyLines) return [];
if (selectionTester === false) {
for (i = 0; i < cd.length; i++) {
cd[i].selected = 0;
}
} else {
for (i = 0; i < cd.length; i++) {
di = cd[i];
lonlat = di.lonlat;
// some projection types can't handle BADNUMs
if (lonlat[0] === BADNUM) continue;
x = xa.c2p(lonlat);
y = ya.c2p(lonlat);
if (selectionTester.contains([x, y], null, i, searchInfo)) {
selection.push({
pointNumber: i,
lon: lonlat[0],
lat: lonlat[1]
});
di.selected = 1;
} else {
di.selected = 0;
}
}
}
return selection;
};
/***/ }),
/***/ 25064:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var scatterStyle = __webpack_require__(49224);
var stylePoints = scatterStyle.stylePoints;
var styleText = scatterStyle.styleText;
module.exports = function style(gd, calcTrace) {
if (calcTrace) styleTrace(gd, calcTrace);
};
function styleTrace(gd, calcTrace) {
var trace = calcTrace[0].trace;
var s = calcTrace[0].node3;
s.style('opacity', calcTrace[0].trace.opacity);
stylePoints(s, trace, gd);
styleText(s, trace, gd);
// this part is incompatible with Drawing.lineGroupStyle
s.selectAll('path.js-line').style('fill', 'none').each(function (d) {
var path = d3.select(this);
var trace = d.trace;
var line = trace.line || {};
path.call(Color.stroke, line.color).call(Drawing.dashLine, line.dash || '', line.width || 0);
if (trace.fill !== 'none') {
path.call(Color.fill, trace.fillcolor);
}
});
}
/***/ }),
/***/ 2876:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var baseAttrs = __webpack_require__(45464);
var fontAttrs = __webpack_require__(25376);
var makeFillcolorAttr = __webpack_require__(98304);
var scatterAttrs = __webpack_require__(52904);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var colorScaleAttrs = __webpack_require__(49084);
var sortObjectKeys = __webpack_require__(95376);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var DASHES = (__webpack_require__(67072).DASHES);
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
var attrs = module.exports = overrideAll({
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,
hovertext: scatterAttrs.hovertext,
textposition: scatterAttrs.textposition,
textfont: fontAttrs({
noFontShadow: true,
noFontLineposition: true,
noFontTextcase: true,
editType: 'calc',
colorEditType: 'style',
arrayOk: true,
noNumericWeightValues: true,
variantValues: ['normal', 'small-caps']
}),
mode: {
valType: 'flaglist',
flags: ['lines', 'markers', 'text'],
extras: ['none']
},
line: {
color: scatterLineAttrs.color,
width: scatterLineAttrs.width,
shape: {
valType: 'enumerated',
values: ['linear', 'hv', 'vh', 'hvh', 'vhv'],
dflt: 'linear',
editType: 'plot'
},
dash: {
valType: 'enumerated',
values: sortObjectKeys(DASHES),
dflt: 'solid'
}
},
marker: extendFlat({}, colorScaleAttrs('marker'), {
symbol: scatterMarkerAttrs.symbol,
angle: scatterMarkerAttrs.angle,
size: scatterMarkerAttrs.size,
sizeref: scatterMarkerAttrs.sizeref,
sizemin: scatterMarkerAttrs.sizemin,
sizemode: scatterMarkerAttrs.sizemode,
opacity: scatterMarkerAttrs.opacity,
colorbar: scatterMarkerAttrs.colorbar,
line: extendFlat({}, colorScaleAttrs('marker.line'), {
width: scatterMarkerLineAttrs.width
})
}),
connectgaps: scatterAttrs.connectgaps,
fill: extendFlat({}, scatterAttrs.fill, {
dflt: 'none'
}),
fillcolor: makeFillcolorAttr(),
// no hoveron
selected: {
marker: scatterAttrs.selected.marker,
textfont: scatterAttrs.selected.textfont
},
unselected: {
marker: scatterAttrs.unselected.marker,
textfont: scatterAttrs.unselected.textfont
},
opacity: baseAttrs.opacity
}, 'calc', 'nested');
attrs.x.editType = attrs.y.editType = attrs.x0.editType = attrs.y0.editType = 'calc+clearAxisTypes';
attrs.hovertemplate = scatterAttrs.hovertemplate;
attrs.texttemplate = scatterAttrs.texttemplate;
/***/ }),
/***/ 64628:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hover = __webpack_require__(41272);
module.exports = {
moduleType: 'trace',
name: 'scattergl',
basePlotModule: __webpack_require__(57952),
categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like'],
attributes: __webpack_require__(2876),
supplyDefaults: __webpack_require__(80220),
crossTraceDefaults: __webpack_require__(35036),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(99396),
calc: __webpack_require__(24856),
hoverPoints: hover.hoverPoints,
selectPoints: __webpack_require__(73224),
meta: {}
};
/***/ }),
/***/ 24856:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var cluster = __webpack_require__(3108);
var Lib = __webpack_require__(3400);
var AxisIDs = __webpack_require__(79811);
var findExtremes = (__webpack_require__(19280).findExtremes);
var alignPeriod = __webpack_require__(1220);
var scatterCalc = __webpack_require__(16356);
var calcMarkerSize = scatterCalc.calcMarkerSize;
var calcAxisExpansion = scatterCalc.calcAxisExpansion;
var setFirstScatter = scatterCalc.setFirstScatter;
var calcColorscale = __webpack_require__(90136);
var convert = __webpack_require__(84236);
var sceneUpdate = __webpack_require__(74588);
var BADNUM = (__webpack_require__(39032).BADNUM);
var TOO_MANY_POINTS = (__webpack_require__(67072).TOO_MANY_POINTS);
module.exports = function calc(gd, trace) {
var fullLayout = gd._fullLayout;
var xa = trace._xA = AxisIDs.getFromId(gd, trace.xaxis, 'x');
var ya = trace._yA = AxisIDs.getFromId(gd, trace.yaxis, 'y');
var subplot = fullLayout._plots[trace.xaxis + trace.yaxis];
var len = trace._length;
var hasTooManyPoints = len >= TOO_MANY_POINTS;
var len2 = len * 2;
var stash = {};
var i;
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;
trace._x = x;
trace._y = y;
if (trace.xperiodalignment) {
trace._origX = origX;
trace._xStarts = xObj.starts;
trace._xEnds = xObj.ends;
}
if (trace.yperiodalignment) {
trace._origY = origY;
trace._yStarts = yObj.starts;
trace._yEnds = yObj.ends;
}
// we need hi-precision for scatter2d,
// regl-scatter2d uses NaNs for bad/missing values
var positions = new Array(len2);
var _ids = new Array(len);
for (i = 0; i < len; i++) {
positions[i * 2] = x[i] === BADNUM ? NaN : x[i];
positions[i * 2 + 1] = y[i] === BADNUM ? NaN : y[i];
// Pre-compute ids.
_ids[i] = i;
}
if (xa.type === 'log') {
for (i = 0; i < len2; i += 2) {
positions[i] = xa.c2l(positions[i]);
}
}
if (ya.type === 'log') {
for (i = 1; i < len2; i += 2) {
positions[i] = ya.c2l(positions[i]);
}
}
// we don't build a tree for log axes since it takes long to convert log2px
// and it is also
if (hasTooManyPoints && xa.type !== 'log' && ya.type !== 'log') {
// FIXME: delegate this to webworker
stash.tree = cluster(positions);
} else {
stash.ids = _ids;
}
// create scene options and scene
calcColorscale(gd, trace);
var opts = sceneOptions(gd, subplot, trace, positions, x, y);
var scene = sceneUpdate(gd, subplot);
// Reuse SVG scatter axis expansion routine.
// For graphs with very large number of points and array marker.size,
// use average marker size instead to speed things up.
setFirstScatter(fullLayout, trace);
var ppad;
if (!hasTooManyPoints) {
ppad = calcMarkerSize(trace, len);
} else if (opts.marker) {
ppad = opts.marker.sizeAvg || Math.max(opts.marker.size, 3);
}
calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
if (opts.errorX) expandForErrorBars(trace, xa, opts.errorX);
if (opts.errorY) expandForErrorBars(trace, ya, opts.errorY);
// set flags to create scene renderers
if (opts.fill && !scene.fill2d) scene.fill2d = true;
if (opts.marker && !scene.scatter2d) scene.scatter2d = true;
if (opts.line && !scene.line2d) scene.line2d = true;
if ((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true;
if (opts.text && !scene.glText) scene.glText = true;
if (opts.marker) opts.marker.snap = len;
scene.lineOptions.push(opts.line);
scene.errorXOptions.push(opts.errorX);
scene.errorYOptions.push(opts.errorY);
scene.fillOptions.push(opts.fill);
scene.markerOptions.push(opts.marker);
scene.markerSelectedOptions.push(opts.markerSel);
scene.markerUnselectedOptions.push(opts.markerUnsel);
scene.textOptions.push(opts.text);
scene.textSelectedOptions.push(opts.textSel);
scene.textUnselectedOptions.push(opts.textUnsel);
scene.selectBatch.push([]);
scene.unselectBatch.push([]);
stash._scene = scene;
stash.index = scene.count;
stash.x = x;
stash.y = y;
stash.positions = positions;
scene.count++;
return [{
x: false,
y: false,
t: stash,
trace: trace
}];
};
function expandForErrorBars(trace, ax, opts) {
var extremes = trace._extremes[ax._id];
var errExt = findExtremes(ax, opts._bnds, {
padded: true
});
extremes.min = extremes.min.concat(errExt.min);
extremes.max = extremes.max.concat(errExt.max);
}
function sceneOptions(gd, subplot, trace, positions, x, y) {
var opts = convert.style(gd, trace);
if (opts.marker) {
opts.marker.positions = positions;
}
if (opts.line && positions.length > 1) {
Lib.extendFlat(opts.line, convert.linePositions(gd, trace, positions));
}
if (opts.errorX || opts.errorY) {
var errors = convert.errorBarPositions(gd, trace, positions, x, y);
if (opts.errorX) {
Lib.extendFlat(opts.errorX, errors.x);
}
if (opts.errorY) {
Lib.extendFlat(opts.errorY, errors.y);
}
}
if (opts.text) {
Lib.extendFlat(opts.text, {
positions: positions
}, convert.textPosition(gd, trace, opts.text, opts.marker));
Lib.extendFlat(opts.textSel, {
positions: positions
}, convert.textPosition(gd, trace, opts.text, opts.markerSel));
Lib.extendFlat(opts.textUnsel, {
positions: positions
}, convert.textPosition(gd, trace, opts.text, opts.markerUnsel));
}
return opts;
}
/***/ }),
/***/ 67072:
/***/ (function(module) {
"use strict";
var SYMBOL_SIZE = 20;
module.exports = {
TOO_MANY_POINTS: 1e5,
SYMBOL_SDF_SIZE: 200,
SYMBOL_SIZE: SYMBOL_SIZE,
SYMBOL_STROKE: SYMBOL_SIZE / 20,
DOT_RE: /-dot/,
OPEN_RE: /-open/,
DASHES: {
solid: [1],
dot: [1, 1],
dash: [4, 1],
longdash: [8, 1],
dashdot: [4, 1, 1, 1],
longdashdot: [8, 1, 1, 1]
}
};
/***/ }),
/***/ 84236:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var svgSdf = __webpack_require__(20472);
var rgba = __webpack_require__(72160);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var Drawing = __webpack_require__(43616);
var AxisIDs = __webpack_require__(79811);
var formatColor = (__webpack_require__(33040).formatColor);
var subTypes = __webpack_require__(43028);
var makeBubbleSizeFn = __webpack_require__(7152);
var helpers = __webpack_require__(80088);
var constants = __webpack_require__(67072);
var DESELECTDIM = (__webpack_require__(13448).DESELECTDIM);
var TEXTOFFSETSIGN = {
start: 1,
left: 1,
end: -1,
right: -1,
middle: 0,
center: 0,
bottom: 1,
top: -1
};
var appendArrayPointValue = (__webpack_require__(10624).appendArrayPointValue);
function convertStyle(gd, trace) {
var i;
var opts = {
marker: undefined,
markerSel: undefined,
markerUnsel: undefined,
line: undefined,
fill: undefined,
errorX: undefined,
errorY: undefined,
text: undefined,
textSel: undefined,
textUnsel: undefined
};
var plotGlPixelRatio = gd._context.plotGlPixelRatio;
if (trace.visible !== true) return opts;
if (subTypes.hasText(trace)) {
opts.text = convertTextStyle(gd, trace);
opts.textSel = convertTextSelection(gd, trace, trace.selected);
opts.textUnsel = convertTextSelection(gd, trace, trace.unselected);
}
if (subTypes.hasMarkers(trace)) {
opts.marker = convertMarkerStyle(gd, trace);
opts.markerSel = convertMarkerSelection(gd, trace, trace.selected);
opts.markerUnsel = convertMarkerSelection(gd, trace, trace.unselected);
if (!trace.unselected && isArrayOrTypedArray(trace.marker.opacity)) {
var mo = trace.marker.opacity;
opts.markerUnsel.opacity = new Array(mo.length);
for (i = 0; i < mo.length; i++) {
opts.markerUnsel.opacity[i] = DESELECTDIM * mo[i];
}
}
}
if (subTypes.hasLines(trace)) {
opts.line = {
overlay: true,
thickness: trace.line.width * plotGlPixelRatio,
color: trace.line.color,
opacity: trace.opacity
};
var dashes = (constants.DASHES[trace.line.dash] || [1]).slice();
for (i = 0; i < dashes.length; ++i) {
dashes[i] *= trace.line.width * plotGlPixelRatio;
}
opts.line.dashes = dashes;
}
if (trace.error_x && trace.error_x.visible) {
opts.errorX = convertErrorBarStyle(trace, trace.error_x, plotGlPixelRatio);
}
if (trace.error_y && trace.error_y.visible) {
opts.errorY = convertErrorBarStyle(trace, trace.error_y, plotGlPixelRatio);
}
if (!!trace.fill && trace.fill !== 'none') {
opts.fill = {
closed: true,
fill: trace.fillcolor,
thickness: 0
};
}
return opts;
}
function convertTextStyle(gd, trace) {
var fullLayout = gd._fullLayout;
var count = trace._length;
var textfontIn = trace.textfont;
var textpositionIn = trace.textposition;
var textPos = isArrayOrTypedArray(textpositionIn) ? textpositionIn : [textpositionIn];
var tfc = textfontIn.color;
var tfs = textfontIn.size;
var tff = textfontIn.family;
var tfw = textfontIn.weight;
var tfy = textfontIn.style;
var tfv = textfontIn.variant;
var optsOut = {};
var i;
var plotGlPixelRatio = gd._context.plotGlPixelRatio;
var texttemplate = trace.texttemplate;
if (texttemplate) {
optsOut.text = [];
var d3locale = fullLayout._d3locale;
var isArray = Array.isArray(texttemplate);
var N = isArray ? Math.min(texttemplate.length, count) : count;
var txt = isArray ? function (i) {
return texttemplate[i];
} : function () {
return texttemplate;
};
for (i = 0; i < N; i++) {
var d = {
i: i
};
var labels = trace._module.formatLabels(d, trace, fullLayout);
var pointValues = {};
appendArrayPointValue(pointValues, trace, i);
var meta = trace._meta || {};
optsOut.text.push(Lib.texttemplateString(txt(i), labels, d3locale, pointValues, d, meta));
}
} else {
if (isArrayOrTypedArray(trace.text) && trace.text.length < count) {
// if text array is shorter, we'll need to append to it, so let's slice to prevent mutating
optsOut.text = trace.text.slice();
} else {
optsOut.text = trace.text;
}
}
// pad text array with empty strings
if (isArrayOrTypedArray(optsOut.text)) {
for (i = optsOut.text.length; i < count; i++) {
optsOut.text[i] = '';
}
}
optsOut.opacity = trace.opacity;
optsOut.font = {};
optsOut.align = [];
optsOut.baseline = [];
for (i = 0; i < textPos.length; i++) {
var tp = textPos[i].split(/\s+/);
switch (tp[1]) {
case 'left':
optsOut.align.push('right');
break;
case 'right':
optsOut.align.push('left');
break;
default:
optsOut.align.push(tp[1]);
}
switch (tp[0]) {
case 'top':
optsOut.baseline.push('bottom');
break;
case 'bottom':
optsOut.baseline.push('top');
break;
default:
optsOut.baseline.push(tp[0]);
}
}
if (isArrayOrTypedArray(tfc)) {
optsOut.color = new Array(count);
for (i = 0; i < count; i++) {
optsOut.color[i] = tfc[i];
}
} else {
optsOut.color = tfc;
}
if (isArrayOrTypedArray(tfs) || Array.isArray(tff) || isArrayOrTypedArray(tfw) || Array.isArray(tfy) || Array.isArray(tfv)) {
// if any textfont param is array - make render a batch
optsOut.font = new Array(count);
for (i = 0; i < count; i++) {
var fonti = optsOut.font[i] = {};
fonti.size = (Lib.isTypedArray(tfs) ? tfs[i] : isArrayOrTypedArray(tfs) ? isNumeric(tfs[i]) ? tfs[i] : 0 : tfs) * plotGlPixelRatio;
fonti.family = Array.isArray(tff) ? tff[i] : tff;
fonti.weight = weightFallBack(isArrayOrTypedArray(tfw) ? tfw[i] : tfw);
fonti.style = Array.isArray(tfy) ? tfy[i] : tfy;
fonti.variant = Array.isArray(tfv) ? tfv[i] : tfv;
}
} else {
// if both are single values, make render fast single-value
optsOut.font = {
size: tfs * plotGlPixelRatio,
family: tff,
weight: weightFallBack(tfw),
style: tfy,
variant: tfv
};
}
return optsOut;
}
// scattergl rendering pipeline has limited support of numeric weight values
// Here we map the numbers to be either bold or normal.
function weightFallBack(w) {
if (w <= 1000) {
return w > 500 ? 'bold' : 'normal';
}
return w;
}
function convertMarkerStyle(gd, trace) {
var count = trace._length;
var optsIn = trace.marker;
var optsOut = {};
var i;
var multiSymbol = isArrayOrTypedArray(optsIn.symbol);
var multiAngle = isArrayOrTypedArray(optsIn.angle);
var multiColor = isArrayOrTypedArray(optsIn.color);
var multiLineColor = isArrayOrTypedArray(optsIn.line.color);
var multiOpacity = isArrayOrTypedArray(optsIn.opacity);
var multiSize = isArrayOrTypedArray(optsIn.size);
var multiLineWidth = isArrayOrTypedArray(optsIn.line.width);
var isOpen;
if (!multiSymbol) isOpen = helpers.isOpenSymbol(optsIn.symbol);
// prepare colors
if (multiSymbol || multiColor || multiLineColor || multiOpacity || multiAngle) {
optsOut.symbols = new Array(count);
optsOut.angles = new Array(count);
optsOut.colors = new Array(count);
optsOut.borderColors = new Array(count);
var symbols = optsIn.symbol;
var angles = optsIn.angle;
var colors = formatColor(optsIn, optsIn.opacity, count);
var borderColors = formatColor(optsIn.line, optsIn.opacity, count);
if (!isArrayOrTypedArray(borderColors[0])) {
var borderColor = borderColors;
borderColors = Array(count);
for (i = 0; i < count; i++) {
borderColors[i] = borderColor;
}
}
if (!isArrayOrTypedArray(colors[0])) {
var color = colors;
colors = Array(count);
for (i = 0; i < count; i++) {
colors[i] = color;
}
}
if (!isArrayOrTypedArray(symbols)) {
var symbol = symbols;
symbols = Array(count);
for (i = 0; i < count; i++) {
symbols[i] = symbol;
}
}
if (!isArrayOrTypedArray(angles)) {
var angle = angles;
angles = Array(count);
for (i = 0; i < count; i++) {
angles[i] = angle;
}
}
optsOut.symbols = symbols;
optsOut.angles = angles;
optsOut.colors = colors;
optsOut.borderColors = borderColors;
for (i = 0; i < count; i++) {
if (multiSymbol) {
isOpen = helpers.isOpenSymbol(optsIn.symbol[i]);
}
if (isOpen) {
borderColors[i] = colors[i].slice();
colors[i] = colors[i].slice();
colors[i][3] = 0;
}
}
optsOut.opacity = trace.opacity;
optsOut.markers = new Array(count);
for (i = 0; i < count; i++) {
optsOut.markers[i] = getSymbolSdf({
mx: optsOut.symbols[i],
ma: optsOut.angles[i]
}, trace);
}
} else {
if (isOpen) {
optsOut.color = rgba(optsIn.color, 'uint8');
optsOut.color[3] = 0;
optsOut.borderColor = rgba(optsIn.color, 'uint8');
} else {
optsOut.color = rgba(optsIn.color, 'uint8');
optsOut.borderColor = rgba(optsIn.line.color, 'uint8');
}
optsOut.opacity = trace.opacity * optsIn.opacity;
optsOut.marker = getSymbolSdf({
mx: optsIn.symbol,
ma: optsIn.angle
}, trace);
}
// prepare sizes
var sizeFactor = 1;
var markerSizeFunc = makeBubbleSizeFn(trace, sizeFactor);
var s;
if (multiSize || multiLineWidth) {
var sizes = optsOut.sizes = new Array(count);
var borderSizes = optsOut.borderSizes = new Array(count);
var sizeTotal = 0;
var sizeAvg;
if (multiSize) {
for (i = 0; i < count; i++) {
sizes[i] = markerSizeFunc(optsIn.size[i]);
sizeTotal += sizes[i];
}
sizeAvg = sizeTotal / count;
} else {
s = markerSizeFunc(optsIn.size);
for (i = 0; i < count; i++) {
sizes[i] = s;
}
}
// See https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798
if (multiLineWidth) {
for (i = 0; i < count; i++) {
borderSizes[i] = optsIn.line.width[i];
}
} else {
s = optsIn.line.width;
for (i = 0; i < count; i++) {
borderSizes[i] = s;
}
}
optsOut.sizeAvg = sizeAvg;
} else {
optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10);
optsOut.borderSizes = markerSizeFunc(optsIn.line.width);
}
return optsOut;
}
function convertMarkerSelection(gd, trace, target) {
var optsIn = trace.marker;
var optsOut = {};
if (!target) return optsOut;
if (target.marker && target.marker.symbol) {
optsOut = convertMarkerStyle(gd, Lib.extendFlat({}, optsIn, target.marker));
} else if (target.marker) {
if (target.marker.size) optsOut.size = target.marker.size;
if (target.marker.color) optsOut.colors = target.marker.color;
if (target.marker.opacity !== undefined) optsOut.opacity = target.marker.opacity;
}
return optsOut;
}
function convertTextSelection(gd, trace, target) {
var optsOut = {};
if (!target) return optsOut;
if (target.textfont) {
var optsIn = {
opacity: 1,
text: trace.text,
texttemplate: trace.texttemplate,
textposition: trace.textposition,
textfont: Lib.extendFlat({}, trace.textfont)
};
if (target.textfont) {
Lib.extendFlat(optsIn.textfont, target.textfont);
}
optsOut = convertTextStyle(gd, optsIn);
}
return optsOut;
}
function convertErrorBarStyle(trace, target, plotGlPixelRatio) {
var optsOut = {
capSize: target.width * 2 * plotGlPixelRatio,
lineWidth: target.thickness * plotGlPixelRatio,
color: target.color
};
if (target.copy_ystyle) {
optsOut = trace.error_y;
}
return optsOut;
}
var SYMBOL_SDF_SIZE = constants.SYMBOL_SDF_SIZE;
var SYMBOL_SIZE = constants.SYMBOL_SIZE;
var SYMBOL_STROKE = constants.SYMBOL_STROKE;
var SYMBOL_SDF = {};
var SYMBOL_SVG_CIRCLE = Drawing.symbolFuncs[0](SYMBOL_SIZE * 0.05);
function getSymbolSdf(d, trace) {
var symbol = d.mx;
if (symbol === 'circle') return null;
var symbolPath, symbolSdf;
var symbolNumber = Drawing.symbolNumber(symbol);
var symbolFunc = Drawing.symbolFuncs[symbolNumber % 100];
var symbolNoDot = !!Drawing.symbolNoDot[symbolNumber % 100];
var symbolNoFill = !!Drawing.symbolNoFill[symbolNumber % 100];
var isDot = helpers.isDotSymbol(symbol);
// until we may handle angles in shader?
if (d.ma) symbol += '_' + d.ma;
// get symbol sdf from cache or generate it
if (SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol];
var angle = Drawing.getMarkerAngle(d, trace);
if (isDot && !symbolNoDot) {
symbolPath = symbolFunc(SYMBOL_SIZE * 1.1, angle) + SYMBOL_SVG_CIRCLE;
} else {
symbolPath = symbolFunc(SYMBOL_SIZE, angle);
}
symbolSdf = svgSdf(symbolPath, {
w: SYMBOL_SDF_SIZE,
h: SYMBOL_SDF_SIZE,
viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE],
stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE
});
SYMBOL_SDF[symbol] = symbolSdf;
return symbolSdf || null;
}
function convertLinePositions(gd, trace, positions) {
var len = positions.length;
var count = len / 2;
var linePositions;
var i;
if (subTypes.hasLines(trace) && count) {
if (trace.line.shape === 'hv') {
linePositions = [];
for (i = 0; i < count - 1; i++) {
if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
linePositions.push(NaN, NaN, NaN, NaN);
} else {
linePositions.push(positions[i * 2], positions[i * 2 + 1]);
if (!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) {
linePositions.push(positions[i * 2 + 2], positions[i * 2 + 1]);
} else {
linePositions.push(NaN, NaN);
}
}
}
linePositions.push(positions[len - 2], positions[len - 1]);
} else if (trace.line.shape === 'hvh') {
linePositions = [];
for (i = 0; i < count - 1; i++) {
if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) {
if (!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) {
linePositions.push(positions[i * 2], positions[i * 2 + 1]);
} else {
linePositions.push(NaN, NaN);
}
linePositions.push(NaN, NaN);
} else {
var midPtX = (positions[i * 2] + positions[i * 2 + 2]) / 2;
linePositions.push(positions[i * 2], positions[i * 2 + 1], midPtX, positions[i * 2 + 1], midPtX, positions[i * 2 + 3]);
}
}
linePositions.push(positions[len - 2], positions[len - 1]);
} else if (trace.line.shape === 'vhv') {
linePositions = [];
for (i = 0; i < count - 1; i++) {
if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) {
if (!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) {
linePositions.push(positions[i * 2], positions[i * 2 + 1]);
} else {
linePositions.push(NaN, NaN);
}
linePositions.push(NaN, NaN);
} else {
var midPtY = (positions[i * 2 + 1] + positions[i * 2 + 3]) / 2;
linePositions.push(positions[i * 2], positions[i * 2 + 1], positions[i * 2], midPtY, positions[i * 2 + 2], midPtY);
}
}
linePositions.push(positions[len - 2], positions[len - 1]);
} else if (trace.line.shape === 'vh') {
linePositions = [];
for (i = 0; i < count - 1; i++) {
if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
linePositions.push(NaN, NaN, NaN, NaN);
} else {
linePositions.push(positions[i * 2], positions[i * 2 + 1]);
if (!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) {
linePositions.push(positions[i * 2], positions[i * 2 + 3]);
} else {
linePositions.push(NaN, NaN);
}
}
}
linePositions.push(positions[len - 2], positions[len - 1]);
} else {
linePositions = positions;
}
}
// If we have data with gaps, we ought to use rect joins
// FIXME: get rid of this
var hasNaN = false;
for (i = 0; i < linePositions.length; i++) {
if (isNaN(linePositions[i])) {
hasNaN = true;
break;
}
}
var join = hasNaN || linePositions.length > constants.TOO_MANY_POINTS ? 'rect' : subTypes.hasMarkers(trace) ? 'rect' : 'round';
// fill gaps
if (hasNaN && trace.connectgaps) {
var lastX = linePositions[0];
var lastY = linePositions[1];
for (i = 0; i < linePositions.length; i += 2) {
if (isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) {
linePositions[i] = lastX;
linePositions[i + 1] = lastY;
} else {
lastX = linePositions[i];
lastY = linePositions[i + 1];
}
}
}
return {
join: join,
positions: linePositions
};
}
function convertErrorBarPositions(gd, trace, positions, x, y) {
var makeComputeError = Registry.getComponentMethod('errorbars', 'makeComputeError');
var xa = AxisIDs.getFromId(gd, trace.xaxis, 'x');
var ya = AxisIDs.getFromId(gd, trace.yaxis, 'y');
var count = positions.length / 2;
var out = {};
function convertOneAxis(coords, ax) {
var axLetter = ax._id.charAt(0);
var opts = trace['error_' + axLetter];
if (opts && opts.visible && (ax.type === 'linear' || ax.type === 'log')) {
var computeError = makeComputeError(opts);
var pOffset = {
x: 0,
y: 1
}[axLetter];
var eOffset = {
x: [0, 1, 2, 3],
y: [2, 3, 0, 1]
}[axLetter];
var errors = new Float64Array(4 * count);
var minShoe = Infinity;
var maxHat = -Infinity;
for (var i = 0, j = 0; i < count; i++, j += 4) {
var dc = coords[i];
if (isNumeric(dc)) {
var dl = positions[i * 2 + pOffset];
var vals = computeError(dc, i);
var lv = vals[0];
var hv = vals[1];
if (isNumeric(lv) && isNumeric(hv)) {
var shoe = dc - lv;
var hat = dc + hv;
errors[j + eOffset[0]] = dl - ax.c2l(shoe);
errors[j + eOffset[1]] = ax.c2l(hat) - dl;
errors[j + eOffset[2]] = 0;
errors[j + eOffset[3]] = 0;
minShoe = Math.min(minShoe, dc - lv);
maxHat = Math.max(maxHat, dc + hv);
}
}
}
out[axLetter] = {
positions: positions,
errors: errors,
_bnds: [minShoe, maxHat]
};
}
}
convertOneAxis(x, xa);
convertOneAxis(y, ya);
return out;
}
function convertTextPosition(gd, trace, textOpts, markerOpts) {
var count = trace._length;
var out = {};
var i;
// corresponds to textPointPosition from component.drawing
if (subTypes.hasMarkers(trace)) {
var fontOpts = textOpts.font;
var align = textOpts.align;
var baseline = textOpts.baseline;
out.offset = new Array(count);
for (i = 0; i < count; i++) {
var ms = markerOpts.sizes ? markerOpts.sizes[i] : markerOpts.size;
var fs = isArrayOrTypedArray(fontOpts) ? fontOpts[i].size : fontOpts.size;
var a = isArrayOrTypedArray(align) ? align.length > 1 ? align[i] : align[0] : align;
var b = isArrayOrTypedArray(baseline) ? baseline.length > 1 ? baseline[i] : baseline[0] : baseline;
var hSign = TEXTOFFSETSIGN[a];
var vSign = TEXTOFFSETSIGN[b];
var xPad = ms ? ms / 0.8 + 1 : 0;
var yPad = -vSign * xPad - vSign * 0.5;
out.offset[i] = [hSign * xPad / fs, yPad / fs];
}
}
return out;
}
module.exports = {
style: convertStyle,
markerStyle: convertMarkerStyle,
markerSelection: convertMarkerSelection,
linePositions: convertLinePositions,
errorBarPositions: convertErrorBarPositions,
textPosition: convertTextPosition
};
/***/ }),
/***/ 80220:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var helpers = __webpack_require__(80088);
var attributes = __webpack_require__(2876);
var constants = __webpack_require__(88200);
var subTypes = __webpack_require__(43028);
var handleXYDefaults = __webpack_require__(43980);
var handlePeriodDefaults = __webpack_require__(31147);
var handleMarkerDefaults = __webpack_require__(74428);
var handleLineDefaults = __webpack_require__(66828);
var handleFillColorDefaults = __webpack_require__(70840);
var handleTextDefaults = __webpack_require__(124);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var isOpen = traceIn.marker ? helpers.isOpenSymbol(traceIn.marker.symbol) : false;
var isBubble = subTypes.isBubble(traceIn);
var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
if (!len) {
traceOut.visible = false;
return;
}
handlePeriodDefaults(traceIn, traceOut, layout, coerce);
coerce('xhoverformat');
coerce('yhoverformat');
var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
coerce('mode', defaultMode);
if (subTypes.hasMarkers(traceOut)) {
handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
noAngleRef: true,
noStandOff: true
});
coerce('marker.line.width', isOpen || isBubble ? 1 : 0);
}
if (subTypes.hasLines(traceOut)) {
coerce('connectgaps');
handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
coerce('line.shape');
}
if (subTypes.hasText(traceOut)) {
coerce('texttemplate');
handleTextDefaults(traceIn, traceOut, layout, coerce, {
noFontShadow: true,
noFontLineposition: true,
noFontTextcase: true
});
}
var lineColor = (traceOut.line || {}).color;
var markerColor = (traceOut.marker || {}).color;
coerce('fill');
if (traceOut.fill !== 'none') {
handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
}
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);
};
/***/ }),
/***/ 26768:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var DESELECTDIM = (__webpack_require__(13448).DESELECTDIM);
function styleTextSelection(cd) {
var cd0 = cd[0];
var trace = cd0.trace;
var stash = cd0.t;
var scene = stash._scene;
var index = stash.index;
var els = scene.selectBatch[index];
var unels = scene.unselectBatch[index];
var baseOpts = scene.textOptions[index];
var selOpts = scene.textSelectedOptions[index] || {};
var unselOpts = scene.textUnselectedOptions[index] || {};
var opts = Lib.extendFlat({}, baseOpts);
var i, j;
if (els.length || unels.length) {
var stc = selOpts.color;
var utc = unselOpts.color;
var base = baseOpts.color;
var hasArrayBase = Lib.isArrayOrTypedArray(base);
opts.color = new Array(trace._length);
for (i = 0; i < els.length; i++) {
j = els[i];
opts.color[j] = stc || (hasArrayBase ? base[j] : base);
}
for (i = 0; i < unels.length; i++) {
j = unels[i];
var basej = hasArrayBase ? base[j] : base;
opts.color[j] = utc ? utc : stc ? basej : Color.addOpacity(basej, DESELECTDIM);
}
}
scene.glText[index].update(opts);
}
module.exports = {
styleTextSelection: styleTextSelection
};
/***/ }),
/***/ 99396:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterFormatLabels = __webpack_require__(76688);
module.exports = function formatLabels(cdi, trace, fullLayout) {
var i = cdi.i;
if (!('x' in cdi)) cdi.x = trace._x[i];
if (!('y' in cdi)) cdi.y = trace._y[i];
return scatterFormatLabels(cdi, trace, fullLayout);
};
/***/ }),
/***/ 80088:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(67072);
exports.isOpenSymbol = function (symbol) {
return typeof symbol === 'string' ? constants.OPEN_RE.test(symbol) : symbol % 200 > 100;
};
exports.isDotSymbol = function (symbol) {
return typeof symbol === 'string' ? constants.DOT_RE.test(symbol) : symbol > 200;
};
/***/ }),
/***/ 41272:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var getTraceColor = __webpack_require__(44928);
function hoverPoints(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var stash = cd[0].t;
var trace = cd[0].trace;
var xa = pointData.xa;
var ya = pointData.ya;
var x = stash.x;
var y = stash.y;
var xpx = xa.c2p(xval);
var ypx = ya.c2p(yval);
var maxDistance = pointData.distance;
var ids;
// FIXME: make sure this is a proper way to calc search radius
if (stash.tree) {
var xl = xa.p2c(xpx - maxDistance);
var xr = xa.p2c(xpx + maxDistance);
var yl = ya.p2c(ypx - maxDistance);
var yr = ya.p2c(ypx + maxDistance);
if (hovermode === 'x') {
ids = stash.tree.range(Math.min(xl, xr), Math.min(ya._rl[0], ya._rl[1]), Math.max(xl, xr), Math.max(ya._rl[0], ya._rl[1]));
} else {
ids = stash.tree.range(Math.min(xl, xr), Math.min(yl, yr), Math.max(xl, xr), Math.max(yl, yr));
}
} else {
ids = stash.ids;
}
// pick the id closest to the point
// note that point possibly may not be found
var k, closestId, ptx, pty, i, dx, dy, dist, dxy;
var minDist = maxDistance;
if (hovermode === 'x') {
var xPeriod = !!trace.xperiodalignment;
var yPeriod = !!trace.yperiodalignment;
for (i = 0; i < ids.length; i++) {
k = ids[i];
ptx = x[k];
dx = Math.abs(xa.c2p(ptx) - xpx);
if (xPeriod) {
var x0 = xa.c2p(trace._xStarts[k]);
var x1 = xa.c2p(trace._xEnds[k]);
dx = xpx >= Math.min(x0, x1) && xpx <= Math.max(x0, x1) ? 0 : Infinity;
}
if (dx < minDist) {
minDist = dx;
pty = y[k];
dy = ya.c2p(pty) - ypx;
if (yPeriod) {
var y0 = ya.c2p(trace._yStarts[k]);
var y1 = ya.c2p(trace._yEnds[k]);
dy = ypx >= Math.min(y0, y1) && ypx <= Math.max(y0, y1) ? 0 : Infinity;
}
dxy = Math.sqrt(dx * dx + dy * dy);
closestId = ids[i];
}
}
} else {
for (i = ids.length - 1; i > -1; i--) {
k = ids[i];
ptx = x[k];
pty = y[k];
dx = xa.c2p(ptx) - xpx;
dy = ya.c2p(pty) - ypx;
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist) {
minDist = dxy = dist;
closestId = k;
}
}
}
pointData.index = closestId;
pointData.distance = minDist;
pointData.dxy = dxy;
if (closestId === undefined) return [pointData];
return [calcHover(pointData, x, y, trace)];
}
function calcHover(pointData, x, y, trace) {
var xa = pointData.xa;
var ya = pointData.ya;
var minDist = pointData.distance;
var dxy = pointData.dxy;
var id = pointData.index;
// the closest data point
var di = {
pointNumber: id,
x: x[id],
y: y[id]
};
// that is single-item arrays_to_calcdata excerpt, since we are doing it for a single point and we don't have to do it beforehead for 1e6 points
di.tx = Lib.isArrayOrTypedArray(trace.text) ? trace.text[id] : trace.text;
di.htx = Array.isArray(trace.hovertext) ? trace.hovertext[id] : trace.hovertext;
di.data = Array.isArray(trace.customdata) ? trace.customdata[id] : trace.customdata;
di.tp = Array.isArray(trace.textposition) ? trace.textposition[id] : trace.textposition;
var font = trace.textfont;
if (font) {
di.ts = Lib.isArrayOrTypedArray(font.size) ? font.size[id] : font.size;
di.tc = Lib.isArrayOrTypedArray(font.color) ? font.color[id] : font.color;
di.tf = Array.isArray(font.family) ? font.family[id] : font.family;
di.tw = Array.isArray(font.weight) ? font.weight[id] : font.weight;
di.ty = Array.isArray(font.style) ? font.style[id] : font.style;
di.tv = Array.isArray(font.variant) ? font.variant[id] : font.variant;
}
var marker = trace.marker;
if (marker) {
di.ms = Lib.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size;
di.mo = Lib.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity;
di.mx = Lib.isArrayOrTypedArray(marker.symbol) ? marker.symbol[id] : marker.symbol;
di.ma = Lib.isArrayOrTypedArray(marker.angle) ? marker.angle[id] : marker.angle;
di.mc = Lib.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color;
}
var line = marker && marker.line;
if (line) {
di.mlc = Array.isArray(line.color) ? line.color[id] : line.color;
di.mlw = Lib.isArrayOrTypedArray(line.width) ? line.width[id] : line.width;
}
var grad = marker && marker.gradient;
if (grad && grad.type !== 'none') {
di.mgt = Array.isArray(grad.type) ? grad.type[id] : grad.type;
di.mgc = Array.isArray(grad.color) ? grad.color[id] : grad.color;
}
var xp = xa.c2p(di.x, true);
var yp = ya.c2p(di.y, true);
var rad = di.mrc || 1;
var hoverlabel = trace.hoverlabel;
if (hoverlabel) {
di.hbg = Array.isArray(hoverlabel.bgcolor) ? hoverlabel.bgcolor[id] : hoverlabel.bgcolor;
di.hbc = Array.isArray(hoverlabel.bordercolor) ? hoverlabel.bordercolor[id] : hoverlabel.bordercolor;
di.hts = Lib.isArrayOrTypedArray(hoverlabel.font.size) ? hoverlabel.font.size[id] : hoverlabel.font.size;
di.htc = Array.isArray(hoverlabel.font.color) ? hoverlabel.font.color[id] : hoverlabel.font.color;
di.htf = Array.isArray(hoverlabel.font.family) ? hoverlabel.font.family[id] : hoverlabel.font.family;
di.hnl = Lib.isArrayOrTypedArray(hoverlabel.namelength) ? hoverlabel.namelength[id] : hoverlabel.namelength;
}
var hoverinfo = trace.hoverinfo;
if (hoverinfo) {
di.hi = Array.isArray(hoverinfo) ? hoverinfo[id] : hoverinfo;
}
var hovertemplate = trace.hovertemplate;
if (hovertemplate) {
di.ht = Array.isArray(hovertemplate) ? hovertemplate[id] : hovertemplate;
}
var fakeCd = {};
fakeCd[pointData.index] = di;
var origX = trace._origX;
var origY = trace._origY;
var pointData2 = Lib.extendFlat({}, pointData, {
color: getTraceColor(trace, di),
x0: xp - rad,
x1: xp + rad,
xLabelVal: origX ? origX[id] : di.x,
y0: yp - rad,
y1: yp + rad,
yLabelVal: origY ? origY[id] : di.y,
cd: fakeCd,
distance: minDist,
spikeDistance: dxy,
hovertemplate: di.ht
});
if (di.htx) pointData2.text = di.htx;else if (di.tx) pointData2.text = di.tx;else if (trace.text) pointData2.text = trace.text;
Lib.fillText(di, trace, pointData2);
Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData2);
return pointData2;
}
module.exports = {
hoverPoints: hoverPoints,
calcHover: calcHover
};
/***/ }),
/***/ 89876:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createScatter = __webpack_require__(38540);
var createLine = __webpack_require__(13472);
var createError = __webpack_require__(24544);
var Text = __webpack_require__(23352);
var Lib = __webpack_require__(3400);
var selectMode = (__webpack_require__(72760).selectMode);
var prepareRegl = __webpack_require__(5048);
var subTypes = __webpack_require__(43028);
var linkTraces = __webpack_require__(14328);
var styleTextSelection = (__webpack_require__(26768).styleTextSelection);
var reglPrecompiled = {};
function getViewport(fullLayout, xaxis, yaxis, plotGlPixelRatio) {
var gs = fullLayout._size;
var width = fullLayout.width * plotGlPixelRatio;
var height = fullLayout.height * plotGlPixelRatio;
var l = gs.l * plotGlPixelRatio;
var b = gs.b * plotGlPixelRatio;
var r = gs.r * plotGlPixelRatio;
var t = gs.t * plotGlPixelRatio;
var w = gs.w * plotGlPixelRatio;
var h = gs.h * plotGlPixelRatio;
return [l + xaxis.domain[0] * w, b + yaxis.domain[0] * h, width - r - (1 - xaxis.domain[1]) * w, height - t - (1 - yaxis.domain[1]) * h];
}
var exports = module.exports = function plot(gd, subplot, cdata) {
if (!cdata.length) return;
var fullLayout = gd._fullLayout;
var scene = subplot._scene;
var xaxis = subplot.xaxis;
var yaxis = subplot.yaxis;
var i, j;
// we may have more subplots than initialized data due to Axes.getSubplots method
if (!scene) return;
var success = prepareRegl(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint'], reglPrecompiled);
if (!success) {
scene.init();
return;
}
var count = scene.count;
var regl = fullLayout._glcanvas.data()[0].regl;
// that is needed for fills
linkTraces(gd, subplot, cdata);
if (scene.dirty) {
if ((scene.line2d || scene.error2d) && !(scene.scatter2d || scene.fill2d || scene.glText)) {
// Fixes shared WebGL context drawing lines only case
regl.clear({});
}
// make sure scenes are created
if (scene.error2d === true) {
scene.error2d = createError(regl);
}
if (scene.line2d === true) {
scene.line2d = createLine(regl);
}
if (scene.scatter2d === true) {
scene.scatter2d = createScatter(regl);
}
if (scene.fill2d === true) {
scene.fill2d = createLine(regl);
}
if (scene.glText === true) {
scene.glText = new Array(count);
for (i = 0; i < count; i++) {
scene.glText[i] = new Text(regl);
}
}
// update main marker options
if (scene.glText) {
if (count > scene.glText.length) {
// add gl text marker
var textsToAdd = count - scene.glText.length;
for (i = 0; i < textsToAdd; i++) {
scene.glText.push(new Text(regl));
}
} else if (count < scene.glText.length) {
// remove gl text marker
var textsToRemove = scene.glText.length - count;
var removedTexts = scene.glText.splice(count, textsToRemove);
removedTexts.forEach(function (text) {
text.destroy();
});
}
for (i = 0; i < count; i++) {
scene.glText[i].update(scene.textOptions[i]);
}
}
if (scene.line2d) {
scene.line2d.update(scene.lineOptions);
scene.lineOptions = scene.lineOptions.map(function (lineOptions) {
if (lineOptions && lineOptions.positions) {
var srcPos = lineOptions.positions;
var firstptdef = 0;
while (firstptdef < srcPos.length && (isNaN(srcPos[firstptdef]) || isNaN(srcPos[firstptdef + 1]))) {
firstptdef += 2;
}
var lastptdef = srcPos.length - 2;
while (lastptdef > firstptdef && (isNaN(srcPos[lastptdef]) || isNaN(srcPos[lastptdef + 1]))) {
lastptdef -= 2;
}
lineOptions.positions = srcPos.slice(firstptdef, lastptdef + 2);
}
return lineOptions;
});
scene.line2d.update(scene.lineOptions);
}
if (scene.error2d) {
var errorBatch = (scene.errorXOptions || []).concat(scene.errorYOptions || []);
scene.error2d.update(errorBatch);
}
if (scene.scatter2d) {
scene.scatter2d.update(scene.markerOptions);
}
// fill requires linked traces, so we generate it's positions here
scene.fillOrder = Lib.repeat(null, count);
if (scene.fill2d) {
scene.fillOptions = scene.fillOptions.map(function (fillOptions, i) {
var cdscatter = cdata[i];
if (!fillOptions || !cdscatter || !cdscatter[0] || !cdscatter[0].trace) return;
var cd = cdscatter[0];
var trace = cd.trace;
var stash = cd.t;
var lineOptions = scene.lineOptions[i];
var last, j;
var fillData = [];
if (trace._ownfill) fillData.push(i);
if (trace._nexttrace) fillData.push(i + 1);
if (fillData.length) scene.fillOrder[i] = fillData;
var pos = [];
var srcPos = lineOptions && lineOptions.positions || stash.positions;
var firstptdef, lastptdef;
if (trace.fill === 'tozeroy') {
firstptdef = 0;
while (firstptdef < srcPos.length && isNaN(srcPos[firstptdef + 1])) {
firstptdef += 2;
}
lastptdef = srcPos.length - 2;
while (lastptdef > firstptdef && isNaN(srcPos[lastptdef + 1])) {
lastptdef -= 2;
}
if (srcPos[firstptdef + 1] !== 0) {
pos = [srcPos[firstptdef], 0];
}
pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2));
if (srcPos[lastptdef + 1] !== 0) {
pos = pos.concat([srcPos[lastptdef], 0]);
}
} else if (trace.fill === 'tozerox') {
firstptdef = 0;
while (firstptdef < srcPos.length && isNaN(srcPos[firstptdef])) {
firstptdef += 2;
}
lastptdef = srcPos.length - 2;
while (lastptdef > firstptdef && isNaN(srcPos[lastptdef])) {
lastptdef -= 2;
}
if (srcPos[firstptdef] !== 0) {
pos = [0, srcPos[firstptdef + 1]];
}
pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2));
if (srcPos[lastptdef] !== 0) {
pos = pos.concat([0, srcPos[lastptdef + 1]]);
}
} else if (trace.fill === 'toself' || trace.fill === 'tonext') {
pos = [];
last = 0;
fillOptions.splitNull = true;
for (j = 0; j < srcPos.length; j += 2) {
if (isNaN(srcPos[j]) || isNaN(srcPos[j + 1])) {
pos = pos.concat(srcPos.slice(last, j));
pos.push(srcPos[last], srcPos[last + 1]);
pos.push(null, null); // keep null to mark end of polygon
last = j + 2;
}
}
pos = pos.concat(srcPos.slice(last));
if (last) {
pos.push(srcPos[last], srcPos[last + 1]);
}
} else {
var nextTrace = trace._nexttrace;
if (nextTrace) {
var nextOptions = scene.lineOptions[i + 1];
if (nextOptions) {
var nextPos = nextOptions.positions;
if (trace.fill === 'tonexty') {
pos = srcPos.slice();
for (i = Math.floor(nextPos.length / 2); i--;) {
var xx = nextPos[i * 2];
var yy = nextPos[i * 2 + 1];
if (isNaN(xx) || isNaN(yy)) continue;
pos.push(xx, yy);
}
fillOptions.fill = nextTrace.fillcolor;
}
}
}
}
// detect prev trace positions to exclude from current fill
if (trace._prevtrace && trace._prevtrace.fill === 'tonext') {
var prevLinePos = scene.lineOptions[i - 1].positions;
// FIXME: likely this logic should be tested better
var offset = pos.length / 2;
last = offset;
var hole = [last];
for (j = 0; j < prevLinePos.length; j += 2) {
if (isNaN(prevLinePos[j]) || isNaN(prevLinePos[j + 1])) {
hole.push(j / 2 + offset + 1);
last = j + 2;
}
}
pos = pos.concat(prevLinePos);
fillOptions.hole = hole;
}
fillOptions.fillmode = trace.fill;
fillOptions.opacity = trace.opacity;
fillOptions.positions = pos;
return fillOptions;
});
scene.fill2d.update(scene.fillOptions);
}
}
// form batch arrays, and check for selected points
var dragmode = fullLayout.dragmode;
var isSelectMode = selectMode(dragmode);
var clickSelectEnabled = fullLayout.clickmode.indexOf('select') > -1;
for (i = 0; i < count; i++) {
var cd0 = cdata[i][0];
var trace = cd0.trace;
var stash = cd0.t;
var index = stash.index;
var len = trace._length;
var x = stash.x;
var y = stash.y;
if (trace.selectedpoints || isSelectMode || clickSelectEnabled) {
if (!isSelectMode) isSelectMode = true;
// regenerate scene batch, if traces number changed during selection
if (trace.selectedpoints) {
var selPts = scene.selectBatch[index] = Lib.selIndices2selPoints(trace);
var selDict = {};
for (j = 0; j < selPts.length; j++) {
selDict[selPts[j]] = 1;
}
var unselPts = [];
for (j = 0; j < len; j++) {
if (!selDict[j]) unselPts.push(j);
}
scene.unselectBatch[index] = unselPts;
}
// precalculate px coords since we are not going to pan during select
// TODO, could do better here e.g.
// - spin that in a webworker
// - compute selection from polygons in data coordinates
// (maybe just for linear axes)
var xpx = stash.xpx = new Array(len);
var ypx = stash.ypx = new Array(len);
for (j = 0; j < len; j++) {
xpx[j] = xaxis.c2p(x[j]);
ypx[j] = yaxis.c2p(y[j]);
}
} else {
stash.xpx = stash.ypx = null;
}
}
if (isSelectMode) {
// create scatter instance by cloning scatter2d
if (!scene.select2d) {
scene.select2d = createScatter(fullLayout._glcanvas.data()[1].regl);
}
// use unselected styles on 'context' canvas
if (scene.scatter2d) {
var unselOpts = new Array(count);
for (i = 0; i < count; i++) {
unselOpts[i] = scene.selectBatch[i].length || scene.unselectBatch[i].length ? scene.markerUnselectedOptions[i] : {};
}
scene.scatter2d.update(unselOpts);
}
// use selected style on 'focus' canvas
if (scene.select2d) {
scene.select2d.update(scene.markerOptions);
scene.select2d.update(scene.markerSelectedOptions);
}
if (scene.glText) {
cdata.forEach(function (cdscatter) {
var trace = ((cdscatter || [])[0] || {}).trace || {};
if (subTypes.hasText(trace)) {
styleTextSelection(cdscatter);
}
});
}
} else {
// reset 'context' scatter2d opts to base opts,
// thus unsetting markerUnselectedOptions from selection
if (scene.scatter2d) {
scene.scatter2d.update(scene.markerOptions);
}
}
// provide viewport and range
var vpRange0 = {
viewport: getViewport(fullLayout, xaxis, yaxis, gd._context.plotGlPixelRatio),
// TODO do we need those fallbacks?
range: [(xaxis._rl || xaxis.range)[0], (yaxis._rl || yaxis.range)[0], (xaxis._rl || xaxis.range)[1], (yaxis._rl || yaxis.range)[1]]
};
var vpRange = Lib.repeat(vpRange0, scene.count);
// upload viewport/range data to GPU
if (scene.fill2d) {
scene.fill2d.update(vpRange);
}
if (scene.line2d) {
scene.line2d.update(vpRange);
}
if (scene.error2d) {
scene.error2d.update(vpRange.concat(vpRange));
}
if (scene.scatter2d) {
scene.scatter2d.update(vpRange);
}
if (scene.select2d) {
scene.select2d.update(vpRange);
}
if (scene.glText) {
scene.glText.forEach(function (text) {
text.update(vpRange0);
});
}
};
exports.reglPrecompiled = reglPrecompiled;
/***/ }),
/***/ 61608:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var plot = __webpack_require__(89876);
var reglPrecompiled = __webpack_require__(28848);
Object.assign(plot.reglPrecompiled, reglPrecompiled);
module.exports = plot;
/***/ }),
/***/ 28848:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var v0 = __webpack_require__(51154);
var v1 = __webpack_require__(81705);
var v2 = __webpack_require__(39760);
var v3 = __webpack_require__(51068);
var v4 = __webpack_require__(81272);
var v5 = __webpack_require__(8756);
var v6 = __webpack_require__(82576);
var v7 = __webpack_require__(29548);
var v8 = __webpack_require__(7108);
var v9 = __webpack_require__(62052);
/* eslint-disable quote-props */
module.exports = {
'3e771157d23b4793771f65d83e6387262ed73d488209157f19a7fa027bddd71b': v0,
'cbf700f001fff25b649fba9c37fa0dc6631c1cdee318ad49473d28ec10dcee81': v1,
'8fad2284703471df7c0e0d0a7b96d983e8c53f6d707dd55d5921c1eab71f6623': v2,
'fe5b6844077cde1bdd7273f4495969fad93500c26a69b62e74ec2664c447bcc7': v3,
'db1b82c68771e7f5012fad1fbdae7ff23b526e58d2995bf6dd2cf30024e0f41d': v4,
'49e82bba439f1d9d441c17ba252d05640bc63fefdf22d1219993633af7730210': v5,
'dbd1cc9126a137a605df67dc0706e55116f04e33b4545a80042031752de5aef5': v6,
'bfc540da96a87fcc039073cb37b45e6b81ef5ee6ef3529d726ceed8336354019': v7,
'6a5d6bd29c15cf7614221b94c3f384df47c2c46fbe4456e8c57b5cd14c84d923': v8,
'8902aff2b23b600f8103bcc84a8af2999d28795208aedadc2db06f921f9c7034': v9
};
/***/ }),
/***/ 74588:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
// make sure scene exists on subplot, return it
module.exports = function sceneUpdate(gd, subplot) {
var scene = subplot._scene;
var resetOpts = {
// number of traces in subplot, since scene:subplot -> 1:1
count: 0,
// whether scene requires init hook in plot call (dirty plot call)
dirty: true,
// last used options
lineOptions: [],
fillOptions: [],
markerOptions: [],
markerSelectedOptions: [],
markerUnselectedOptions: [],
errorXOptions: [],
errorYOptions: [],
textOptions: [],
textSelectedOptions: [],
textUnselectedOptions: [],
// selection batches
selectBatch: [],
unselectBatch: []
};
// regl- component stubs, initialized in dirty plot call
var initOpts = {
fill2d: false,
scatter2d: false,
error2d: false,
line2d: false,
glText: false,
select2d: false
};
if (!subplot._scene) {
scene = subplot._scene = {};
scene.init = function init() {
Lib.extendFlat(scene, initOpts, resetOpts);
};
scene.init();
// apply new option to all regl components (used on drag)
scene.update = function update(opt) {
var opts = Lib.repeat(opt, scene.count);
if (scene.fill2d) scene.fill2d.update(opts);
if (scene.scatter2d) scene.scatter2d.update(opts);
if (scene.line2d) scene.line2d.update(opts);
if (scene.error2d) scene.error2d.update(opts.concat(opts));
if (scene.select2d) scene.select2d.update(opts);
if (scene.glText) {
for (var i = 0; i < scene.count; i++) {
scene.glText[i].update(opt);
}
}
};
// draw traces in proper order
scene.draw = function draw() {
var count = scene.count;
var fill2d = scene.fill2d;
var error2d = scene.error2d;
var line2d = scene.line2d;
var scatter2d = scene.scatter2d;
var glText = scene.glText;
var select2d = scene.select2d;
var selectBatch = scene.selectBatch;
var unselectBatch = scene.unselectBatch;
for (var i = 0; i < count; i++) {
if (fill2d && scene.fillOrder[i]) {
fill2d.draw(scene.fillOrder[i]);
}
if (line2d && scene.lineOptions[i]) {
line2d.draw(i);
}
if (error2d) {
if (scene.errorXOptions[i]) error2d.draw(i);
if (scene.errorYOptions[i]) error2d.draw(i + count);
}
if (scatter2d && scene.markerOptions[i]) {
if (unselectBatch[i].length) {
var arg = Lib.repeat([], scene.count);
arg[i] = unselectBatch[i];
scatter2d.draw(arg);
} else if (!selectBatch[i].length) {
scatter2d.draw(i);
}
}
if (glText[i] && scene.textOptions[i]) {
glText[i].render();
}
}
if (select2d) {
select2d.draw(selectBatch);
}
scene.dirty = false;
};
// remove scene resources
scene.destroy = function destroy() {
if (scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy();
if (scene.scatter2d && scene.scatter2d.destroy) scene.scatter2d.destroy();
if (scene.error2d && scene.error2d.destroy) scene.error2d.destroy();
if (scene.line2d && scene.line2d.destroy) scene.line2d.destroy();
if (scene.select2d && scene.select2d.destroy) scene.select2d.destroy();
if (scene.glText) {
scene.glText.forEach(function (text) {
if (text.destroy) text.destroy();
});
}
scene.lineOptions = null;
scene.fillOptions = null;
scene.markerOptions = null;
scene.markerSelectedOptions = null;
scene.markerUnselectedOptions = null;
scene.errorXOptions = null;
scene.errorYOptions = null;
scene.textOptions = null;
scene.textSelectedOptions = null;
scene.textUnselectedOptions = null;
scene.selectBatch = null;
scene.unselectBatch = null;
// we can't just delete _scene, because `destroy` is called in the
// middle of supplyDefaults, before relinkPrivateKeys which will put it back.
subplot._scene = null;
};
}
// in case if we have scene from the last calc - reset data
if (!scene.dirty) {
Lib.extendFlat(scene, resetOpts);
}
return scene;
};
/***/ }),
/***/ 73224:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var subTypes = __webpack_require__(43028);
var styleTextSelection = (__webpack_require__(26768).styleTextSelection);
module.exports = function select(searchInfo, selectionTester) {
var cd = searchInfo.cd;
var xa = searchInfo.xaxis;
var ya = searchInfo.yaxis;
var selection = [];
var trace = cd[0].trace;
var stash = cd[0].t;
var len = trace._length;
var x = stash.x;
var y = stash.y;
var scene = stash._scene;
var index = stash.index;
if (!scene) return selection;
var hasText = subTypes.hasText(trace);
var hasMarkers = subTypes.hasMarkers(trace);
var hasOnlyLines = !hasMarkers && !hasText;
if (trace.visible !== true || hasOnlyLines) return selection;
var els = [];
var unels = [];
// degenerate polygon does not enable selection
// filter out points by visible scatter ones
if (selectionTester !== false && !selectionTester.degenerate) {
for (var i = 0; i < len; i++) {
if (selectionTester.contains([stash.xpx[i], stash.ypx[i]], false, i, searchInfo)) {
els.push(i);
selection.push({
pointNumber: i,
x: xa.c2d(x[i]),
y: ya.c2d(y[i])
});
} else {
unels.push(i);
}
}
}
if (hasMarkers) {
var scatter2d = scene.scatter2d;
if (!els.length && !unels.length) {
// reset to base styles when clearing
var baseOpts = new Array(scene.count);
baseOpts[index] = scene.markerOptions[index];
scatter2d.update.apply(scatter2d, baseOpts);
} else if (!scene.selectBatch[index].length && !scene.unselectBatch[index].length) {
// set unselected styles on 'context' canvas (if not done already)
var unselOpts = new Array(scene.count);
unselOpts[index] = scene.markerUnselectedOptions[index];
scatter2d.update.apply(scatter2d, unselOpts);
}
}
scene.selectBatch[index] = els;
scene.unselectBatch[index] = unels;
if (hasText) {
styleTextSelection(cd);
}
return selection;
};
/***/ }),
/***/ 75819:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var index = __webpack_require__(64628);
index.plot = __webpack_require__(61608);
module.exports = index;
/***/ }),
/***/ 31512:
/***/ (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 scatterGeoAttrs = __webpack_require__(6096);
var scatterAttrs = __webpack_require__(52904);
var mapboxAttrs = __webpack_require__(5232);
var baseAttrs = __webpack_require__(45464);
var colorScaleAttrs = __webpack_require__(49084);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var mapboxLayoutAtributes = __webpack_require__(5232);
var lineAttrs = scatterGeoAttrs.line;
var markerAttrs = scatterGeoAttrs.marker;
module.exports = overrideAll({
lon: scatterGeoAttrs.lon,
lat: scatterGeoAttrs.lat,
cluster: {
enabled: {
valType: 'boolean'
},
maxzoom: extendFlat({}, mapboxLayoutAtributes.layers.maxzoom, {}),
step: {
valType: 'number',
arrayOk: true,
dflt: -1,
min: -1
},
size: {
valType: 'number',
arrayOk: true,
dflt: 20,
min: 0
},
color: {
valType: 'color',
arrayOk: true
},
opacity: extendFlat({}, markerAttrs.opacity, {
dflt: 1
})
},
// locations
// locationmode
mode: extendFlat({}, scatterAttrs.mode, {
dflt: 'markers'
}),
text: extendFlat({}, scatterAttrs.text, {}),
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['lat', 'lon', 'text']
}),
hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
line: {
color: lineAttrs.color,
width: lineAttrs.width
// TODO
// dash: dash
},
connectgaps: scatterAttrs.connectgaps,
marker: extendFlat({
symbol: {
valType: 'string',
dflt: 'circle',
arrayOk: true
},
angle: {
valType: 'number',
dflt: 'auto',
arrayOk: true
},
allowoverlap: {
valType: 'boolean',
dflt: false
},
opacity: markerAttrs.opacity,
size: markerAttrs.size,
sizeref: markerAttrs.sizeref,
sizemin: markerAttrs.sizemin,
sizemode: markerAttrs.sizemode
}, colorScaleAttrs('marker')
// line
),
fill: scatterGeoAttrs.fill,
fillcolor: makeFillcolorAttr(),
textfont: mapboxAttrs.layers.symbol.textfont,
textposition: mapboxAttrs.layers.symbol.textposition,
below: {
valType: 'string'
},
selected: {
marker: scatterAttrs.selected.marker
},
unselected: {
marker: scatterAttrs.unselected.marker
},
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['lon', 'lat', 'text', 'name']
}),
hovertemplate: hovertemplateAttrs()
}, 'calc', 'nested');
/***/ }),
/***/ 79732:
/***/ (function(module) {
"use strict";
// Must use one of the following fonts as the family, else default to 'Open Sans Regular'
// See https://github.com/openmaptiles/fonts/blob/gh-pages/fontstacks.json
var supportedFonts = ['Metropolis Black Italic', 'Metropolis Black', 'Metropolis Bold Italic', 'Metropolis Bold', 'Metropolis Extra Bold Italic', 'Metropolis Extra Bold', 'Metropolis Extra Light Italic', 'Metropolis Extra Light', 'Metropolis Light Italic', 'Metropolis Light', 'Metropolis Medium Italic', 'Metropolis Medium', 'Metropolis Regular Italic', 'Metropolis Regular', 'Metropolis Semi Bold Italic', 'Metropolis Semi Bold', 'Metropolis Thin Italic', 'Metropolis Thin', 'Open Sans Bold Italic', 'Open Sans Bold', 'Open Sans Extrabold Italic', 'Open Sans Extrabold', 'Open Sans Italic', 'Open Sans Light Italic', 'Open Sans Light', 'Open Sans Regular', 'Open Sans Semibold Italic', 'Open Sans Semibold', 'Klokantech Noto Sans Bold', 'Klokantech Noto Sans CJK Bold', 'Klokantech Noto Sans CJK Regular', 'Klokantech Noto Sans Italic', 'Klokantech Noto Sans Regular'];
module.exports = {
isSupportedFont: function (a) {
return supportedFonts.indexOf(a) !== -1;
}
};
/***/ }),
/***/ 59392:
/***/ (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);
var geoJsonUtils = __webpack_require__(44808);
var Colorscale = __webpack_require__(8932);
var Drawing = __webpack_require__(43616);
var makeBubbleSizeFn = __webpack_require__(7152);
var subTypes = __webpack_require__(43028);
var isSupportedFont = (__webpack_require__(79732).isSupportedFont);
var convertTextOpts = __webpack_require__(89032);
var appendArrayPointValue = (__webpack_require__(10624).appendArrayPointValue);
var NEWLINES = (__webpack_require__(72736).NEWLINES);
var BR_TAG_ALL = (__webpack_require__(72736).BR_TAG_ALL);
module.exports = function convert(gd, calcTrace) {
var trace = calcTrace[0].trace;
var isVisible = trace.visible === true && trace._length !== 0;
var hasFill = trace.fill !== 'none';
var hasLines = subTypes.hasLines(trace);
var hasMarkers = subTypes.hasMarkers(trace);
var hasText = subTypes.hasText(trace);
var hasCircles = hasMarkers && trace.marker.symbol === 'circle';
var hasSymbols = hasMarkers && trace.marker.symbol !== 'circle';
var hasCluster = trace.cluster && trace.cluster.enabled;
var fill = initContainer('fill');
var line = initContainer('line');
var circle = initContainer('circle');
var symbol = initContainer('symbol');
var opts = {
fill: fill,
line: line,
circle: circle,
symbol: symbol
};
// early return if not visible or placeholder
if (!isVisible) return opts;
// fill layer and line layer use the same coords
var lineCoords;
if (hasFill || hasLines) {
lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);
}
if (hasFill) {
fill.geojson = geoJsonUtils.makePolygon(lineCoords);
fill.layout.visibility = 'visible';
Lib.extendFlat(fill.paint, {
'fill-color': trace.fillcolor
});
}
if (hasLines) {
line.geojson = geoJsonUtils.makeLine(lineCoords);
line.layout.visibility = 'visible';
Lib.extendFlat(line.paint, {
'line-width': trace.line.width,
'line-color': trace.line.color,
'line-opacity': trace.opacity
});
// TODO convert line.dash into line-dasharray
}
if (hasCircles) {
var circleOpts = makeCircleOpts(calcTrace);
circle.geojson = circleOpts.geojson;
circle.layout.visibility = 'visible';
if (hasCluster) {
circle.filter = ['!', ['has', 'point_count']];
opts.cluster = {
type: 'circle',
filter: ['has', 'point_count'],
layout: {
visibility: 'visible'
},
paint: {
'circle-color': arrayifyAttribute(trace.cluster.color, trace.cluster.step),
'circle-radius': arrayifyAttribute(trace.cluster.size, trace.cluster.step),
'circle-opacity': arrayifyAttribute(trace.cluster.opacity, trace.cluster.step)
}
};
opts.clusterCount = {
type: 'symbol',
filter: ['has', 'point_count'],
paint: {},
layout: {
'text-field': '{point_count_abbreviated}',
'text-font': getTextFont(trace),
'text-size': 12
}
};
}
Lib.extendFlat(circle.paint, {
'circle-color': circleOpts.mcc,
'circle-radius': circleOpts.mrc,
'circle-opacity': circleOpts.mo
});
}
if (hasCircles && hasCluster) {
circle.filter = ['!', ['has', 'point_count']];
}
if (hasSymbols || hasText) {
symbol.geojson = makeSymbolGeoJSON(calcTrace, gd);
Lib.extendFlat(symbol.layout, {
visibility: 'visible',
'icon-image': '{symbol}-15',
'text-field': '{text}'
});
if (hasSymbols) {
Lib.extendFlat(symbol.layout, {
'icon-size': trace.marker.size / 10
});
if ('angle' in trace.marker && trace.marker.angle !== 'auto') {
Lib.extendFlat(symbol.layout, {
// unfortunately cant use {angle} do to this issue:
// https://github.com/mapbox/mapbox-gl-js/issues/873
'icon-rotate': {
type: 'identity',
property: 'angle'
},
'icon-rotation-alignment': 'map'
});
}
symbol.layout['icon-allow-overlap'] = trace.marker.allowoverlap;
Lib.extendFlat(symbol.paint, {
'icon-opacity': trace.opacity * trace.marker.opacity,
// TODO does not work ??
'icon-color': trace.marker.color
});
}
if (hasText) {
var iconSize = (trace.marker || {}).size;
var textOpts = convertTextOpts(trace.textposition, iconSize);
// all data-driven below !!
Lib.extendFlat(symbol.layout, {
'text-size': trace.textfont.size,
'text-anchor': textOpts.anchor,
'text-offset': textOpts.offset,
'text-font': getTextFont(trace)
});
Lib.extendFlat(symbol.paint, {
'text-color': trace.textfont.color,
'text-opacity': trace.opacity
});
}
}
return opts;
};
function initContainer(type) {
return {
type: type,
geojson: geoJsonUtils.makeBlank(),
layout: {
visibility: 'none'
},
filter: null,
paint: {}
};
}
function makeCircleOpts(calcTrace) {
var trace = calcTrace[0].trace;
var marker = trace.marker;
var selectedpoints = trace.selectedpoints;
var arrayColor = Lib.isArrayOrTypedArray(marker.color);
var arraySize = Lib.isArrayOrTypedArray(marker.size);
var arrayOpacity = Lib.isArrayOrTypedArray(marker.opacity);
var i;
function addTraceOpacity(o) {
return trace.opacity * o;
}
function size2radius(s) {
return s / 2;
}
var colorFn;
if (arrayColor) {
if (Colorscale.hasColorscale(trace, 'marker')) {
colorFn = Colorscale.makeColorScaleFuncFromTrace(marker);
} else {
colorFn = Lib.identity;
}
}
var sizeFn;
if (arraySize) {
sizeFn = makeBubbleSizeFn(trace);
}
var opacityFn;
if (arrayOpacity) {
opacityFn = function (mo) {
var mo2 = isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
return addTraceOpacity(mo2);
};
}
var features = [];
for (i = 0; i < calcTrace.length; i++) {
var calcPt = calcTrace[i];
var lonlat = calcPt.lonlat;
if (isBADNUM(lonlat)) continue;
var props = {};
if (colorFn) props.mcc = calcPt.mcc = colorFn(calcPt.mc);
if (sizeFn) props.mrc = calcPt.mrc = sizeFn(calcPt.ms);
if (opacityFn) props.mo = opacityFn(calcPt.mo);
if (selectedpoints) props.selected = calcPt.selected || 0;
features.push({
type: 'Feature',
id: i + 1,
geometry: {
type: 'Point',
coordinates: lonlat
},
properties: props
});
}
var fns;
if (selectedpoints) {
fns = Drawing.makeSelectedPointStyleFns(trace);
for (i = 0; i < features.length; i++) {
var d = features[i].properties;
if (fns.selectedOpacityFn) {
d.mo = addTraceOpacity(fns.selectedOpacityFn(d));
}
if (fns.selectedColorFn) {
d.mcc = fns.selectedColorFn(d);
}
if (fns.selectedSizeFn) {
d.mrc = fns.selectedSizeFn(d);
}
}
}
return {
geojson: {
type: 'FeatureCollection',
features: features
},
mcc: arrayColor || fns && fns.selectedColorFn ? {
type: 'identity',
property: 'mcc'
} : marker.color,
mrc: arraySize || fns && fns.selectedSizeFn ? {
type: 'identity',
property: 'mrc'
} : size2radius(marker.size),
mo: arrayOpacity || fns && fns.selectedOpacityFn ? {
type: 'identity',
property: 'mo'
} : addTraceOpacity(marker.opacity)
};
}
function makeSymbolGeoJSON(calcTrace, gd) {
var fullLayout = gd._fullLayout;
var trace = calcTrace[0].trace;
var marker = trace.marker || {};
var symbol = marker.symbol;
var angle = marker.angle;
var fillSymbol = symbol !== 'circle' ? getFillFunc(symbol) : blankFillFunc;
var fillAngle = angle !== 'auto' ? getFillFunc(angle, true) : blankFillFunc;
var fillText = subTypes.hasText(trace) ? getFillFunc(trace.text) : blankFillFunc;
var features = [];
for (var i = 0; i < calcTrace.length; i++) {
var calcPt = calcTrace[i];
if (isBADNUM(calcPt.lonlat)) continue;
var texttemplate = trace.texttemplate;
var text;
if (texttemplate) {
var tt = Array.isArray(texttemplate) ? texttemplate[i] || '' : texttemplate;
var labels = trace._module.formatLabels(calcPt, trace, fullLayout);
var pointValues = {};
appendArrayPointValue(pointValues, trace, calcPt.i);
var meta = trace._meta || {};
text = Lib.texttemplateString(tt, labels, fullLayout._d3locale, pointValues, calcPt, meta);
} else {
text = fillText(i);
}
if (text) {
text = text.replace(NEWLINES, '').replace(BR_TAG_ALL, '\n');
}
features.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: calcPt.lonlat
},
properties: {
symbol: fillSymbol(i),
angle: fillAngle(i),
text: text
}
});
}
return {
type: 'FeatureCollection',
features: features
};
}
function getFillFunc(attr, numeric) {
if (Lib.isArrayOrTypedArray(attr)) {
if (numeric) {
return function (i) {
return isNumeric(attr[i]) ? +attr[i] : 0;
};
}
return function (i) {
return attr[i];
};
} else if (attr) {
return function () {
return attr;
};
} else {
return blankFillFunc;
}
}
function blankFillFunc() {
return '';
}
// only need to check lon (OR lat)
function isBADNUM(lonlat) {
return lonlat[0] === BADNUM;
}
function arrayifyAttribute(values, step) {
var newAttribute;
if (Lib.isArrayOrTypedArray(values) && Lib.isArrayOrTypedArray(step)) {
newAttribute = ['step', ['get', 'point_count'], values[0]];
for (var idx = 1; idx < values.length; idx++) {
newAttribute.push(step[idx - 1], values[idx]);
}
} else {
newAttribute = values;
}
return newAttribute;
}
function getTextFont(trace) {
var font = trace.textfont;
var family = font.family;
var style = font.style;
var weight = font.weight;
var parts = family.split(' ');
var isItalic = parts[parts.length - 1] === 'Italic';
if (isItalic) parts.pop();
isItalic = isItalic || style === 'italic';
var str = parts.join(' ');
if (weight === 'bold' && parts.indexOf('Bold') === -1) {
str += ' Bold';
} else if (weight <= 1000) {
// numeric font-weight
// See supportedFonts
if (parts[0] === 'Metropolis') {
str = 'Metropolis';
if (weight > 850) str += ' Black';else if (weight > 750) str += ' Extra Bold';else if (weight > 650) str += ' Bold';else if (weight > 550) str += ' Semi Bold';else if (weight > 450) str += ' Medium';else if (weight > 350) str += ' Regular';else if (weight > 250) str += ' Light';else if (weight > 150) str += ' Extra Light';else str += ' Thin';
} else if (parts.slice(0, 2).join(' ') === 'Open Sans') {
str = 'Open Sans';
if (weight > 750) str += ' Extrabold';else if (weight > 650) str += ' Bold';else if (weight > 550) str += ' Semibold';else if (weight > 350) str += ' Regular';else str += ' Light';
} else if (parts.slice(0, 3).join(' ') === 'Klokantech Noto Sans') {
str = 'Klokantech Noto Sans';
if (parts[3] === 'CJK') str += ' CJK';
str += weight > 500 ? ' Bold' : ' Regular';
}
}
if (isItalic) str += ' Italic';
if (str === 'Open Sans Regular Italic') str = 'Open Sans Italic';else if (str === 'Open Sans Regular Bold') str = 'Open Sans Bold';else if (str === 'Open Sans Regular Bold Italic') str = 'Open Sans Bold Italic';else if (str === 'Klokantech Noto Sans Regular Italic') str = 'Klokantech Noto Sans Italic';
// Ensure the result is a supported font
if (!isSupportedFont(str)) {
str = family;
}
var textFont = str.split(', ');
return textFont;
}
/***/ }),
/***/ 15752:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var subTypes = __webpack_require__(43028);
var handleMarkerDefaults = __webpack_require__(74428);
var handleLineDefaults = __webpack_require__(66828);
var handleTextDefaults = __webpack_require__(124);
var handleFillColorDefaults = __webpack_require__(70840);
var attributes = __webpack_require__(31512);
var isSupportedFont = (__webpack_require__(79732).isSupportedFont);
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);
}
var len = handleLonLatDefaults(traceIn, traceOut, coerce);
if (!len) {
traceOut.visible = false;
return;
}
coerce('text');
coerce('texttemplate');
coerce('hovertext');
coerce('hovertemplate');
coerce('mode');
coerce('below');
if (subTypes.hasMarkers(traceOut)) {
handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
noLine: true,
noAngle: true
});
coerce('marker.allowoverlap');
coerce('marker.angle');
// array marker.size and marker.color are only supported with circles
var marker = traceOut.marker;
if (marker.symbol !== 'circle') {
if (Lib.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0];
if (Lib.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0];
}
}
if (subTypes.hasLines(traceOut)) {
handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
noDash: true
});
coerce('connectgaps');
}
var clusterMaxzoom = coerce2('cluster.maxzoom');
var clusterStep = coerce2('cluster.step');
var clusterColor = coerce2('cluster.color', traceOut.marker && traceOut.marker.color || defaultColor);
var clusterSize = coerce2('cluster.size');
var clusterOpacity = coerce2('cluster.opacity');
var clusterEnabledDflt = clusterMaxzoom !== false || clusterStep !== false || clusterColor !== false || clusterSize !== false || clusterOpacity !== false;
var clusterEnabled = coerce('cluster.enabled', clusterEnabledDflt);
if (clusterEnabled || subTypes.hasText(traceOut)) {
var layoutFontFamily = layout.font.family;
handleTextDefaults(traceIn, traceOut, layout, coerce, {
noSelect: true,
noFontVariant: true,
noFontShadow: true,
noFontLineposition: true,
noFontTextcase: true,
font: {
family: isSupportedFont(layoutFontFamily) ? layoutFontFamily : 'Open Sans Regular',
weight: layout.font.weight,
style: layout.font.style,
size: layout.font.size,
color: layout.font.color
}
});
}
coerce('fill');
if (traceOut.fill !== 'none') {
handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
}
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
function handleLonLatDefaults(traceIn, traceOut, coerce) {
var lon = coerce('lon') || [];
var lat = coerce('lat') || [];
var len = Math.min(lon.length, lat.length);
traceOut._length = len;
return len;
}
/***/ }),
/***/ 37920:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt) {
out.lon = pt.lon;
out.lat = pt.lat;
return out;
};
/***/ }),
/***/ 11960:
/***/ (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;
var ax = subplot.mockAxis;
var lonlat = cdi.lonlat;
labels.lonLabel = Axes.tickText(ax, ax.c2l(lonlat[0]), true).text;
labels.latLabel = Axes.tickText(ax, ax.c2l(lonlat[1]), true).text;
return labels;
};
/***/ }),
/***/ 63312:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Fx = __webpack_require__(93024);
var Lib = __webpack_require__(3400);
var getTraceColor = __webpack_require__(44928);
var fillText = Lib.fillText;
var BADNUM = (__webpack_require__(39032).BADNUM);
var LAYER_PREFIX = (__webpack_require__(47552).traceLayerPrefix);
function hoverPoints(pointData, xval, yval) {
var cd = pointData.cd;
var trace = cd[0].trace;
var xa = pointData.xa;
var ya = pointData.ya;
var subplot = pointData.subplot;
var clusteredPointsIds = [];
var layer = LAYER_PREFIX + trace.uid + '-circle';
var hasCluster = trace.cluster && trace.cluster.enabled;
if (hasCluster) {
var elems = subplot.map.queryRenderedFeatures(null, {
layers: [layer]
});
clusteredPointsIds = elems.map(function (elem) {
return elem.id;
});
}
// compute winding number about [-180, 180] globe
var winding = xval >= 0 ? Math.floor((xval + 180) / 360) : Math.ceil((xval - 180) / 360);
// shift longitude to [-180, 180] to determine closest point
var lonShift = winding * 360;
var xval2 = xval - lonShift;
function distFn(d) {
var lonlat = d.lonlat;
if (lonlat[0] === BADNUM) return Infinity;
if (hasCluster && clusteredPointsIds.indexOf(d.i + 1) === -1) return Infinity;
var lon = Lib.modHalf(lonlat[0], 360);
var lat = lonlat[1];
var pt = subplot.project([lon, lat]);
var dx = pt.x - xa.c2p([xval2, lat]);
var dy = pt.y - ya.c2p([lon, yval]);
var rad = Math.max(3, d.mrc || 0);
return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad);
}
Fx.getClosest(cd, distFn, pointData);
// skip the rest (for this trace) if we didn't find a close point
if (pointData.index === false) return;
var di = cd[pointData.index];
var lonlat = di.lonlat;
var lonlatShifted = [Lib.modHalf(lonlat[0], 360) + lonShift, lonlat[1]];
// shift labels back to original winded globe
var xc = xa.c2p(lonlatShifted);
var yc = ya.c2p(lonlatShifted);
var rad = di.mrc || 1;
pointData.x0 = xc - rad;
pointData.x1 = xc + rad;
pointData.y0 = yc - rad;
pointData.y1 = yc + rad;
var fullLayout = {};
fullLayout[trace.subplot] = {
_subplot: subplot
};
var labels = trace._module.formatLabels(di, trace, fullLayout);
pointData.lonLabel = labels.lonLabel;
pointData.latLabel = labels.latLabel;
pointData.color = getTraceColor(trace, di);
pointData.extraText = getExtraText(trace, di, cd[0].t.labels);
pointData.hovertemplate = trace.hovertemplate;
return [pointData];
}
function getExtraText(trace, di, labels) {
if (trace.hovertemplate) return;
var hoverinfo = di.hi || trace.hoverinfo;
var parts = hoverinfo.split('+');
var isAll = parts.indexOf('all') !== -1;
var hasLon = parts.indexOf('lon') !== -1;
var hasLat = parts.indexOf('lat') !== -1;
var lonlat = di.lonlat;
var text = [];
// TODO should we use a mock axis to format hover?
// If so, we'll need to make precision be zoom-level dependent
function format(v) {
return v + '\u00B0';
}
if (isAll || hasLon && hasLat) {
text.push('(' + format(lonlat[1]) + ', ' + format(lonlat[0]) + ')');
} else if (hasLon) {
text.push(labels.lon + format(lonlat[0]));
} else if (hasLat) {
text.push(labels.lat + format(lonlat[1]));
}
if (isAll || parts.indexOf('text') !== -1) {
fillText(di, trace, text);
}
return text.join(' ');
}
module.exports = {
hoverPoints: hoverPoints,
getExtraText: getExtraText
};
/***/ }),
/***/ 11572:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(31512),
supplyDefaults: __webpack_require__(15752),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(11960),
calc: __webpack_require__(25212),
plot: __webpack_require__(9660),
hoverPoints: (__webpack_require__(63312).hoverPoints),
eventData: __webpack_require__(37920),
selectPoints: __webpack_require__(404),
styleOnSelect: function (_, cd) {
if (cd) {
var trace = cd[0].trace;
trace._glTrace.update(cd);
}
},
moduleType: 'trace',
name: 'scattermapbox',
basePlotModule: __webpack_require__(33688),
categories: ['mapbox', 'gl', 'symbols', 'showLegend', 'scatter-like'],
meta: {}
};
/***/ }),
/***/ 9660:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var convert = __webpack_require__(59392);
var LAYER_PREFIX = (__webpack_require__(47552).traceLayerPrefix);
var ORDER = {
cluster: ['cluster', 'clusterCount', 'circle'],
nonCluster: ['fill', 'line', 'circle', 'symbol']
};
function ScatterMapbox(subplot, uid, clusterEnabled, isHidden) {
this.type = 'scattermapbox';
this.subplot = subplot;
this.uid = uid;
this.clusterEnabled = clusterEnabled;
this.isHidden = isHidden;
this.sourceIds = {
fill: 'source-' + uid + '-fill',
line: 'source-' + uid + '-line',
circle: 'source-' + uid + '-circle',
symbol: 'source-' + uid + '-symbol',
cluster: 'source-' + uid + '-circle',
clusterCount: 'source-' + uid + '-circle'
};
this.layerIds = {
fill: LAYER_PREFIX + uid + '-fill',
line: LAYER_PREFIX + uid + '-line',
circle: LAYER_PREFIX + uid + '-circle',
symbol: LAYER_PREFIX + uid + '-symbol',
cluster: LAYER_PREFIX + uid + '-cluster',
clusterCount: LAYER_PREFIX + uid + '-cluster-count'
};
// We could merge the 'fill' source with the 'line' source and
// the 'circle' source with the 'symbol' source if ever having
// for up-to 4 sources per 'scattermapbox' traces becomes a problem.
// previous 'below' value,
// need this to update it properly
this.below = null;
}
var proto = ScatterMapbox.prototype;
proto.addSource = function (k, opts, cluster) {
var sourceOpts = {
type: 'geojson',
data: opts.geojson
};
if (cluster && cluster.enabled) {
Lib.extendFlat(sourceOpts, {
cluster: true,
clusterMaxZoom: cluster.maxzoom
});
}
var isSourceExists = this.subplot.map.getSource(this.sourceIds[k]);
if (isSourceExists) {
isSourceExists.setData(opts.geojson);
} else {
this.subplot.map.addSource(this.sourceIds[k], sourceOpts);
}
};
proto.setSourceData = function (k, opts) {
this.subplot.map.getSource(this.sourceIds[k]).setData(opts.geojson);
};
proto.addLayer = function (k, opts, below) {
var source = {
type: opts.type,
id: this.layerIds[k],
source: this.sourceIds[k],
layout: opts.layout,
paint: opts.paint
};
if (opts.filter) {
source.filter = opts.filter;
}
var currentLayerId = this.layerIds[k];
var layerExist;
var layers = this.subplot.getMapLayers();
for (var i = 0; i < layers.length; i++) {
if (layers[i].id === currentLayerId) {
layerExist = true;
break;
}
}
if (layerExist) {
this.subplot.setOptions(currentLayerId, 'setLayoutProperty', source.layout);
if (source.layout.visibility === 'visible') {
this.subplot.setOptions(currentLayerId, 'setPaintProperty', source.paint);
}
} else {
this.subplot.addLayer(source, below);
}
};
proto.update = function update(calcTrace) {
var trace = calcTrace[0].trace;
var subplot = this.subplot;
var map = subplot.map;
var optsAll = convert(subplot.gd, calcTrace);
var below = subplot.belowLookup['trace-' + this.uid];
var hasCluster = !!(trace.cluster && trace.cluster.enabled);
var hadCluster = !!this.clusterEnabled;
var lThis = this;
function addCluster(noSource) {
if (!noSource) lThis.addSource('circle', optsAll.circle, trace.cluster);
var order = ORDER.cluster;
for (var i = 0; i < order.length; i++) {
var k = order[i];
var opts = optsAll[k];
lThis.addLayer(k, opts, below);
}
}
function removeCluster(noSource) {
var order = ORDER.cluster;
for (var i = order.length - 1; i >= 0; i--) {
var k = order[i];
map.removeLayer(lThis.layerIds[k]);
}
if (!noSource) map.removeSource(lThis.sourceIds.circle);
}
function addNonCluster(noSource) {
var order = ORDER.nonCluster;
for (var i = 0; i < order.length; i++) {
var k = order[i];
var opts = optsAll[k];
if (!noSource) lThis.addSource(k, opts);
lThis.addLayer(k, opts, below);
}
}
function removeNonCluster(noSource) {
var order = ORDER.nonCluster;
for (var i = order.length - 1; i >= 0; i--) {
var k = order[i];
map.removeLayer(lThis.layerIds[k]);
if (!noSource) map.removeSource(lThis.sourceIds[k]);
}
}
function remove(noSource) {
if (hadCluster) removeCluster(noSource);else removeNonCluster(noSource);
}
function add(noSource) {
if (hasCluster) addCluster(noSource);else addNonCluster(noSource);
}
function repaint() {
var order = hasCluster ? ORDER.cluster : ORDER.nonCluster;
for (var i = 0; i < order.length; i++) {
var k = order[i];
var opts = optsAll[k];
if (!opts) continue;
subplot.setOptions(lThis.layerIds[k], 'setLayoutProperty', opts.layout);
if (opts.layout.visibility === 'visible') {
if (k !== 'cluster') {
lThis.setSourceData(k, opts);
}
subplot.setOptions(lThis.layerIds[k], 'setPaintProperty', opts.paint);
}
}
}
var wasHidden = this.isHidden;
var isHidden = trace.visible !== true;
if (isHidden) {
if (!wasHidden) remove();
} else if (wasHidden) {
if (!isHidden) add();
} else if (hadCluster !== hasCluster) {
remove();
add();
} else if (this.below !== below) {
remove(true);
add(true);
repaint();
} else {
repaint();
}
this.clusterEnabled = hasCluster;
this.isHidden = isHidden;
this.below = below;
// link ref for quick update during selections
calcTrace[0].trace._glTrace = this;
};
proto.dispose = function dispose() {
var map = this.subplot.map;
var order = this.clusterEnabled ? ORDER.cluster : ORDER.nonCluster;
for (var i = order.length - 1; i >= 0; i--) {
var k = order[i];
map.removeLayer(this.layerIds[k]);
map.removeSource(this.sourceIds[k]);
}
};
module.exports = function createScatterMapbox(subplot, calcTrace) {
var trace = calcTrace[0].trace;
var hasCluster = trace.cluster && trace.cluster.enabled;
var isHidden = trace.visible !== true;
var scatterMapbox = new ScatterMapbox(subplot, trace.uid, hasCluster, isHidden);
var optsAll = convert(subplot.gd, calcTrace);
var below = scatterMapbox.below = subplot.belowLookup['trace-' + trace.uid];
var i, k, opts;
if (hasCluster) {
scatterMapbox.addSource('circle', optsAll.circle, trace.cluster);
for (i = 0; i < ORDER.cluster.length; i++) {
k = ORDER.cluster[i];
opts = optsAll[k];
scatterMapbox.addLayer(k, opts, below);
}
} else {
for (i = 0; i < ORDER.nonCluster.length; i++) {
k = ORDER.nonCluster[i];
opts = optsAll[k];
scatterMapbox.addSource(k, opts, trace.cluster);
scatterMapbox.addLayer(k, opts, below);
}
}
// link ref for quick update during selections
calcTrace[0].trace._glTrace = scatterMapbox;
return scatterMapbox;
};
/***/ }),
/***/ 404:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var subtypes = __webpack_require__(43028);
var BADNUM = (__webpack_require__(39032).BADNUM);
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;
if (!subtypes.hasMarkers(trace)) return [];
if (selectionTester === false) {
for (i = 0; i < cd.length; i++) {
cd[i].selected = 0;
}
} else {
for (i = 0; i < cd.length; i++) {
var di = cd[i];
var lonlat = di.lonlat;
if (lonlat[0] !== BADNUM) {
var lonlat2 = [Lib.modHalf(lonlat[0], 360), lonlat[1]];
var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)];
if (selectionTester.contains(xy, null, i, searchInfo)) {
selection.push({
pointNumber: i,
lon: lonlat[0],
lat: lonlat[1]
});
di.selected = 1;
} else {
di.selected = 0;
}
}
}
}
return selection;
};
/***/ }),
/***/ 8319:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var extendFlat = (__webpack_require__(92880).extendFlat);
var makeFillcolorAttr = __webpack_require__(98304);
var scatterAttrs = __webpack_require__(52904);
var baseAttrs = __webpack_require__(45464);
var lineAttrs = scatterAttrs.line;
module.exports = {
mode: scatterAttrs.mode,
r: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
theta: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
r0: {
valType: 'any',
dflt: 0,
editType: 'calc+clearAxisTypes'
},
dr: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
theta0: {
valType: 'any',
dflt: 0,
editType: 'calc+clearAxisTypes'
},
dtheta: {
valType: 'number',
editType: 'calc'
},
thetaunit: {
valType: 'enumerated',
values: ['radians', 'degrees', 'gradians'],
dflt: 'degrees',
editType: 'calc+clearAxisTypes'
},
text: scatterAttrs.text,
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['r', 'theta', 'text']
}),
hovertext: scatterAttrs.hovertext,
line: {
color: lineAttrs.color,
width: lineAttrs.width,
dash: lineAttrs.dash,
backoff: lineAttrs.backoff,
shape: extendFlat({}, lineAttrs.shape, {
values: ['linear', 'spline']
}),
smoothing: lineAttrs.smoothing,
editType: 'calc'
},
connectgaps: scatterAttrs.connectgaps,
marker: scatterAttrs.marker,
cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {
dflt: false
}),
textposition: scatterAttrs.textposition,
textfont: scatterAttrs.textfont,
fill: extendFlat({}, scatterAttrs.fill, {
values: ['none', 'toself', 'tonext'],
dflt: 'none'
}),
fillcolor: makeFillcolorAttr(),
// TODO error bars
// https://stackoverflow.com/a/26597487/4068492
// error_x (error_r, error_theta)
// error_y
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['r', 'theta', 'text', 'name']
}),
hoveron: scatterAttrs.hoveron,
hovertemplate: hovertemplateAttrs(),
selected: scatterAttrs.selected,
unselected: scatterAttrs.unselected
};
/***/ }),
/***/ 58320:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var BADNUM = (__webpack_require__(39032).BADNUM);
var Axes = __webpack_require__(54460);
var calcColorscale = __webpack_require__(90136);
var arraysToCalcdata = __webpack_require__(20148);
var calcSelection = __webpack_require__(4500);
var calcMarkerSize = (__webpack_require__(16356).calcMarkerSize);
module.exports = function calc(gd, trace) {
var fullLayout = gd._fullLayout;
var subplotId = trace.subplot;
var radialAxis = fullLayout[subplotId].radialaxis;
var angularAxis = fullLayout[subplotId].angularaxis;
var rArray = radialAxis.makeCalcdata(trace, 'r');
var thetaArray = angularAxis.makeCalcdata(trace, 'theta');
var len = trace._length;
var cd = new Array(len);
for (var i = 0; i < len; i++) {
var r = rArray[i];
var theta = thetaArray[i];
var cdi = cd[i] = {};
if (isNumeric(r) && isNumeric(theta)) {
cdi.r = r;
cdi.theta = theta;
} else {
cdi.r = BADNUM;
}
}
var ppad = calcMarkerSize(trace, len);
trace._extremes.x = Axes.findExtremes(radialAxis, rArray, {
ppad: ppad
});
calcColorscale(gd, trace);
arraysToCalcdata(cd, trace);
calcSelection(cd, trace);
return cd;
};
/***/ }),
/***/ 85968:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
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 PTS_LINESONLY = (__webpack_require__(88200).PTS_LINESONLY);
var attributes = __webpack_require__(8319);
function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
if (!len) {
traceOut.visible = false;
return;
}
coerce('thetaunit');
coerce('mode', len < PTS_LINESONLY ? 'lines+markers' : 'lines');
coerce('text');
coerce('hovertext');
if (traceOut.hoveron !== 'fills') coerce('hovertemplate');
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);
}
function handleRThetaDefaults(traceIn, traceOut, layout, coerce) {
var r = coerce('r');
var theta = coerce('theta');
// TODO: handle this case outside supply defaults step
if (Lib.isTypedArray(r)) {
traceOut.r = r = Array.from(r);
}
if (Lib.isTypedArray(theta)) {
traceOut.theta = theta = Array.from(theta);
}
var len;
if (r) {
if (theta) {
len = Math.min(r.length, theta.length);
} else {
len = r.length;
coerce('theta0');
coerce('dtheta');
}
} else {
if (!theta) return 0;
len = traceOut.theta.length;
coerce('r0');
coerce('dr');
}
traceOut._length = len;
return len;
}
module.exports = {
handleRThetaDefaults: handleRThetaDefaults,
supplyDefaults: supplyDefaults
};
/***/ }),
/***/ 22852:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
module.exports = function formatLabels(cdi, trace, fullLayout) {
var labels = {};
var subplot = fullLayout[trace.subplot]._subplot;
var radialAxis;
var angularAxis;
// for scatterpolargl texttemplate, _subplot is NOT defined, this takes part during the convert step
// TODO we should consider moving the texttemplate formatting logic to the plot step
if (!subplot) {
subplot = fullLayout[trace.subplot];
radialAxis = subplot.radialaxis;
angularAxis = subplot.angularaxis;
} else {
radialAxis = subplot.radialAxis;
angularAxis = subplot.angularAxis;
}
var rVal = radialAxis.c2l(cdi.r);
labels.rLabel = Axes.tickText(radialAxis, rVal, true).text;
// N.B here the ° sign is part of the formatted value for thetaunit:'degrees'
var thetaVal = angularAxis.thetaunit === 'degrees' ? Lib.rad2deg(cdi.theta) : cdi.theta;
labels.thetaLabel = Axes.tickText(angularAxis, thetaVal, true).text;
return labels;
};
/***/ }),
/***/ 8504:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterHover = __webpack_require__(98723);
function hoverPoints(pointData, xval, yval, hovermode) {
var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
if (!scatterPointData || scatterPointData[0].index === false) return;
var newPointData = scatterPointData[0];
// hovering on fill case
if (newPointData.index === undefined) {
return scatterPointData;
}
var subplot = pointData.subplot;
var cdi = newPointData.cd[newPointData.index];
var trace = newPointData.trace;
if (!subplot.isPtInside(cdi)) return;
newPointData.xLabelVal = undefined;
newPointData.yLabelVal = undefined;
makeHoverPointText(cdi, trace, subplot, newPointData);
newPointData.hovertemplate = trace.hovertemplate;
return scatterPointData;
}
function makeHoverPointText(cdi, trace, subplot, pointData) {
var radialAxis = subplot.radialAxis;
var angularAxis = subplot.angularAxis;
radialAxis._hovertitle = 'r';
angularAxis._hovertitle = 'θ';
var fullLayout = {};
fullLayout[trace.subplot] = {
_subplot: subplot
};
var labels = trace._module.formatLabels(cdi, trace, fullLayout);
pointData.rLabel = labels.rLabel;
pointData.thetaLabel = labels.thetaLabel;
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 = ['r', 'theta', 'text'];
if (parts.indexOf('r') !== -1) textPart(radialAxis, pointData.rLabel);
if (parts.indexOf('theta') !== -1) textPart(angularAxis, pointData.thetaLabel);
if (parts.indexOf('text') !== -1 && pointData.text) {
text.push(pointData.text);
delete pointData.text;
}
pointData.extraText = text.join(' ');
}
}
module.exports = {
hoverPoints: hoverPoints,
makeHoverPointText: makeHoverPointText
};
/***/ }),
/***/ 76924:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'scatterpolar',
basePlotModule: __webpack_require__(40872),
categories: ['polar', 'symbols', 'showLegend', 'scatter-like'],
attributes: __webpack_require__(8319),
supplyDefaults: (__webpack_require__(85968).supplyDefaults),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(22852),
calc: __webpack_require__(58320),
plot: __webpack_require__(43456),
style: (__webpack_require__(49224).style),
styleOnSelect: (__webpack_require__(49224).styleOnSelect),
hoverPoints: (__webpack_require__(8504).hoverPoints),
selectPoints: __webpack_require__(91560),
meta: {}
};
/***/ }),
/***/ 43456:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterPlot = __webpack_require__(96504);
var BADNUM = (__webpack_require__(39032).BADNUM);
module.exports = function plot(gd, subplot, moduleCalcData) {
var mlayer = subplot.layers.frontplot.select('g.scatterlayer');
var xa = subplot.xaxis;
var ya = subplot.yaxis;
var plotinfo = {
xaxis: xa,
yaxis: ya,
plot: subplot.framework,
layerClipId: subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null
};
var radialAxis = subplot.radialAxis;
var angularAxis = subplot.angularAxis;
// convert:
// 'c' (r,theta) -> 'geometric' (r,theta) -> (x,y)
for (var i = 0; i < moduleCalcData.length; i++) {
var cdi = moduleCalcData[i];
for (var j = 0; j < cdi.length; j++) {
if (j === 0) {
cdi[0].trace._xA = xa;
cdi[0].trace._yA = ya;
}
var cd = cdi[j];
var r = cd.r;
if (r === BADNUM) {
cd.x = cd.y = BADNUM;
} else {
var rg = radialAxis.c2g(r);
var thetag = angularAxis.c2g(cd.theta);
cd.x = rg * Math.cos(thetag);
cd.y = rg * Math.sin(thetag);
}
}
}
scatterPlot(gd, plotinfo, moduleCalcData, mlayer);
};
/***/ }),
/***/ 24396:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterPolarAttrs = __webpack_require__(8319);
var scatterGlAttrs = __webpack_require__(2876);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
module.exports = {
mode: scatterPolarAttrs.mode,
r: scatterPolarAttrs.r,
theta: scatterPolarAttrs.theta,
r0: scatterPolarAttrs.r0,
dr: scatterPolarAttrs.dr,
theta0: scatterPolarAttrs.theta0,
dtheta: scatterPolarAttrs.dtheta,
thetaunit: scatterPolarAttrs.thetaunit,
text: scatterPolarAttrs.text,
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['r', 'theta', 'text']
}),
hovertext: scatterPolarAttrs.hovertext,
hovertemplate: scatterPolarAttrs.hovertemplate,
line: {
color: scatterGlAttrs.line.color,
width: scatterGlAttrs.line.width,
dash: scatterGlAttrs.line.dash,
editType: 'calc'
},
connectgaps: scatterGlAttrs.connectgaps,
marker: scatterGlAttrs.marker,
// no cliponaxis
fill: scatterGlAttrs.fill,
fillcolor: scatterGlAttrs.fillcolor,
textposition: scatterGlAttrs.textposition,
textfont: scatterGlAttrs.textfont,
hoverinfo: scatterPolarAttrs.hoverinfo,
// no hoveron
selected: scatterPolarAttrs.selected,
unselected: scatterPolarAttrs.unselected
};
/***/ }),
/***/ 27160:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'scatterpolargl',
basePlotModule: __webpack_require__(40872),
categories: ['gl', 'regl', 'polar', 'symbols', 'showLegend', 'scatter-like'],
attributes: __webpack_require__(24396),
supplyDefaults: __webpack_require__(98608),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(94120),
calc: __webpack_require__(66720),
hoverPoints: (__webpack_require__(1600).hoverPoints),
selectPoints: __webpack_require__(73224),
meta: {}
};
/***/ }),
/***/ 66720:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var calcColorscale = __webpack_require__(90136);
var calcMarkerSize = (__webpack_require__(16356).calcMarkerSize);
var convert = __webpack_require__(84236);
var Axes = __webpack_require__(54460);
var TOO_MANY_POINTS = (__webpack_require__(67072).TOO_MANY_POINTS);
module.exports = function calc(gd, trace) {
var fullLayout = gd._fullLayout;
var subplotId = trace.subplot;
var radialAxis = fullLayout[subplotId].radialaxis;
var angularAxis = fullLayout[subplotId].angularaxis;
var rArray = trace._r = radialAxis.makeCalcdata(trace, 'r');
var thetaArray = trace._theta = angularAxis.makeCalcdata(trace, 'theta');
var len = trace._length;
var stash = {};
if (len < rArray.length) rArray = rArray.slice(0, len);
if (len < thetaArray.length) thetaArray = thetaArray.slice(0, len);
stash.r = rArray;
stash.theta = thetaArray;
calcColorscale(gd, trace);
// only compute 'style' options in calc, as position options
// depend on the radial range and must be set in plot
var opts = stash.opts = convert.style(gd, trace);
// For graphs with very large number of points and array marker.size,
// use average marker size instead to speed things up.
var ppad;
if (len < TOO_MANY_POINTS) {
ppad = calcMarkerSize(trace, len);
} else if (opts.marker) {
ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3));
}
trace._extremes.x = Axes.findExtremes(radialAxis, rArray, {
ppad: ppad
});
return [{
x: false,
y: false,
t: stash,
trace: trace
}];
};
/***/ }),
/***/ 98608:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var subTypes = __webpack_require__(43028);
var handleRThetaDefaults = (__webpack_require__(85968).handleRThetaDefaults);
var handleMarkerDefaults = __webpack_require__(74428);
var handleLineDefaults = __webpack_require__(66828);
var handleTextDefaults = __webpack_require__(124);
var handleFillColorDefaults = __webpack_require__(70840);
var PTS_LINESONLY = (__webpack_require__(88200).PTS_LINESONLY);
var attributes = __webpack_require__(24396);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
if (!len) {
traceOut.visible = false;
return;
}
coerce('thetaunit');
coerce('mode', len < PTS_LINESONLY ? 'lines+markers' : 'lines');
coerce('text');
coerce('hovertext');
if (traceOut.hoveron !== 'fills') coerce('hovertemplate');
if (subTypes.hasMarkers(traceOut)) {
handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
noAngleRef: true,
noStandOff: true
});
}
if (subTypes.hasLines(traceOut)) {
handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
coerce('connectgaps');
}
if (subTypes.hasText(traceOut)) {
coerce('texttemplate');
handleTextDefaults(traceIn, traceOut, layout, coerce, {
noFontShadow: true,
noFontLineposition: true,
noFontTextcase: true
});
}
coerce('fill');
if (traceOut.fill !== 'none') {
handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
}
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
/***/ }),
/***/ 94120:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterPolarFormatLabels = __webpack_require__(22852);
module.exports = function formatLabels(cdi, trace, fullLayout) {
var i = cdi.i;
if (!('r' in cdi)) cdi.r = trace._r[i];
if (!('theta' in cdi)) cdi.theta = trace._theta[i];
return scatterPolarFormatLabels(cdi, trace, fullLayout);
};
/***/ }),
/***/ 1600:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hover = __webpack_require__(41272);
var makeHoverPointText = (__webpack_require__(8504).makeHoverPointText);
function hoverPoints(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var stash = cd[0].t;
var rArray = stash.r;
var thetaArray = stash.theta;
var scatterPointData = hover.hoverPoints(pointData, xval, yval, hovermode);
if (!scatterPointData || scatterPointData[0].index === false) return;
var newPointData = scatterPointData[0];
if (newPointData.index === undefined) {
return scatterPointData;
}
var subplot = pointData.subplot;
var cdi = newPointData.cd[newPointData.index];
var trace = newPointData.trace;
// augment pointData with r/theta param
cdi.r = rArray[newPointData.index];
cdi.theta = thetaArray[newPointData.index];
if (!subplot.isPtInside(cdi)) return;
newPointData.xLabelVal = undefined;
newPointData.yLabelVal = undefined;
makeHoverPointText(cdi, trace, subplot, newPointData);
return scatterPointData;
}
module.exports = {
hoverPoints: hoverPoints
};
/***/ }),
/***/ 56512:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var cluster = __webpack_require__(3108);
var isNumeric = __webpack_require__(38248);
var scatterglPlot = __webpack_require__(89876);
var sceneUpdate = __webpack_require__(74588);
var convert = __webpack_require__(84236);
var Lib = __webpack_require__(3400);
var TOO_MANY_POINTS = (__webpack_require__(67072).TOO_MANY_POINTS);
var reglPrecompiled = {};
module.exports = function plot(gd, subplot, cdata) {
if (!cdata.length) return;
var radialAxis = subplot.radialAxis;
var angularAxis = subplot.angularAxis;
var scene = sceneUpdate(gd, subplot);
cdata.forEach(function (cdscatter) {
if (!cdscatter || !cdscatter[0] || !cdscatter[0].trace) return;
var cd = cdscatter[0];
var trace = cd.trace;
var stash = cd.t;
var len = trace._length;
var rArray = stash.r;
var thetaArray = stash.theta;
var opts = stash.opts;
var i;
var subRArray = rArray.slice();
var subThetaArray = thetaArray.slice();
// filter out by range
for (i = 0; i < rArray.length; i++) {
if (!subplot.isPtInside({
r: rArray[i],
theta: thetaArray[i]
})) {
subRArray[i] = NaN;
subThetaArray[i] = NaN;
}
}
var positions = new Array(len * 2);
var x = Array(len);
var y = Array(len);
for (i = 0; i < len; i++) {
var r = subRArray[i];
var xx, yy;
if (isNumeric(r)) {
var rg = radialAxis.c2g(r);
var thetag = angularAxis.c2g(subThetaArray[i], trace.thetaunit);
xx = rg * Math.cos(thetag);
yy = rg * Math.sin(thetag);
} else {
xx = yy = NaN;
}
x[i] = positions[i * 2] = xx;
y[i] = positions[i * 2 + 1] = yy;
}
stash.tree = cluster(positions);
// FIXME: see scattergl.js#109
if (opts.marker && len >= TOO_MANY_POINTS) {
opts.marker.cluster = stash.tree;
}
if (opts.marker) {
opts.markerSel.positions = opts.markerUnsel.positions = opts.marker.positions = positions;
}
if (opts.line && positions.length > 1) {
Lib.extendFlat(opts.line, convert.linePositions(gd, trace, positions));
}
if (opts.text) {
Lib.extendFlat(opts.text, {
positions: positions
}, convert.textPosition(gd, trace, opts.text, opts.marker));
Lib.extendFlat(opts.textSel, {
positions: positions
}, convert.textPosition(gd, trace, opts.text, opts.markerSel));
Lib.extendFlat(opts.textUnsel, {
positions: positions
}, convert.textPosition(gd, trace, opts.text, opts.markerUnsel));
}
if (opts.fill && !scene.fill2d) scene.fill2d = true;
if (opts.marker && !scene.scatter2d) scene.scatter2d = true;
if (opts.line && !scene.line2d) scene.line2d = true;
if (opts.text && !scene.glText) scene.glText = true;
scene.lineOptions.push(opts.line);
scene.fillOptions.push(opts.fill);
scene.markerOptions.push(opts.marker);
scene.markerSelectedOptions.push(opts.markerSel);
scene.markerUnselectedOptions.push(opts.markerUnsel);
scene.textOptions.push(opts.text);
scene.textSelectedOptions.push(opts.textSel);
scene.textUnselectedOptions.push(opts.textUnsel);
scene.selectBatch.push([]);
scene.unselectBatch.push([]);
stash.x = x;
stash.y = y;
stash.rawx = x;
stash.rawy = y;
stash.r = rArray;
stash.theta = thetaArray;
stash.positions = positions;
stash._scene = scene;
stash.index = scene.count;
scene.count++;
});
return scatterglPlot(gd, subplot, cdata);
};
module.exports.reglPrecompiled = reglPrecompiled;
/***/ }),
/***/ 46072:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var plot = __webpack_require__(56512);
var reglPrecompiled = __webpack_require__(51315);
var reglPrecompiledDep = __webpack_require__(28848);
Object.assign(plot.reglPrecompiled, reglPrecompiled);
Object.assign(plot.reglPrecompiled, reglPrecompiledDep);
module.exports = plot;
/***/ }),
/***/ 51315:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var v0 = __webpack_require__(51154);
var v1 = __webpack_require__(81705);
var v2 = __webpack_require__(39760);
var v3 = __webpack_require__(51068);
var v4 = __webpack_require__(81272);
var v5 = __webpack_require__(8756);
var v6 = __webpack_require__(82576);
var v7 = __webpack_require__(29548);
var v8 = __webpack_require__(7108);
var v9 = __webpack_require__(62052);
/* eslint-disable quote-props */
module.exports = {
'3e771157d23b4793771f65d83e6387262ed73d488209157f19a7fa027bddd71b': v0,
'cbf700f001fff25b649fba9c37fa0dc6631c1cdee318ad49473d28ec10dcee81': v1,
'8fad2284703471df7c0e0d0a7b96d983e8c53f6d707dd55d5921c1eab71f6623': v2,
'fe5b6844077cde1bdd7273f4495969fad93500c26a69b62e74ec2664c447bcc7': v3,
'db1b82c68771e7f5012fad1fbdae7ff23b526e58d2995bf6dd2cf30024e0f41d': v4,
'49e82bba439f1d9d441c17ba252d05640bc63fefdf22d1219993633af7730210': v5,
'dbd1cc9126a137a605df67dc0706e55116f04e33b4545a80042031752de5aef5': v6,
'bfc540da96a87fcc039073cb37b45e6b81ef5ee6ef3529d726ceed8336354019': v7,
'6a5d6bd29c15cf7614221b94c3f384df47c2c46fbe4456e8c57b5cd14c84d923': v8,
'8902aff2b23b600f8103bcc84a8af2999d28795208aedadc2db06f921f9c7034': v9
};
/***/ }),
/***/ 58400:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var index = __webpack_require__(27160);
index.plot = __webpack_require__(46072);
module.exports = index;
/***/ }),
/***/ 69496:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var extendFlat = (__webpack_require__(92880).extendFlat);
var makeFillcolorAttr = __webpack_require__(98304);
var scatterAttrs = __webpack_require__(52904);
var baseAttrs = __webpack_require__(45464);
var lineAttrs = scatterAttrs.line;
module.exports = {
mode: scatterAttrs.mode,
real: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
imag: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
text: scatterAttrs.text,
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['real', 'imag', 'text']
}),
hovertext: scatterAttrs.hovertext,
line: {
color: lineAttrs.color,
width: lineAttrs.width,
dash: lineAttrs.dash,
backoff: lineAttrs.backoff,
shape: extendFlat({}, lineAttrs.shape, {
values: ['linear', 'spline']
}),
smoothing: lineAttrs.smoothing,
editType: 'calc'
},
connectgaps: scatterAttrs.connectgaps,
marker: scatterAttrs.marker,
cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {
dflt: false
}),
textposition: scatterAttrs.textposition,
textfont: scatterAttrs.textfont,
fill: extendFlat({}, scatterAttrs.fill, {
values: ['none', 'toself', 'tonext'],
dflt: 'none'
}),
fillcolor: makeFillcolorAttr(),
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['real', 'imag', 'text', 'name']
}),
hoveron: scatterAttrs.hoveron,
hovertemplate: hovertemplateAttrs(),
selected: scatterAttrs.selected,
unselected: scatterAttrs.unselected
};
/***/ }),
/***/ 47507:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var BADNUM = (__webpack_require__(39032).BADNUM);
var calcColorscale = __webpack_require__(90136);
var arraysToCalcdata = __webpack_require__(20148);
var calcSelection = __webpack_require__(4500);
var calcMarkerSize = (__webpack_require__(16356).calcMarkerSize);
module.exports = function calc(gd, trace) {
var fullLayout = gd._fullLayout;
var subplotId = trace.subplot;
var realAxis = fullLayout[subplotId].realaxis;
var imaginaryAxis = fullLayout[subplotId].imaginaryaxis;
var realArray = realAxis.makeCalcdata(trace, 'real');
var imagArray = imaginaryAxis.makeCalcdata(trace, 'imag');
var len = trace._length;
var cd = new Array(len);
for (var i = 0; i < len; i++) {
var real = realArray[i];
var imag = imagArray[i];
var cdi = cd[i] = {};
if (isNumeric(real) && isNumeric(imag)) {
cdi.real = real;
cdi.imag = imag;
} else {
cdi.real = BADNUM;
}
}
calcMarkerSize(trace, len);
calcColorscale(gd, trace);
arraysToCalcdata(cd, trace);
calcSelection(cd, trace);
return cd;
};
/***/ }),
/***/ 76716:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
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 PTS_LINESONLY = (__webpack_require__(88200).PTS_LINESONLY);
var attributes = __webpack_require__(69496);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleRealImagDefaults(traceIn, traceOut, layout, coerce);
if (!len) {
traceOut.visible = false;
return;
}
coerce('mode', len < PTS_LINESONLY ? 'lines+markers' : 'lines');
coerce('text');
coerce('hovertext');
if (traceOut.hoveron !== 'fills') coerce('hovertemplate');
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);
};
function handleRealImagDefaults(traceIn, traceOut, layout, coerce) {
var real = coerce('real');
var imag = coerce('imag');
var len;
if (real && imag) {
len = Math.min(real.length, imag.length);
}
// TODO: handle this case outside supply defaults step
if (Lib.isTypedArray(real)) {
traceOut.real = real = Array.from(real);
}
if (Lib.isTypedArray(imag)) {
traceOut.imag = imag = Array.from(imag);
}
traceOut._length = len;
return len;
}
/***/ }),
/***/ 49504:
/***/ (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.realLabel = Axes.tickText(subplot.radialAxis, cdi.real, true).text;
labels.imagLabel = Axes.tickText(subplot.angularAxis, cdi.imag, true).text;
return labels;
};
/***/ }),
/***/ 25292:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterHover = __webpack_require__(98723);
function hoverPoints(pointData, xval, yval, hovermode) {
var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
if (!scatterPointData || scatterPointData[0].index === false) return;
var newPointData = scatterPointData[0];
// hovering on fill case
if (newPointData.index === undefined) {
return scatterPointData;
}
var subplot = pointData.subplot;
var cdi = newPointData.cd[newPointData.index];
var trace = newPointData.trace;
if (!subplot.isPtInside(cdi)) return;
newPointData.xLabelVal = undefined;
newPointData.yLabelVal = undefined;
makeHoverPointText(cdi, trace, subplot, newPointData);
newPointData.hovertemplate = trace.hovertemplate;
return scatterPointData;
}
function makeHoverPointText(cdi, trace, subplot, pointData) {
var realAxis = subplot.radialAxis;
var imaginaryAxis = subplot.angularAxis;
realAxis._hovertitle = 'real';
imaginaryAxis._hovertitle = 'imag';
var fullLayout = {};
fullLayout[trace.subplot] = {
_subplot: subplot
};
var labels = trace._module.formatLabels(cdi, trace, fullLayout);
pointData.realLabel = labels.realLabel;
pointData.imagLabel = labels.imagLabel;
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 = ['real', 'imag', 'text'];
if (parts.indexOf('real') !== -1) textPart(realAxis, pointData.realLabel);
if (parts.indexOf('imag') !== -1) textPart(imaginaryAxis, pointData.imagLabel);
if (parts.indexOf('text') !== -1 && pointData.text) {
text.push(pointData.text);
delete pointData.text;
}
pointData.extraText = text.join(' ');
}
}
module.exports = {
hoverPoints: hoverPoints,
makeHoverPointText: makeHoverPointText
};
/***/ }),
/***/ 95443:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'scattersmith',
basePlotModule: __webpack_require__(47788),
categories: ['smith', 'symbols', 'showLegend', 'scatter-like'],
attributes: __webpack_require__(69496),
supplyDefaults: __webpack_require__(76716),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(49504),
calc: __webpack_require__(47507),
plot: __webpack_require__(34927),
style: (__webpack_require__(49224).style),
styleOnSelect: (__webpack_require__(49224).styleOnSelect),
hoverPoints: (__webpack_require__(25292).hoverPoints),
selectPoints: __webpack_require__(91560),
meta: {}
};
/***/ }),
/***/ 34927:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterPlot = __webpack_require__(96504);
var BADNUM = (__webpack_require__(39032).BADNUM);
var helpers = __webpack_require__(36416);
var smith = helpers.smith;
module.exports = function plot(gd, subplot, moduleCalcData) {
var mlayer = subplot.layers.frontplot.select('g.scatterlayer');
var xa = subplot.xaxis;
var ya = subplot.yaxis;
var plotinfo = {
xaxis: xa,
yaxis: ya,
plot: subplot.framework,
layerClipId: subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null
};
// convert:
// 'c' (real,imag) -> (x,y)
for (var i = 0; i < moduleCalcData.length; i++) {
var cdi = moduleCalcData[i];
for (var j = 0; j < cdi.length; j++) {
if (j === 0) {
cdi[0].trace._xA = xa;
cdi[0].trace._yA = ya;
}
var cd = cdi[j];
var real = cd.real;
if (real === BADNUM) {
cd.x = cd.y = BADNUM;
} else {
var t = smith([real, cd.imag]);
cd.x = t[0];
cd.y = t[1];
}
}
}
scatterPlot(gd, plotinfo, moduleCalcData, mlayer);
};
/***/ }),
/***/ 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);
};
/***/ }),
/***/ 44524:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterAttrs = __webpack_require__(52904);
var colorScaleAttrs = __webpack_require__(49084);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var scatterGlAttrs = __webpack_require__(2876);
var cartesianIdRegex = (__webpack_require__(33816).idRegex);
var templatedArray = (__webpack_require__(31780).templatedArray);
var extendFlat = (__webpack_require__(92880).extendFlat);
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
var markerLineAttrs = extendFlat(colorScaleAttrs('marker.line', {
editTypeOverride: 'calc'
}), {
width: extendFlat({}, scatterMarkerLineAttrs.width, {
editType: 'calc'
}),
editType: 'calc'
});
var markerAttrs = extendFlat(colorScaleAttrs('marker'), {
symbol: scatterMarkerAttrs.symbol,
angle: scatterMarkerAttrs.angle,
size: extendFlat({}, scatterMarkerAttrs.size, {
editType: 'markerSize'
}),
sizeref: scatterMarkerAttrs.sizeref,
sizemin: scatterMarkerAttrs.sizemin,
sizemode: scatterMarkerAttrs.sizemode,
opacity: scatterMarkerAttrs.opacity,
colorbar: scatterMarkerAttrs.colorbar,
line: markerLineAttrs,
editType: 'calc'
});
markerAttrs.color.editType = markerAttrs.cmin.editType = markerAttrs.cmax.editType = 'style';
function makeAxesValObject(axLetter) {
return {
valType: 'info_array',
freeLength: true,
editType: 'calc',
items: {
valType: 'subplotid',
regex: cartesianIdRegex[axLetter],
editType: 'plot'
}
};
}
module.exports = {
dimensions: templatedArray('dimension', {
visible: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
label: {
valType: 'string',
editType: 'calc'
},
values: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
axis: {
type: {
valType: 'enumerated',
values: ['linear', 'log', 'date', 'category'],
editType: 'calc+clearAxisTypes'
},
// TODO make 'true' the default in v3?
matches: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
editType: 'calc+clearAxisTypes'
},
// TODO should add an attribute to pin down x only vars and y only vars
// like https://seaborn.pydata.org/generated/seaborn.pairplot.html
// x_vars and y_vars
// maybe more axis defaulting option e.g. `showgrid: false`
editType: 'calc+clearAxisTypes'
}),
// mode: {}, (only 'markers' for now)
text: extendFlat({}, scatterGlAttrs.text, {}),
hovertext: extendFlat({}, scatterGlAttrs.hovertext, {}),
hovertemplate: hovertemplateAttrs(),
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
marker: markerAttrs,
xaxes: makeAxesValObject('x'),
yaxes: makeAxesValObject('y'),
diagonal: {
visible: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
// type: 'scattergl' | 'histogram' | 'box' | 'violin'
// ...
// more options
editType: 'calc'
},
showupperhalf: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
showlowerhalf: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
selected: {
marker: scatterGlAttrs.selected.marker,
editType: 'calc'
},
unselected: {
marker: scatterGlAttrs.unselected.marker,
editType: 'calc'
},
opacity: scatterGlAttrs.opacity
};
/***/ }),
/***/ 28888:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Grid = __webpack_require__(12704);
module.exports = {
moduleType: 'trace',
name: 'splom',
categories: ['gl', 'regl', 'cartesian', 'symbols', 'showLegend', 'scatter-like'],
attributes: __webpack_require__(44524),
supplyDefaults: __webpack_require__(69544),
colorbar: __webpack_require__(5528),
calc: __webpack_require__(66821),
plot: __webpack_require__(54840),
hoverPoints: (__webpack_require__(72248).hoverPoints),
selectPoints: __webpack_require__(62500),
editStyle: __webpack_require__(83156),
meta: {}
};
// splom traces use the 'grid' component to generate their axes,
// register it here
Registry.register(Grid);
/***/ }),
/***/ 99332:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createLine = __webpack_require__(13472);
var Registry = __webpack_require__(24040);
var prepareRegl = __webpack_require__(5048);
var getModuleCalcData = (__webpack_require__(84888)/* .getModuleCalcData */ ._M);
var Cartesian = __webpack_require__(57952);
var getFromId = (__webpack_require__(79811).getFromId);
var shouldShowZeroLine = (__webpack_require__(54460).shouldShowZeroLine);
var SPLOM = 'splom';
var reglPrecompiled = {};
function plot(gd) {
var fullLayout = gd._fullLayout;
var _module = Registry.getModule(SPLOM);
var splomCalcData = getModuleCalcData(gd.calcdata, _module)[0];
var success = prepareRegl(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint'], reglPrecompiled);
if (!success) return;
if (fullLayout._hasOnlyLargeSploms) {
updateGrid(gd);
}
_module.plot(gd, {}, splomCalcData);
}
function drag(gd) {
var cd = gd.calcdata;
var fullLayout = gd._fullLayout;
if (fullLayout._hasOnlyLargeSploms) {
updateGrid(gd);
}
for (var i = 0; i < cd.length; i++) {
var cd0 = cd[i][0];
var trace = cd0.trace;
var scene = fullLayout._splomScenes[trace.uid];
if (trace.type === 'splom' && scene && scene.matrix) {
dragOne(gd, trace, scene);
}
}
}
function dragOne(gd, trace, scene) {
var visibleLength = scene.matrixOptions.data.length;
var visibleDims = trace._visibleDims;
var ranges = scene.viewOpts.ranges = new Array(visibleLength);
for (var k = 0; k < visibleDims.length; k++) {
var i = visibleDims[k];
var rng = ranges[k] = new Array(4);
var xa = getFromId(gd, trace._diag[i][0]);
if (xa) {
rng[0] = xa.r2l(xa.range[0]);
rng[2] = xa.r2l(xa.range[1]);
}
var ya = getFromId(gd, trace._diag[i][1]);
if (ya) {
rng[1] = ya.r2l(ya.range[0]);
rng[3] = ya.r2l(ya.range[1]);
}
}
if (scene.selectBatch.length || scene.unselectBatch.length) {
scene.matrix.update({
ranges: ranges
}, {
ranges: ranges
});
} else {
scene.matrix.update({
ranges: ranges
});
}
}
function updateGrid(gd) {
var fullLayout = gd._fullLayout;
var regl = fullLayout._glcanvas.data()[0].regl;
var splomGrid = fullLayout._splomGrid;
if (!splomGrid) {
splomGrid = fullLayout._splomGrid = createLine(regl);
}
splomGrid.update(makeGridData(gd));
}
function makeGridData(gd) {
var plotGlPixelRatio = gd._context.plotGlPixelRatio;
var fullLayout = gd._fullLayout;
var gs = fullLayout._size;
var fullView = [0, 0, fullLayout.width * plotGlPixelRatio, fullLayout.height * plotGlPixelRatio];
var lookup = {};
var k;
function push(prefix, ax, x0, x1, y0, y1) {
x0 *= plotGlPixelRatio;
x1 *= plotGlPixelRatio;
y0 *= plotGlPixelRatio;
y1 *= plotGlPixelRatio;
var lcolor = ax[prefix + 'color'];
var lwidth = ax[prefix + 'width'];
var key = String(lcolor + lwidth);
if (key in lookup) {
lookup[key].data.push(NaN, NaN, x0, x1, y0, y1);
} else {
lookup[key] = {
data: [x0, x1, y0, y1],
join: 'rect',
thickness: lwidth * plotGlPixelRatio,
color: lcolor,
viewport: fullView,
range: fullView,
overlay: false
};
}
}
for (k in fullLayout._splomSubplots) {
var sp = fullLayout._plots[k];
var xa = sp.xaxis;
var ya = sp.yaxis;
var xVals = xa._gridVals;
var yVals = ya._gridVals;
var xOffset = xa._offset;
var xLength = xa._length;
var yLength = ya._length;
// ya.l2p assumes top-to-bottom coordinate system (a la SVG),
// we need to compute bottom-to-top offsets and slopes:
var yOffset = gs.b + ya.domain[0] * gs.h;
var ym = -ya._m;
var yb = -ym * ya.r2l(ya.range[0], ya.calendar);
var x, y;
if (xa.showgrid) {
for (k = 0; k < xVals.length; k++) {
x = xOffset + xa.l2p(xVals[k].x);
push('grid', xa, x, yOffset, x, yOffset + yLength);
}
}
if (ya.showgrid) {
for (k = 0; k < yVals.length; k++) {
y = yOffset + yb + ym * yVals[k].x;
push('grid', ya, xOffset, y, xOffset + xLength, y);
}
}
if (shouldShowZeroLine(gd, xa, ya)) {
x = xOffset + xa.l2p(0);
push('zeroline', xa, x, yOffset, x, yOffset + yLength);
}
if (shouldShowZeroLine(gd, ya, xa)) {
y = yOffset + yb + 0;
push('zeroline', ya, xOffset, y, xOffset + xLength, y);
}
}
var gridBatches = [];
for (k in lookup) {
gridBatches.push(lookup[k]);
}
return gridBatches;
}
function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var lookup = {};
var i;
if (oldFullLayout._splomScenes) {
for (i = 0; i < newFullData.length; i++) {
var newTrace = newFullData[i];
if (newTrace.type === 'splom') {
lookup[newTrace.uid] = 1;
}
}
for (i = 0; i < oldFullData.length; i++) {
var oldTrace = oldFullData[i];
if (!lookup[oldTrace.uid]) {
var scene = oldFullLayout._splomScenes[oldTrace.uid];
if (scene && scene.destroy) scene.destroy();
// must first set scene to null in order to get garbage collected
oldFullLayout._splomScenes[oldTrace.uid] = null;
delete oldFullLayout._splomScenes[oldTrace.uid];
}
}
}
if (Object.keys(oldFullLayout._splomScenes || {}).length === 0) {
delete oldFullLayout._splomScenes;
}
if (oldFullLayout._splomGrid && !newFullLayout._hasOnlyLargeSploms && oldFullLayout._hasOnlyLargeSploms) {
// must first set scene to null in order to get garbage collected
oldFullLayout._splomGrid.destroy();
oldFullLayout._splomGrid = null;
delete oldFullLayout._splomGrid;
}
Cartesian.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
}
module.exports = {
name: SPLOM,
attr: Cartesian.attr,
attrRegex: Cartesian.attrRegex,
layoutAttributes: Cartesian.layoutAttributes,
supplyLayoutDefaults: Cartesian.supplyLayoutDefaults,
drawFramework: Cartesian.drawFramework,
plot: plot,
drag: drag,
updateGrid: updateGrid,
clean: clean,
updateFx: Cartesian.updateFx,
toSVG: Cartesian.toSVG,
reglPrecompiled: reglPrecompiled
};
/***/ }),
/***/ 19043:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var basePlot = __webpack_require__(99332);
var reglPrecompiled = __webpack_require__(62600);
Object.assign(basePlot.reglPrecompiled, reglPrecompiled);
module.exports = basePlot;
/***/ }),
/***/ 66821:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var AxisIDs = __webpack_require__(79811);
var calcMarkerSize = (__webpack_require__(16356).calcMarkerSize);
var calcAxisExpansion = (__webpack_require__(16356).calcAxisExpansion);
var calcColorscale = __webpack_require__(90136);
var convertMarkerSelection = (__webpack_require__(84236).markerSelection);
var convertMarkerStyle = (__webpack_require__(84236).markerStyle);
var sceneUpdate = __webpack_require__(72308);
var BADNUM = (__webpack_require__(39032).BADNUM);
var TOO_MANY_POINTS = (__webpack_require__(67072).TOO_MANY_POINTS);
module.exports = function calc(gd, trace) {
var dimensions = trace.dimensions;
var commonLength = trace._length;
var opts = {};
// 'c' for calculated, 'l' for linear,
// only differ here for log axes, pass ldata to createMatrix as 'data'
var cdata = opts.cdata = [];
var ldata = opts.data = [];
// keep track of visible dimensions
var visibleDims = trace._visibleDims = [];
var i, k, dim, xa, ya;
function makeCalcdata(ax, dim) {
// call makeCalcdata with fake input
var ccol = ax.makeCalcdata({
v: dim.values,
vcalendar: trace.calendar
}, 'v');
for (var j = 0; j < ccol.length; j++) {
ccol[j] = ccol[j] === BADNUM ? NaN : ccol[j];
}
cdata.push(ccol);
ldata.push(ax.type === 'log' ? Lib.simpleMap(ccol, ax.c2l) : ccol);
}
for (i = 0; i < dimensions.length; i++) {
dim = dimensions[i];
if (dim.visible) {
xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
// if corresponding x & y axes don't have matching types, skip dim
if (xa && ya && xa.type !== ya.type) {
Lib.log('Skipping splom dimension ' + i + ' with conflicting axis types');
continue;
}
if (xa) {
makeCalcdata(xa, dim);
if (ya && ya.type === 'category') {
ya._categories = xa._categories.slice();
}
} else {
// should not make it here, if both xa and ya undefined
makeCalcdata(ya, dim);
}
visibleDims.push(i);
}
}
calcColorscale(gd, trace);
Lib.extendFlat(opts, convertMarkerStyle(gd, trace));
var visibleLength = cdata.length;
var hasTooManyPoints = visibleLength * commonLength > TOO_MANY_POINTS;
// Reuse SVG scatter axis expansion routine.
// For graphs with very large number of points and array marker.size,
// use average marker size instead to speed things up.
var ppad;
if (hasTooManyPoints) {
ppad = opts.sizeAvg || Math.max(opts.size, 3);
} else {
ppad = calcMarkerSize(trace, commonLength);
}
for (k = 0; k < visibleDims.length; k++) {
i = visibleDims[k];
dim = dimensions[i];
xa = AxisIDs.getFromId(gd, trace._diag[i][0]) || {};
ya = AxisIDs.getFromId(gd, trace._diag[i][1]) || {};
calcAxisExpansion(gd, trace, xa, ya, cdata[k], cdata[k], ppad);
}
var scene = sceneUpdate(gd, trace);
if (!scene.matrix) scene.matrix = true;
scene.matrixOptions = opts;
scene.selectedOptions = convertMarkerSelection(gd, trace, trace.selected);
scene.unselectedOptions = convertMarkerSelection(gd, trace, trace.unselected);
return [{
x: false,
y: false,
t: {},
trace: trace
}];
};
/***/ }),
/***/ 69544:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleArrayContainerDefaults = __webpack_require__(51272);
var attributes = __webpack_require__(44524);
var subTypes = __webpack_require__(43028);
var handleMarkerDefaults = __webpack_require__(74428);
var mergeLength = __webpack_require__(26284);
var isOpenSymbol = (__webpack_require__(80088).isOpenSymbol);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
name: 'dimensions',
handleItemDefaults: dimensionDefaults
});
var showDiag = coerce('diagonal.visible');
var showUpper = coerce('showupperhalf');
var showLower = coerce('showlowerhalf');
var dimLength = mergeLength(traceOut, dimensions, 'values');
if (!dimLength || !showDiag && !showUpper && !showLower) {
traceOut.visible = false;
return;
}
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
coerce('xhoverformat');
coerce('yhoverformat');
handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
noAngleRef: true,
noStandOff: true
});
var isOpen = isOpenSymbol(traceOut.marker.symbol);
var isBubble = subTypes.isBubble(traceOut);
coerce('marker.line.width', isOpen || isBubble ? 1 : 0);
handleAxisDefaults(traceIn, traceOut, layout, coerce);
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
function dimensionDefaults(dimIn, dimOut) {
function coerce(attr, dflt) {
return Lib.coerce(dimIn, dimOut, attributes.dimensions, attr, dflt);
}
coerce('label');
var values = coerce('values');
if (!(values && values.length)) dimOut.visible = false;else coerce('visible');
coerce('axis.type');
coerce('axis.matches');
}
function handleAxisDefaults(traceIn, traceOut, layout, coerce) {
var dimensions = traceOut.dimensions;
var dimLength = dimensions.length;
var showUpper = traceOut.showupperhalf;
var showLower = traceOut.showlowerhalf;
var showDiag = traceOut.diagonal.visible;
var i, j;
var xAxesDflt = new Array(dimLength);
var yAxesDflt = new Array(dimLength);
for (i = 0; i < dimLength; i++) {
var suffix = i ? i + 1 : '';
xAxesDflt[i] = 'x' + suffix;
yAxesDflt[i] = 'y' + suffix;
}
var xaxes = coerce('xaxes', xAxesDflt);
var yaxes = coerce('yaxes', yAxesDflt);
// build list of [x,y] axis corresponding to each dimensions[i],
// very useful for passing options to regl-splom
var diag = traceOut._diag = new Array(dimLength);
// lookup for 'drawn' x|y axes, to avoid costly indexOf downstream
traceOut._xaxes = {};
traceOut._yaxes = {};
// list of 'drawn' x|y axes, use to generate list of subplots
var xList = [];
var yList = [];
function fillAxisStashes(axId, counterAxId, dim, list) {
if (!axId) return;
var axLetter = axId.charAt(0);
var stash = layout._splomAxes[axLetter];
traceOut['_' + axLetter + 'axes'][axId] = 1;
list.push(axId);
if (!(axId in stash)) {
var s = stash[axId] = {};
if (dim) {
s.label = dim.label || '';
if (dim.visible && dim.axis) {
if (dim.axis.type) s.type = dim.axis.type;
if (dim.axis.matches) s.matches = counterAxId;
}
}
}
}
// cases where showDiag and showLower or showUpper are false
// no special treatment as the 'drawn' x-axes and y-axes no longer match
// the dimensions items and xaxes|yaxes 1-to-1
var mustShiftX = !showDiag && !showLower;
var mustShiftY = !showDiag && !showUpper;
traceOut._axesDim = {};
for (i = 0; i < dimLength; i++) {
var dim = dimensions[i];
var i0 = i === 0;
var iN = i === dimLength - 1;
var xaId = i0 && mustShiftX || iN && mustShiftY ? undefined : xaxes[i];
var yaId = i0 && mustShiftY || iN && mustShiftX ? undefined : yaxes[i];
fillAxisStashes(xaId, yaId, dim, xList);
fillAxisStashes(yaId, xaId, dim, yList);
diag[i] = [xaId, yaId];
traceOut._axesDim[xaId] = i;
traceOut._axesDim[yaId] = i;
}
// fill in splom subplot keys
for (i = 0; i < xList.length; i++) {
for (j = 0; j < yList.length; j++) {
var id = xList[i] + yList[j];
if (i > j && showUpper) {
layout._splomSubplots[id] = 1;
} else if (i < j && showLower) {
layout._splomSubplots[id] = 1;
} else if (i === j && (showDiag || !showLower || !showUpper)) {
// need to include diagonal subplots when
// hiding one half and the diagonal
layout._splomSubplots[id] = 1;
}
}
}
// when lower half is omitted, or when just the diagonal is gone,
// override grid default to make sure axes remain on
// the left/bottom of the plot area
if (!showLower || !showDiag && showUpper && showLower) {
layout._splomGridDflt.xside = 'bottom';
layout._splomGridDflt.yside = 'left';
}
}
/***/ }),
/***/ 83156:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var calcColorscale = __webpack_require__(90136);
var convertMarkerStyle = (__webpack_require__(84236).markerStyle);
module.exports = function editStyle(gd, cd0) {
var trace = cd0.trace;
var scene = gd._fullLayout._splomScenes[trace.uid];
if (scene) {
calcColorscale(gd, trace);
Lib.extendFlat(scene.matrixOptions, convertMarkerStyle(gd, trace));
// TODO [un]selected styles?
var opts = Lib.extendFlat({}, scene.matrixOptions, scene.viewOpts);
// TODO this is too long for arrayOk attributes!
scene.matrix.update(opts, null);
}
};
/***/ }),
/***/ 50328:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
exports.getDimIndex = function getDimIndex(trace, ax) {
var axId = ax._id;
var axLetter = axId.charAt(0);
var ind = {
x: 0,
y: 1
}[axLetter];
var visibleDims = trace._visibleDims;
for (var k = 0; k < visibleDims.length; k++) {
var i = visibleDims[k];
if (trace._diag[i][ind] === axId) return k;
}
return false;
};
/***/ }),
/***/ 72248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var helpers = __webpack_require__(50328);
var calcHover = (__webpack_require__(41272).calcHover);
var getFromId = (__webpack_require__(54460).getFromId);
var extendFlat = (__webpack_require__(92880).extendFlat);
function hoverPoints(pointData, xval, yval, hovermode, opts) {
if (!opts) opts = {};
var hovermodeHasX = (hovermode || '').charAt(0) === 'x';
var hovermodeHasY = (hovermode || '').charAt(0) === 'y';
var points = _hoverPoints(pointData, xval, yval);
if ((hovermodeHasX || hovermodeHasY) && opts.hoversubplots === 'axis' && points[0]) {
var subplotsWith = (hovermodeHasX ? pointData.xa : pointData.ya)._subplotsWith;
var gd = opts.gd;
var _pointData = extendFlat({}, pointData);
for (var i = 0; i < subplotsWith.length; i++) {
var spId = subplotsWith[i];
// do not reselect on the initial subplot
if (spId === pointData.xa._id + pointData.ya._id) continue;
if (hovermodeHasY) {
_pointData.xa = getFromId(gd, spId, 'x');
} else {
// hovermodeHasX
_pointData.ya = getFromId(gd, spId, 'y');
}
var axisHoversubplots = hovermodeHasX || hovermodeHasY;
var newPoints = _hoverPoints(_pointData, xval, yval, axisHoversubplots);
points = points.concat(newPoints);
}
}
return points;
}
function _hoverPoints(pointData, xval, yval, axisHoversubplots) {
var cd = pointData.cd;
var trace = cd[0].trace;
var scene = pointData.scene;
var cdata = scene.matrixOptions.cdata;
var xa = pointData.xa;
var ya = pointData.ya;
var xpx = xa.c2p(xval);
var ypx = ya.c2p(yval);
var maxDistance = pointData.distance;
var xi = helpers.getDimIndex(trace, xa);
var yi = helpers.getDimIndex(trace, ya);
if (xi === false || yi === false) return [pointData];
var x = cdata[xi];
var y = cdata[yi];
var id, dxy;
var minDist = maxDistance;
for (var i = 0; i < x.length; i++) {
if (axisHoversubplots && i !== pointData.index) continue;
var ptx = x[i];
var pty = y[i];
var dx = xa.c2p(ptx) - xpx;
var dy = ya.c2p(pty) - ypx;
var dist = Math.sqrt(dx * dx + dy * dy);
if (axisHoversubplots || dist < minDist) {
minDist = dxy = dist;
id = i;
}
}
pointData.index = id;
pointData.distance = minDist;
pointData.dxy = dxy;
if (id === undefined) return [pointData];
return [calcHover(pointData, x, y, trace)];
}
module.exports = {
hoverPoints: hoverPoints
};
/***/ }),
/***/ 54840:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createMatrix = __webpack_require__(55795);
var Lib = __webpack_require__(3400);
var AxisIDs = __webpack_require__(79811);
var selectMode = (__webpack_require__(72760).selectMode);
module.exports = function plot(gd, _, splomCalcData) {
if (!splomCalcData.length) return;
for (var i = 0; i < splomCalcData.length; i++) {
plotOne(gd, splomCalcData[i][0]);
}
};
function plotOne(gd, cd0) {
var fullLayout = gd._fullLayout;
var gs = fullLayout._size;
var trace = cd0.trace;
var stash = cd0.t;
var scene = fullLayout._splomScenes[trace.uid];
var matrixOpts = scene.matrixOptions;
var cdata = matrixOpts.cdata;
var regl = fullLayout._glcanvas.data()[0].regl;
var dragmode = fullLayout.dragmode;
var xa, ya;
var i, j, k;
if (cdata.length === 0) return;
// augment options with proper upper/lower halves
// regl-splom's default grid starts from bottom-left
matrixOpts.lower = trace.showupperhalf;
matrixOpts.upper = trace.showlowerhalf;
matrixOpts.diagonal = trace.diagonal.visible;
var visibleDims = trace._visibleDims;
var visibleLength = cdata.length;
var viewOpts = scene.viewOpts = {};
viewOpts.ranges = new Array(visibleLength);
viewOpts.domains = new Array(visibleLength);
for (k = 0; k < visibleDims.length; k++) {
i = visibleDims[k];
var rng = viewOpts.ranges[k] = new Array(4);
var dmn = viewOpts.domains[k] = new Array(4);
xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
if (xa) {
rng[0] = xa._rl[0];
rng[2] = xa._rl[1];
dmn[0] = xa.domain[0];
dmn[2] = xa.domain[1];
}
ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
if (ya) {
rng[1] = ya._rl[0];
rng[3] = ya._rl[1];
dmn[1] = ya.domain[0];
dmn[3] = ya.domain[1];
}
}
var plotGlPixelRatio = gd._context.plotGlPixelRatio;
var l = gs.l * plotGlPixelRatio;
var b = gs.b * plotGlPixelRatio;
var w = gs.w * plotGlPixelRatio;
var h = gs.h * plotGlPixelRatio;
viewOpts.viewport = [l, b, w + l, h + b];
if (scene.matrix === true) {
scene.matrix = createMatrix(regl);
}
var clickSelectEnabled = fullLayout.clickmode.indexOf('select') > -1;
var isSelectMode = selectMode(dragmode) || !!trace.selectedpoints || clickSelectEnabled;
var needsBaseUpdate = true;
if (isSelectMode) {
var commonLength = trace._length;
// regenerate scene batch, if traces number changed during selection
if (trace.selectedpoints) {
scene.selectBatch = trace.selectedpoints;
var selPts = trace.selectedpoints;
var selDict = {};
for (i = 0; i < selPts.length; i++) {
selDict[selPts[i]] = true;
}
var unselPts = [];
for (i = 0; i < commonLength; i++) {
if (!selDict[i]) unselPts.push(i);
}
scene.unselectBatch = unselPts;
}
// precalculate px coords since we are not going to pan during select
var xpx = stash.xpx = new Array(visibleLength);
var ypx = stash.ypx = new Array(visibleLength);
for (k = 0; k < visibleDims.length; k++) {
i = visibleDims[k];
xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
if (xa) {
xpx[k] = new Array(commonLength);
for (j = 0; j < commonLength; j++) {
xpx[k][j] = xa.c2p(cdata[k][j]);
}
}
ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
if (ya) {
ypx[k] = new Array(commonLength);
for (j = 0; j < commonLength; j++) {
ypx[k][j] = ya.c2p(cdata[k][j]);
}
}
}
if (scene.selectBatch.length || scene.unselectBatch.length) {
var unselOpts = Lib.extendFlat({}, matrixOpts, scene.unselectedOptions, viewOpts);
var selOpts = Lib.extendFlat({}, matrixOpts, scene.selectedOptions, viewOpts);
scene.matrix.update(unselOpts, selOpts);
needsBaseUpdate = false;
}
} else {
stash.xpx = stash.ypx = null;
}
if (needsBaseUpdate) {
var opts = Lib.extendFlat({}, matrixOpts, viewOpts);
scene.matrix.update(opts, null);
}
}
/***/ }),
/***/ 62600:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var v0 = __webpack_require__(51154);
var v1 = __webpack_require__(81705);
var v2 = __webpack_require__(39760);
var v3 = __webpack_require__(82576);
var v4 = __webpack_require__(29548);
var v5 = __webpack_require__(51068);
var v6 = __webpack_require__(81272);
var v7 = __webpack_require__(8756);
var v8 = __webpack_require__(7108);
var v9 = __webpack_require__(62052);
/* eslint-disable quote-props */
module.exports = {
'3e771157d23b4793771f65d83e6387262ed73d488209157f19a7fa027bddd71b': v0,
'cbf700f001fff25b649fba9c37fa0dc6631c1cdee318ad49473d28ec10dcee81': v1,
'8fad2284703471df7c0e0d0a7b96d983e8c53f6d707dd55d5921c1eab71f6623': v2,
'dbd1cc9126a137a605df67dc0706e55116f04e33b4545a80042031752de5aef5': v3,
'bfc540da96a87fcc039073cb37b45e6b81ef5ee6ef3529d726ceed8336354019': v4,
'fe5b6844077cde1bdd7273f4495969fad93500c26a69b62e74ec2664c447bcc7': v5,
'db1b82c68771e7f5012fad1fbdae7ff23b526e58d2995bf6dd2cf30024e0f41d': v6,
'49e82bba439f1d9d441c17ba252d05640bc63fefdf22d1219993633af7730210': v7,
'6a5d6bd29c15cf7614221b94c3f384df47c2c46fbe4456e8c57b5cd14c84d923': v8,
'8902aff2b23b600f8103bcc84a8af2999d28795208aedadc2db06f921f9c7034': v9
};
/***/ }),
/***/ 72308:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
module.exports = function sceneUpdate(gd, trace) {
var fullLayout = gd._fullLayout;
var uid = trace.uid;
// must place ref to 'scene' in fullLayout, so that:
// - it can be relinked properly on updates
// - it can be destroyed properly when needed
var splomScenes = fullLayout._splomScenes;
if (!splomScenes) splomScenes = fullLayout._splomScenes = {};
var reset = {
dirty: true,
selectBatch: [],
unselectBatch: []
};
var first = {
matrix: false,
selectBatch: [],
unselectBatch: []
};
var scene = splomScenes[trace.uid];
if (!scene) {
scene = splomScenes[uid] = Lib.extendFlat({}, reset, first);
scene.draw = function draw() {
if (scene.matrix && scene.matrix.draw) {
if (scene.selectBatch.length || scene.unselectBatch.length) {
scene.matrix.draw(scene.unselectBatch, scene.selectBatch);
} else {
scene.matrix.draw();
}
}
scene.dirty = false;
};
// remove scene resources
scene.destroy = function destroy() {
if (scene.matrix && scene.matrix.destroy) {
scene.matrix.destroy();
}
scene.matrixOptions = null;
scene.selectBatch = null;
scene.unselectBatch = null;
scene = null;
};
}
// In case if we have scene from the last calc - reset data
if (!scene.dirty) {
Lib.extendFlat(scene, reset);
}
return scene;
};
/***/ }),
/***/ 62500:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var pushUnique = Lib.pushUnique;
var subTypes = __webpack_require__(43028);
var helpers = __webpack_require__(50328);
module.exports = function select(searchInfo, selectionTester) {
var cd = searchInfo.cd;
var trace = cd[0].trace;
var stash = cd[0].t;
var scene = searchInfo.scene;
var cdata = scene.matrixOptions.cdata;
var xa = searchInfo.xaxis;
var ya = searchInfo.yaxis;
var selection = [];
if (!scene) return selection;
var hasOnlyLines = !subTypes.hasMarkers(trace) && !subTypes.hasText(trace);
if (trace.visible !== true || hasOnlyLines) return selection;
var xi = helpers.getDimIndex(trace, xa);
var yi = helpers.getDimIndex(trace, ya);
if (xi === false || yi === false) return selection;
var xpx = stash.xpx[xi];
var ypx = stash.ypx[yi];
var x = cdata[xi];
var y = cdata[yi];
var els = (searchInfo.scene.selectBatch || []).slice();
var unels = [];
// degenerate polygon does not enable selection
// filter out points by visible scatter ones
if (selectionTester !== false && !selectionTester.degenerate) {
for (var i = 0; i < x.length; i++) {
if (selectionTester.contains([xpx[i], ypx[i]], null, i, searchInfo)) {
selection.push({
pointNumber: i,
x: x[i],
y: y[i]
});
pushUnique(els, i);
} else if (els.indexOf(i) !== -1) {
pushUnique(els, i);
} else {
unels.push(i);
}
}
}
var matrixOpts = scene.matrixOptions;
if (!els.length && !unels.length) {
scene.matrix.update(matrixOpts, null);
} else if (!scene.selectBatch.length && !scene.unselectBatch.length) {
scene.matrix.update(scene.unselectedOptions, Lib.extendFlat({}, matrixOpts, scene.selectedOptions, scene.viewOpts));
}
scene.selectBatch = els;
scene.unselectBatch = unels;
return selection;
};
/***/ }),
/***/ 15680:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var index = __webpack_require__(28888);
index.basePlotModule = __webpack_require__(19043), module.exports = index;
/***/ }),
/***/ 90167:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorScaleAttrs = __webpack_require__(49084);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var mesh3dAttrs = __webpack_require__(52948);
var baseAttrs = __webpack_require__(45464);
var extendFlat = (__webpack_require__(92880).extendFlat);
var attrs = {
x: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
y: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
z: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
u: {
valType: 'data_array',
editType: 'calc'
},
v: {
valType: 'data_array',
editType: 'calc'
},
w: {
valType: 'data_array',
editType: 'calc'
},
starts: {
x: {
valType: 'data_array',
editType: 'calc'
},
y: {
valType: 'data_array',
editType: 'calc'
},
z: {
valType: 'data_array',
editType: 'calc'
},
editType: 'calc'
},
maxdisplayed: {
valType: 'integer',
min: 0,
dflt: 1000,
editType: 'calc'
},
// TODO
//
// Should add 'absolute' (like cone traces have), but currently gl-streamtube3d's
// `absoluteTubeSize` doesn't behave well enough for our needs.
//
// 'fixed' would be a nice addition to plot stream 'lines', see
// https://github.com/plotly/plotly.js/commit/812be20750e21e0a1831975001c248d365850f73#r29129877
//
// sizemode: {
// valType: 'enumerated',
// values: ['scaled', 'absolute', 'fixed'],
// dflt: 'scaled',
// editType: 'calc',
//
// },
sizeref: {
valType: 'number',
editType: 'calc',
min: 0,
dflt: 1
},
text: {
valType: 'string',
dflt: '',
editType: 'calc'
},
hovertext: {
valType: 'string',
dflt: '',
editType: 'calc'
},
hovertemplate: hovertemplateAttrs({
editType: 'calc'
}, {
keys: ['tubex', 'tubey', 'tubez', 'tubeu', 'tubev', 'tubew', 'norm', 'divergence']
}),
uhoverformat: axisHoverFormat('u', 1),
vhoverformat: axisHoverFormat('v', 1),
whoverformat: axisHoverFormat('w', 1),
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z'),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
};
extendFlat(attrs, colorScaleAttrs('', {
colorAttr: 'u/v/w norm',
showScaleDflt: true,
editTypeOverride: 'calc'
}));
var fromMesh3d = ['opacity', 'lightposition', 'lighting'];
fromMesh3d.forEach(function (k) {
attrs[k] = mesh3dAttrs[k];
});
attrs.hoverinfo = extendFlat({}, baseAttrs.hoverinfo, {
editType: 'calc',
flags: ['x', 'y', 'z', 'u', 'v', 'w', 'norm', 'divergence', 'text', 'name'],
dflt: 'x+y+z+norm+text+name'
});
attrs.transforms = undefined;
module.exports = attrs;
/***/ }),
/***/ 3832:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var colorscaleCalc = __webpack_require__(47128);
function calc(gd, trace) {
trace._len = Math.min(trace.u.length, trace.v.length, trace.w.length, trace.x.length, trace.y.length, trace.z.length);
trace._u = filter(trace.u, trace._len);
trace._v = filter(trace.v, trace._len);
trace._w = filter(trace.w, trace._len);
trace._x = filter(trace.x, trace._len);
trace._y = filter(trace.y, trace._len);
trace._z = filter(trace.z, trace._len);
var grid = processGrid(trace);
trace._gridFill = grid.fill;
trace._Xs = grid.Xs;
trace._Ys = grid.Ys;
trace._Zs = grid.Zs;
trace._len = grid.len;
var slen = 0;
var startx, starty, startz;
if (trace.starts) {
startx = filter(trace.starts.x || []);
starty = filter(trace.starts.y || []);
startz = filter(trace.starts.z || []);
slen = Math.min(startx.length, starty.length, startz.length);
}
trace._startsX = startx || [];
trace._startsY = starty || [];
trace._startsZ = startz || [];
var normMax = 0;
var normMin = Infinity;
var i;
for (i = 0; i < trace._len; i++) {
var u = trace._u[i];
var v = trace._v[i];
var w = trace._w[i];
var norm = Math.sqrt(u * u + v * v + w * w);
normMax = Math.max(normMax, norm);
normMin = Math.min(normMin, norm);
}
colorscaleCalc(gd, trace, {
vals: [normMin, normMax],
containerStr: '',
cLetter: 'c'
});
for (i = 0; i < slen; i++) {
var sx = startx[i];
grid.xMax = Math.max(grid.xMax, sx);
grid.xMin = Math.min(grid.xMin, sx);
var sy = starty[i];
grid.yMax = Math.max(grid.yMax, sy);
grid.yMin = Math.min(grid.yMin, sy);
var sz = startz[i];
grid.zMax = Math.max(grid.zMax, sz);
grid.zMin = Math.min(grid.zMin, sz);
}
trace._slen = slen;
trace._normMax = normMax;
trace._xbnds = [grid.xMin, grid.xMax];
trace._ybnds = [grid.yMin, grid.yMax];
trace._zbnds = [grid.zMin, grid.zMax];
}
function processGrid(trace) {
var x = trace._x;
var y = trace._y;
var z = trace._z;
var len = trace._len;
var i, j, k;
var xMax = -Infinity;
var xMin = Infinity;
var yMax = -Infinity;
var yMin = Infinity;
var zMax = -Infinity;
var zMin = Infinity;
var gridFill = '';
var filledX;
var filledY;
var filledZ;
var firstX, lastX;
var firstY, lastY;
var firstZ, lastZ;
if (len) {
firstX = x[0];
firstY = y[0];
firstZ = z[0];
}
if (len > 1) {
lastX = x[len - 1];
lastY = y[len - 1];
lastZ = z[len - 1];
}
for (i = 0; i < len; i++) {
xMax = Math.max(xMax, x[i]);
xMin = Math.min(xMin, x[i]);
yMax = Math.max(yMax, y[i]);
yMin = Math.min(yMin, y[i]);
zMax = Math.max(zMax, z[i]);
zMin = Math.min(zMin, z[i]);
if (!filledX && x[i] !== firstX) {
filledX = true;
gridFill += 'x';
}
if (!filledY && y[i] !== firstY) {
filledY = true;
gridFill += 'y';
}
if (!filledZ && z[i] !== firstZ) {
filledZ = true;
gridFill += 'z';
}
}
// fill if not filled - case of having dimension(s) with one item
if (!filledX) gridFill += 'x';
if (!filledY) gridFill += 'y';
if (!filledZ) gridFill += 'z';
var Xs = distinctVals(trace._x);
var Ys = distinctVals(trace._y);
var Zs = distinctVals(trace._z);
gridFill = gridFill.replace('x', (firstX > lastX ? '-' : '+') + 'x');
gridFill = gridFill.replace('y', (firstY > lastY ? '-' : '+') + 'y');
gridFill = gridFill.replace('z', (firstZ > lastZ ? '-' : '+') + 'z');
var empty = function () {
len = 0;
Xs = [];
Ys = [];
Zs = [];
};
// Over-specified mesh case, this would error in tube2mesh
if (!len || len < Xs.length * Ys.length * Zs.length) empty();
var getArray = function (c) {
return c === 'x' ? x : c === 'y' ? y : z;
};
var getVals = function (c) {
return c === 'x' ? Xs : c === 'y' ? Ys : Zs;
};
var getDir = function (c) {
return c[len - 1] < c[0] ? -1 : 1;
};
var arrK = getArray(gridFill[1]);
var arrJ = getArray(gridFill[3]);
var arrI = getArray(gridFill[5]);
var nk = getVals(gridFill[1]).length;
var nj = getVals(gridFill[3]).length;
var ni = getVals(gridFill[5]).length;
var arbitrary = false;
var getIndex = function (_i, _j, _k) {
return nk * (nj * _i + _j) + _k;
};
var dirK = getDir(getArray(gridFill[1]));
var dirJ = getDir(getArray(gridFill[3]));
var dirI = getDir(getArray(gridFill[5]));
for (i = 0; i < ni - 1; i++) {
for (j = 0; j < nj - 1; j++) {
for (k = 0; k < nk - 1; k++) {
var q000 = getIndex(i, j, k);
var q001 = getIndex(i, j, k + 1);
var q010 = getIndex(i, j + 1, k);
var q100 = getIndex(i + 1, j, k);
if (!(arrK[q000] * dirK < arrK[q001] * dirK) || !(arrJ[q000] * dirJ < arrJ[q010] * dirJ) || !(arrI[q000] * dirI < arrI[q100] * dirI)) {
arbitrary = true;
}
if (arbitrary) break;
}
if (arbitrary) break;
}
if (arbitrary) break;
}
if (arbitrary) {
Lib.warn('Encountered arbitrary coordinates! Unable to input data grid.');
empty();
}
return {
xMin: xMin,
yMin: yMin,
zMin: zMin,
xMax: xMax,
yMax: yMax,
zMax: zMax,
Xs: Xs,
Ys: Ys,
Zs: Zs,
len: len,
fill: gridFill
};
}
function distinctVals(col) {
return Lib.distinctVals(col).vals;
}
function filter(arr, len) {
if (len === undefined) len = arr.length;
// no need for casting typed arrays to numbers
if (Lib.isTypedArray(arr)) return arr.subarray(0, len);
var values = [];
for (var i = 0; i < len; i++) {
values[i] = +arr[i];
}
return values;
}
module.exports = {
calc: calc,
filter: filter,
processGrid: processGrid
};
/***/ }),
/***/ 25668:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var tube2mesh = (__webpack_require__(67792).gl_streamtube3d);
var createTubeMesh = tube2mesh.createTubeMesh;
var Lib = __webpack_require__(3400);
var parseColorScale = (__webpack_require__(33040).parseColorScale);
var extractOpts = (__webpack_require__(8932).extractOpts);
var zip3 = __webpack_require__(52094);
var axisName2scaleIndex = {
xaxis: 0,
yaxis: 1,
zaxis: 2
};
function Streamtube(scene, uid) {
this.scene = scene;
this.uid = uid;
this.mesh = null;
this.data = null;
}
var proto = Streamtube.prototype;
proto.handlePick = function (selection) {
var sceneLayout = this.scene.fullSceneLayout;
var dataScale = this.scene.dataScale;
function fromDataScale(v, axisName) {
var ax = sceneLayout[axisName];
var scale = dataScale[axisName2scaleIndex[axisName]];
return ax.l2c(v) / scale;
}
if (selection.object === this.mesh) {
var pos = selection.data.position;
var uvx = selection.data.velocity;
selection.traceCoordinate = [fromDataScale(pos[0], 'xaxis'), fromDataScale(pos[1], 'yaxis'), fromDataScale(pos[2], 'zaxis'), fromDataScale(uvx[0], 'xaxis'), fromDataScale(uvx[1], 'yaxis'), fromDataScale(uvx[2], 'zaxis'),
// u/v/w norm
selection.data.intensity * this.data._normMax,
// divergence
selection.data.divergence];
selection.textLabel = this.data.hovertext || this.data.text;
return true;
}
};
function getDfltStartingPositions(vec) {
var len = vec.length;
var s;
if (len > 2) {
s = vec.slice(1, len - 1);
} else if (len === 2) {
s = [(vec[0] + vec[1]) / 2];
} else {
s = vec;
}
return s;
}
function getBoundPads(vec) {
var len = vec.length;
if (len === 1) {
return [0.5, 0.5];
} else {
return [vec[1] - vec[0], vec[len - 1] - vec[len - 2]];
}
}
function convert(scene, trace) {
var sceneLayout = scene.fullSceneLayout;
var dataScale = scene.dataScale;
var len = trace._len;
var tubeOpts = {};
function toDataCoords(arr, axisName) {
var ax = sceneLayout[axisName];
var scale = dataScale[axisName2scaleIndex[axisName]];
return Lib.simpleMap(arr, function (v) {
return ax.d2l(v) * scale;
});
}
tubeOpts.vectors = zip3(toDataCoords(trace._u, 'xaxis'), toDataCoords(trace._v, 'yaxis'), toDataCoords(trace._w, 'zaxis'), len);
// Over-specified mesh case, this would error in tube2mesh
if (!len) {
return {
positions: [],
cells: []
};
}
var meshx = toDataCoords(trace._Xs, 'xaxis');
var meshy = toDataCoords(trace._Ys, 'yaxis');
var meshz = toDataCoords(trace._Zs, 'zaxis');
tubeOpts.meshgrid = [meshx, meshy, meshz];
tubeOpts.gridFill = trace._gridFill;
var slen = trace._slen;
if (slen) {
tubeOpts.startingPositions = zip3(toDataCoords(trace._startsX, 'xaxis'), toDataCoords(trace._startsY, 'yaxis'), toDataCoords(trace._startsZ, 'zaxis'));
} else {
// Default starting positions:
//
// if len>2, cut xz plane at min-y,
// takes all x/y/z pts on that plane except those on the edges
// to generate "well-defined" tubes,
//
// if len=2, take position halfway between two the pts,
//
// if len=1, take that pt
var sy0 = meshy[0];
var sx = getDfltStartingPositions(meshx);
var sz = getDfltStartingPositions(meshz);
var startingPositions = new Array(sx.length * sz.length);
var m = 0;
for (var i = 0; i < sx.length; i++) {
for (var k = 0; k < sz.length; k++) {
startingPositions[m++] = [sx[i], sy0, sz[k]];
}
}
tubeOpts.startingPositions = startingPositions;
}
tubeOpts.colormap = parseColorScale(trace);
tubeOpts.tubeSize = trace.sizeref;
tubeOpts.maxLength = trace.maxdisplayed;
// add some padding around the bounds
// to e.g. allow tubes starting from a slice of the x/y/z mesh
// to go beyond bounds a little bit w/o getting clipped
var xbnds = toDataCoords(trace._xbnds, 'xaxis');
var ybnds = toDataCoords(trace._ybnds, 'yaxis');
var zbnds = toDataCoords(trace._zbnds, 'zaxis');
var xpads = getBoundPads(meshx);
var ypads = getBoundPads(meshy);
var zpads = getBoundPads(meshz);
var bounds = [[xbnds[0] - xpads[0], ybnds[0] - ypads[0], zbnds[0] - zpads[0]], [xbnds[1] + xpads[1], ybnds[1] + ypads[1], zbnds[1] + zpads[1]]];
var meshData = tube2mesh(tubeOpts, bounds);
// N.B. cmin/cmax correspond to the min/max vector norm
// in the u/v/w arrays, which in general is NOT equal to max
// intensity that colors the tubes.
var cOpts = extractOpts(trace);
meshData.vertexIntensityBounds = [cOpts.min / trace._normMax, cOpts.max / trace._normMax];
// pass gl-mesh3d lighting attributes
var lp = trace.lightposition;
meshData.lightPosition = [lp.x, lp.y, lp.z];
meshData.ambient = trace.lighting.ambient;
meshData.diffuse = trace.lighting.diffuse;
meshData.specular = trace.lighting.specular;
meshData.roughness = trace.lighting.roughness;
meshData.fresnel = trace.lighting.fresnel;
meshData.opacity = trace.opacity;
// stash autorange pad value
trace._pad = meshData.tubeScale * trace.sizeref * 2;
return meshData;
}
proto.update = function (data) {
this.data = data;
var meshData = convert(this.scene, data);
this.mesh.update(meshData);
};
proto.dispose = function () {
this.scene.glplot.remove(this.mesh);
this.mesh.dispose();
};
function createStreamtubeTrace(scene, data) {
var gl = scene.glplot.gl;
var meshData = convert(scene, data);
var mesh = createTubeMesh(gl, meshData);
var streamtube = new Streamtube(scene, data.uid);
streamtube.mesh = mesh;
streamtube.data = data;
mesh._trace = streamtube;
scene.glplot.add(mesh);
return streamtube;
}
module.exports = createStreamtubeTrace;
/***/ }),
/***/ 54304:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(90167);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var u = coerce('u');
var v = coerce('v');
var w = coerce('w');
var x = coerce('x');
var y = coerce('y');
var z = coerce('z');
if (!u || !u.length || !v || !v.length || !w || !w.length || !x || !x.length || !y || !y.length || !z || !z.length) {
traceOut.visible = false;
return;
}
coerce('starts.x');
coerce('starts.y');
coerce('starts.z');
coerce('maxdisplayed');
coerce('sizeref');
coerce('lighting.ambient');
coerce('lighting.diffuse');
coerce('lighting.specular');
coerce('lighting.roughness');
coerce('lighting.fresnel');
coerce('lightposition.x');
coerce('lightposition.y');
coerce('lightposition.z');
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'c'
});
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
coerce('uhoverformat');
coerce('vhoverformat');
coerce('whoverformat');
coerce('xhoverformat');
coerce('yhoverformat');
coerce('zhoverformat');
// disable 1D transforms (for now)
// x/y/z and u/v/w have matching lengths,
// but they don't have to match with starts.(x|y|z)
traceOut._length = null;
};
/***/ }),
/***/ 15436:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'streamtube',
basePlotModule: __webpack_require__(12536),
categories: ['gl3d', 'showLegend'],
attributes: __webpack_require__(90167),
supplyDefaults: __webpack_require__(54304),
colorbar: {
min: 'cmin',
max: 'cmax'
},
calc: (__webpack_require__(3832).calc),
plot: __webpack_require__(25668),
eventData: function (out, pt) {
out.tubex = out.x;
out.tubey = out.y;
out.tubez = out.z;
out.tubeu = pt.traceCoordinate[3];
out.tubev = pt.traceCoordinate[4];
out.tubew = pt.traceCoordinate[5];
out.norm = pt.traceCoordinate[6];
out.divergence = pt.traceCoordinate[7];
// Does not correspond to input x/y/z, so delete them
delete out.x;
delete out.y;
delete out.z;
return out;
},
meta: {}
};
/***/ }),
/***/ 424:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var baseAttrs = __webpack_require__(45464);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var colorScaleAttrs = __webpack_require__(49084);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var pieAttrs = __webpack_require__(74996);
var constants = __webpack_require__(27328);
var extendFlat = (__webpack_require__(92880).extendFlat);
var pattern = (__webpack_require__(98192)/* .pattern */ .c);
module.exports = {
labels: {
valType: 'data_array',
editType: 'calc'
},
parents: {
valType: 'data_array',
editType: 'calc'
},
values: {
valType: 'data_array',
editType: 'calc'
},
branchvalues: {
valType: 'enumerated',
values: ['remainder', 'total'],
dflt: 'remainder',
editType: 'calc'
},
count: {
valType: 'flaglist',
flags: ['branches', 'leaves'],
dflt: 'leaves',
editType: 'calc'
},
level: {
valType: 'any',
editType: 'plot',
anim: true
},
maxdepth: {
valType: 'integer',
editType: 'plot',
dflt: -1
},
marker: extendFlat({
colors: {
valType: 'data_array',
editType: 'calc'
},
// colorinheritance: {
// valType: 'enumerated',
// values: ['per-branch', 'per-label', false]
// },
line: {
color: extendFlat({}, pieAttrs.marker.line.color, {
dflt: null
}),
width: extendFlat({}, pieAttrs.marker.line.width, {
dflt: 1
}),
editType: 'calc'
},
pattern: pattern,
editType: 'calc'
}, colorScaleAttrs('marker', {
colorAttr: 'colors',
anim: false // TODO: set to anim: true?
})),
leaf: {
opacity: {
valType: 'number',
editType: 'style',
min: 0,
max: 1
},
editType: 'plot'
},
text: pieAttrs.text,
textinfo: {
valType: 'flaglist',
flags: ['label', 'text', 'value', 'current path', 'percent root', 'percent entry', 'percent parent'],
extras: ['none'],
editType: 'plot'
},
// TODO: incorporate `label` and `value` in the eventData
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: constants.eventDataKeys.concat(['label', 'value'])
}),
hovertext: pieAttrs.hovertext,
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['label', 'text', 'value', 'name', 'current path', 'percent root', 'percent entry', 'percent parent'],
dflt: 'label+text+value+name'
}),
hovertemplate: hovertemplateAttrs({}, {
keys: constants.eventDataKeys
}),
textfont: pieAttrs.textfont,
insidetextorientation: pieAttrs.insidetextorientation,
insidetextfont: pieAttrs.insidetextfont,
outsidetextfont: extendFlat({}, pieAttrs.outsidetextfont, {}),
rotation: {
valType: 'angle',
dflt: 0,
editType: 'plot'
},
sort: pieAttrs.sort,
root: {
color: {
valType: 'color',
editType: 'calc',
dflt: 'rgba(0,0,0,0)'
},
editType: 'calc'
},
domain: domainAttrs({
name: 'sunburst',
trace: true,
editType: 'calc'
})
};
/***/ }),
/***/ 54904:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var plots = __webpack_require__(7316);
exports.name = 'sunburst';
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);
};
/***/ }),
/***/ 3776:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3Hierarchy = __webpack_require__(74148);
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var makeColorScaleFn = (__webpack_require__(8932).makeColorScaleFuncFromTrace);
var makePullColorFn = (__webpack_require__(45768).makePullColorFn);
var generateExtendedColors = (__webpack_require__(45768).generateExtendedColors);
var colorscaleCalc = (__webpack_require__(8932).calc);
var ALMOST_EQUAL = (__webpack_require__(39032).ALMOST_EQUAL);
var sunburstExtendedColorWays = {};
var treemapExtendedColorWays = {};
var icicleExtendedColorWays = {};
exports.calc = function (gd, trace) {
var fullLayout = gd._fullLayout;
var ids = trace.ids;
var hasIds = Lib.isArrayOrTypedArray(ids);
var labels = trace.labels;
var parents = trace.parents;
var values = trace.values;
var hasValues = Lib.isArrayOrTypedArray(values);
var cd = [];
var parent2children = {};
var refs = {};
var addToLookup = function (parent, v) {
if (parent2children[parent]) parent2children[parent].push(v);else parent2children[parent] = [v];
refs[v] = 1;
};
// treat number `0` as valid
var isValidKey = function (k) {
return k || typeof k === 'number';
};
var isValidVal = function (i) {
return !hasValues || isNumeric(values[i]) && values[i] >= 0;
};
var len;
var isValid;
var getId;
if (hasIds) {
len = Math.min(ids.length, parents.length);
isValid = function (i) {
return isValidKey(ids[i]) && isValidVal(i);
};
getId = function (i) {
return String(ids[i]);
};
} else {
len = Math.min(labels.length, parents.length);
isValid = function (i) {
return isValidKey(labels[i]) && isValidVal(i);
};
// TODO We could allow some label / parent duplication
//
// From AJ:
// It would work OK for one level
// (multiple rows with the same name and different parents -
// or even the same parent) but if that name is then used as a parent
// which one is it?
getId = function (i) {
return String(labels[i]);
};
}
if (hasValues) len = Math.min(len, values.length);
for (var i = 0; i < len; i++) {
if (isValid(i)) {
var id = getId(i);
var pid = isValidKey(parents[i]) ? String(parents[i]) : '';
var cdi = {
i: i,
id: id,
pid: pid,
label: isValidKey(labels[i]) ? String(labels[i]) : ''
};
if (hasValues) cdi.v = +values[i];
cd.push(cdi);
addToLookup(pid, id);
}
}
if (!parent2children['']) {
var impliedRoots = [];
var k;
for (k in parent2children) {
if (!refs[k]) {
impliedRoots.push(k);
}
}
// if an `id` has no ref in the `parents` array,
// take it as being the root node
if (impliedRoots.length === 1) {
k = impliedRoots[0];
cd.unshift({
hasImpliedRoot: true,
id: k,
pid: '',
label: k
});
} else {
return Lib.warn(['Multiple implied roots, cannot build', trace.type, 'hierarchy of', trace.name + '.', 'These roots include:', impliedRoots.join(', ')].join(' '));
}
} else if (parent2children[''].length > 1) {
var dummyId = Lib.randstr();
// if multiple rows linked to the root node,
// add dummy "root of roots" node to make d3 build the hierarchy successfully
for (var j = 0; j < cd.length; j++) {
if (cd[j].pid === '') {
cd[j].pid = dummyId;
}
}
cd.unshift({
hasMultipleRoots: true,
id: dummyId,
pid: '',
label: ''
});
}
// TODO might be better to replace stratify() with our own algorithm
var root;
try {
root = d3Hierarchy.stratify().id(function (d) {
return d.id;
}).parentId(function (d) {
return d.pid;
})(cd);
} catch (e) {
return Lib.warn(['Failed to build', trace.type, 'hierarchy of', trace.name + '.', 'Error:', e.message].join(' '));
}
var hierarchy = d3Hierarchy.hierarchy(root);
var failed = false;
if (hasValues) {
switch (trace.branchvalues) {
case 'remainder':
hierarchy.sum(function (d) {
return d.data.v;
});
break;
case 'total':
hierarchy.each(function (d) {
var cdi = d.data.data;
var v = cdi.v;
if (d.children) {
var partialSum = d.children.reduce(function (a, c) {
return a + c.data.data.v;
}, 0);
// N.B. we must fill in `value` for generated sectors
// with the partialSum to compute the correct partition
if (cdi.hasImpliedRoot || cdi.hasMultipleRoots) {
v = partialSum;
}
if (v < partialSum * ALMOST_EQUAL) {
failed = true;
return Lib.warn(['Total value for node', d.data.data.id, 'of', trace.name, 'is smaller than the sum of its children.', '\nparent value =', v, '\nchildren sum =', partialSum].join(' '));
}
}
d.value = v;
});
break;
}
} else {
countDescendants(hierarchy, trace, {
branches: trace.count.indexOf('branches') !== -1,
leaves: trace.count.indexOf('leaves') !== -1
});
}
if (failed) return;
// TODO add way to sort by height also?
if (trace.sort) {
hierarchy.sort(function (a, b) {
return b.value - a.value;
});
}
var pullColor;
var scaleColor;
var colors = trace.marker.colors || [];
var hasColors = !!colors.length;
if (trace._hasColorscale) {
if (!hasColors) {
colors = hasValues ? trace.values : trace._values;
}
colorscaleCalc(gd, trace, {
vals: colors,
containerStr: 'marker',
cLetter: 'c'
});
scaleColor = makeColorScaleFn(trace.marker);
} else {
pullColor = makePullColorFn(fullLayout['_' + trace.type + 'colormap']);
}
// TODO keep track of 'root-children' (i.e. branch) for hover info etc.
hierarchy.each(function (d) {
var cdi = d.data.data;
// N.B. this mutates items in `cd`
cdi.color = trace._hasColorscale ? scaleColor(colors[cdi.i]) : pullColor(colors[cdi.i], cdi.id);
});
cd[0].hierarchy = hierarchy;
return cd;
};
/*
* `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
*/
exports._runCrossTraceCalc = function (desiredType, gd) {
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, desiredType === 'icicle' ? icicleExtendedColorWays : desiredType === 'treemap' ? treemapExtendedColorWays : sunburstExtendedColorWays);
}
var dfltColorCount = 0;
var rootColor;
function pickColor(d) {
var cdi = d.data.data;
var id = cdi.id;
if (cdi.color === false) {
if (colorMap[id]) {
// have we seen this label and assigned a color to it in a previous trace?
cdi.color = colorMap[id];
} else if (d.parent) {
if (d.parent.parent) {
// from third-level on, inherit from parent
cdi.color = d.parent.data.data.color;
} else {
// pick new color for second level
colorMap[id] = cdi.color = colorWay[dfltColorCount % colorWay.length];
dfltColorCount++;
}
} else {
// set root color. no coloring by default.
cdi.color = rootColor;
}
}
}
for (var i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var cd0 = cd[0];
if (cd0.trace.type === desiredType && cd0.hierarchy) {
rootColor = cd0.trace.root.color;
cd0.hierarchy.each(pickColor);
}
}
};
exports.crossTraceCalc = function (gd) {
return exports._runCrossTraceCalc('sunburst', gd);
};
function countDescendants(node, trace, opts) {
var nChild = 0;
var children = node.children;
if (children) {
var len = children.length;
for (var i = 0; i < len; i++) {
nChild += countDescendants(children[i], trace, opts);
}
if (opts.branches) nChild++; // count this branch
} else {
if (opts.leaves) nChild++; // count this leaf
}
// save to the node
node.value = node.data.data.value = nChild;
// save to the trace
if (!trace._values) trace._values = [];
trace._values[node.data.data.i] = nChild;
return nChild;
}
/***/ }),
/***/ 27328:
/***/ (function(module) {
"use strict";
module.exports = {
CLICK_TRANSITION_TIME: 750,
CLICK_TRANSITION_EASING: 'linear',
eventDataKeys: [
// string
'currentPath', 'root', 'entry',
// no need to add 'parent' here
// percentages i.e. ratios
'percentRoot', 'percentEntry', 'percentParent']
};
/***/ }),
/***/ 25244:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(424);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var handleText = (__webpack_require__(31508).handleText);
var handleMarkerDefaults = (__webpack_require__(74174).handleMarkerDefaults);
var Colorscale = __webpack_require__(8932);
var hasColorscale = Colorscale.hasColorscale;
var colorscaleDefaults = Colorscale.handleDefaults;
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var labels = coerce('labels');
var parents = coerce('parents');
if (!labels || !labels.length || !parents || !parents.length) {
traceOut.visible = false;
return;
}
var vals = coerce('values');
if (vals && vals.length) {
coerce('branchvalues');
} else {
coerce('count');
}
coerce('level');
coerce('maxdepth');
handleMarkerDefaults(traceIn, traceOut, layout, coerce);
var withColorscale = traceOut._hasColorscale = hasColorscale(traceIn, 'marker', 'colors') || (traceIn.marker || {}).coloraxis // N.B. special logic to consider "values" colorscales
;
if (withColorscale) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'marker.',
cLetter: 'c'
});
}
coerce('leaf.opacity', withColorscale ? 1 : 0.7);
var text = coerce('text');
coerce('texttemplate');
if (!traceOut.texttemplate) coerce('textinfo', Lib.isArrayOrTypedArray(text) ? 'text+label' : 'label');
coerce('hovertext');
coerce('hovertemplate');
var textposition = 'auto';
handleText(traceIn, traceOut, layout, coerce, textposition, {
moduleHasSelected: false,
moduleHasUnselected: false,
moduleHasConstrain: false,
moduleHasCliponaxis: false,
moduleHasTextangle: false,
moduleHasInsideanchor: false
});
coerce('insidetextorientation');
coerce('sort');
coerce('rotation');
coerce('root.color');
handleDomainDefaults(traceOut, layout, coerce);
// do not support transforms for now
traceOut._length = null;
};
/***/ }),
/***/ 60404:
/***/ (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, fadedColor) {
var cdi = pt.data.data;
var ptNumber = cdi.i;
var color = fadedColor || cdi.color;
if (ptNumber >= 0) {
pt.i = cdi.i;
var marker = trace.marker;
if (marker.pattern) {
if (!marker.colors || !marker.pattern.shape) {
marker.color = color;
pt.color = color;
}
} else {
marker.color = color;
pt.color = color;
}
Drawing.pointStyle(s, trace, gd, pt);
} else {
Color.fill(s, color);
}
};
/***/ }),
/***/ 45716:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Registry = __webpack_require__(24040);
var appendArrayPointValue = (__webpack_require__(10624).appendArrayPointValue);
var Fx = __webpack_require__(93024);
var Lib = __webpack_require__(3400);
var Events = __webpack_require__(95924);
var helpers = __webpack_require__(78176);
var pieHelpers = __webpack_require__(69656);
var formatValue = pieHelpers.formatPieValue;
module.exports = function attachFxHandlers(sliceTop, entry, gd, cd, opts) {
var cd0 = cd[0];
var trace = cd0.trace;
var hierarchy = cd0.hierarchy;
var isSunburst = trace.type === 'sunburst';
var isTreemapOrIcicle = trace.type === 'treemap' || trace.type === 'icicle';
// 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;
var onMouseOver = function (pt) {
var fullLayoutNow = gd._fullLayout;
if (gd._dragging || fullLayoutNow.hovermode === false) return;
var traceNow = gd._fullData[trace.index];
var cdi = pt.data.data;
var ptNumber = cdi.i;
var isRoot = helpers.isHierarchyRoot(pt);
var parent = helpers.getParent(hierarchy, pt);
var val = helpers.getValue(pt);
var _cast = function (astr) {
return Lib.castOption(traceNow, ptNumber, astr);
};
var hovertemplate = _cast('hovertemplate');
var hoverinfo = Fx.castHoverinfo(traceNow, fullLayoutNow, ptNumber);
var separators = fullLayoutNow.separators;
var eventData;
if (hovertemplate || hoverinfo && hoverinfo !== 'none' && hoverinfo !== 'skip') {
var hoverCenterX;
var hoverCenterY;
if (isSunburst) {
hoverCenterX = cd0.cx + pt.pxmid[0] * (1 - pt.rInscribed);
hoverCenterY = cd0.cy + pt.pxmid[1] * (1 - pt.rInscribed);
}
if (isTreemapOrIcicle) {
hoverCenterX = pt._hoverX;
hoverCenterY = pt._hoverY;
}
var hoverPt = {};
var parts = [];
var thisText = [];
var hasFlag = function (flag) {
return parts.indexOf(flag) !== -1;
};
if (hoverinfo) {
parts = hoverinfo === 'all' ? traceNow._module.attributes.hoverinfo.flags : hoverinfo.split('+');
}
hoverPt.label = cdi.label;
if (hasFlag('label') && hoverPt.label) thisText.push(hoverPt.label);
if (cdi.hasOwnProperty('v')) {
hoverPt.value = cdi.v;
hoverPt.valueLabel = formatValue(hoverPt.value, separators);
if (hasFlag('value')) thisText.push(hoverPt.valueLabel);
}
hoverPt.currentPath = pt.currentPath = helpers.getPath(pt.data);
if (hasFlag('current path') && !isRoot) {
thisText.push(hoverPt.currentPath);
}
var tx;
var allPercents = [];
var insertPercent = function () {
if (allPercents.indexOf(tx) === -1) {
// no need to add redundant info
thisText.push(tx);
allPercents.push(tx);
}
};
hoverPt.percentParent = pt.percentParent = val / helpers.getValue(parent);
hoverPt.parent = pt.parentString = helpers.getPtLabel(parent);
if (hasFlag('percent parent')) {
tx = helpers.formatPercent(hoverPt.percentParent, separators) + ' of ' + hoverPt.parent;
insertPercent();
}
hoverPt.percentEntry = pt.percentEntry = val / helpers.getValue(entry);
hoverPt.entry = pt.entry = helpers.getPtLabel(entry);
if (hasFlag('percent entry') && !isRoot && !pt.onPathbar) {
tx = helpers.formatPercent(hoverPt.percentEntry, separators) + ' of ' + hoverPt.entry;
insertPercent();
}
hoverPt.percentRoot = pt.percentRoot = val / helpers.getValue(hierarchy);
hoverPt.root = pt.root = helpers.getPtLabel(hierarchy);
if (hasFlag('percent root') && !isRoot) {
tx = helpers.formatPercent(hoverPt.percentRoot, separators) + ' of ' + hoverPt.root;
insertPercent();
}
hoverPt.text = _cast('hovertext') || _cast('text');
if (hasFlag('text')) {
tx = hoverPt.text;
if (Lib.isValidTextValue(tx)) thisText.push(tx);
}
eventData = [makeEventData(pt, traceNow, opts.eventDataKeys)];
var hoverItems = {
trace: traceNow,
y: hoverCenterY,
_x0: pt._x0,
_x1: pt._x1,
_y0: pt._y0,
_y1: pt._y1,
text: thisText.join(' '),
name: hovertemplate || hasFlag('name') ? traceNow.name : undefined,
color: _cast('hoverlabel.bgcolor') || cdi.color,
borderColor: _cast('hoverlabel.bordercolor'),
fontFamily: _cast('hoverlabel.font.family'),
fontSize: _cast('hoverlabel.font.size'),
fontColor: _cast('hoverlabel.font.color'),
fontWeight: _cast('hoverlabel.font.weight'),
fontStyle: _cast('hoverlabel.font.style'),
fontVariant: _cast('hoverlabel.font.variant'),
nameLength: _cast('hoverlabel.namelength'),
textAlign: _cast('hoverlabel.align'),
hovertemplate: hovertemplate,
hovertemplateLabels: hoverPt,
eventData: eventData
};
if (isSunburst) {
hoverItems.x0 = hoverCenterX - pt.rInscribed * pt.rpx1;
hoverItems.x1 = hoverCenterX + pt.rInscribed * pt.rpx1;
hoverItems.idealAlign = pt.pxmid[0] < 0 ? 'left' : 'right';
}
if (isTreemapOrIcicle) {
hoverItems.x = hoverCenterX;
hoverItems.idealAlign = hoverCenterX < 0 ? 'left' : 'right';
}
var bbox = [];
Fx.loneHover(hoverItems, {
container: fullLayoutNow._hoverlayer.node(),
outerContainer: fullLayoutNow._paper.node(),
gd: gd,
inOut_bbox: bbox
});
eventData[0].bbox = bbox[0];
trace._hasHoverLabel = true;
}
if (isTreemapOrIcicle) {
var slice = sliceTop.select('path.surface');
opts.styleOne(slice, pt, traceNow, gd, {
hovered: true
});
}
trace._hasHoverEvent = true;
gd.emit('plotly_hover', {
points: eventData || [makeEventData(pt, traceNow, opts.eventDataKeys)],
event: d3.event
});
};
var onMouseOut = function (evt) {
var fullLayoutNow = gd._fullLayout;
var traceNow = gd._fullData[trace.index];
var pt = d3.select(this).datum();
if (trace._hasHoverEvent) {
evt.originalEvent = d3.event;
gd.emit('plotly_unhover', {
points: [makeEventData(pt, traceNow, opts.eventDataKeys)],
event: d3.event
});
trace._hasHoverEvent = false;
}
if (trace._hasHoverLabel) {
Fx.loneUnhover(fullLayoutNow._hoverlayer.node());
trace._hasHoverLabel = false;
}
if (isTreemapOrIcicle) {
var slice = sliceTop.select('path.surface');
opts.styleOne(slice, pt, traceNow, gd, {
hovered: false
});
}
};
var onClick = 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 fullLayoutNow = gd._fullLayout;
var traceNow = gd._fullData[trace.index];
var noTransition = isSunburst && (helpers.isHierarchyRoot(pt) || helpers.isLeaf(pt));
var id = helpers.getPtId(pt);
var nextEntry = helpers.isEntry(pt) ? helpers.findEntryWithChild(hierarchy, id) : helpers.findEntryWithLevel(hierarchy, id);
var nextLevel = helpers.getPtId(nextEntry);
var typeClickEvtData = {
points: [makeEventData(pt, traceNow, opts.eventDataKeys)],
event: d3.event
};
if (!noTransition) typeClickEvtData.nextLevel = nextLevel;
var clickVal = Events.triggerHandler(gd, 'plotly_' + trace.type + 'click', typeClickEvtData);
if (clickVal !== false && fullLayoutNow.hovermode) {
gd._hoverdata = [makeEventData(pt, traceNow, opts.eventDataKeys)];
Fx.click(gd, d3.event);
}
// if click does not trigger a transition, we're done!
if (noTransition) return;
// if custom handler returns false, we're done!
if (clickVal === false) return;
// skip if triggered from dragging a nearby cartesian subplot
if (gd._dragging) return;
// skip during transitions, to avoid potential bugs
// we could remove this check later
if (gd._transitioning) return;
// store 'old' level in guiEdit stash, so that subsequent Plotly.react
// calls with the same uirevision can start from the same entry
Registry.call('_storeDirectGUIEdit', traceNow, fullLayoutNow._tracePreGUI[traceNow.uid], {
level: traceNow.level
});
var frame = {
data: [{
level: nextLevel
}],
traces: [trace.index]
};
var animOpts = {
frame: {
redraw: false,
duration: opts.transitionTime
},
transition: {
duration: opts.transitionTime,
easing: opts.transitionEasing
},
mode: 'immediate',
fromcurrent: true
};
Fx.loneUnhover(fullLayoutNow._hoverlayer.node());
Registry.call('animate', gd, frame, animOpts);
};
sliceTop.on('mouseover', onMouseOver);
sliceTop.on('mouseout', onMouseOut);
sliceTop.on('click', onClick);
};
function makeEventData(pt, trace, keys) {
var cdi = pt.data.data;
var out = {
curveNumber: trace.index,
pointNumber: cdi.i,
data: trace._input,
fullData: trace
// TODO more things like 'children', 'siblings', 'hierarchy?
};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key in pt) out[key] = pt[key];
}
// handle special case of parent
if ('parentString' in pt && !helpers.isHierarchyRoot(pt)) out.parent = pt.parentString;
appendArrayPointValue(out, trace, cdi.i);
return out;
}
/***/ }),
/***/ 78176:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var setCursor = __webpack_require__(93972);
var pieHelpers = __webpack_require__(69656);
exports.findEntryWithLevel = function (hierarchy, level) {
var out;
if (level) {
hierarchy.eachAfter(function (pt) {
if (exports.getPtId(pt) === level) {
return out = pt.copy();
}
});
}
return out || hierarchy;
};
exports.findEntryWithChild = function (hierarchy, childId) {
var out;
hierarchy.eachAfter(function (pt) {
var children = pt.children || [];
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (exports.getPtId(child) === childId) {
return out = pt.copy();
}
}
});
return out || hierarchy;
};
exports.isEntry = function (pt) {
return !pt.parent;
};
exports.isLeaf = function (pt) {
return !pt.children;
};
exports.getPtId = function (pt) {
return pt.data.data.id;
};
exports.getPtLabel = function (pt) {
return pt.data.data.label;
};
exports.getValue = function (d) {
return d.value;
};
exports.isHierarchyRoot = function (pt) {
return getParentId(pt) === '';
};
exports.setSliceCursor = function (sliceTop, gd, opts) {
var hide = opts.isTransitioning;
if (!hide) {
var pt = sliceTop.datum();
hide = opts.hideOnRoot && exports.isHierarchyRoot(pt) || opts.hideOnLeaves && exports.isLeaf(pt);
}
setCursor(sliceTop, hide ? null : 'pointer');
};
function determineOutsideTextFont(trace, pt, layoutFont) {
return {
color: exports.getOutsideTextFontKey('color', trace, pt, layoutFont),
family: exports.getOutsideTextFontKey('family', trace, pt, layoutFont),
size: exports.getOutsideTextFontKey('size', trace, pt, layoutFont),
weight: exports.getOutsideTextFontKey('weight', trace, pt, layoutFont),
style: exports.getOutsideTextFontKey('style', trace, pt, layoutFont),
variant: exports.getOutsideTextFontKey('variant', trace, pt, layoutFont),
textcase: exports.getOutsideTextFontKey('textcase', trace, pt, layoutFont),
lineposition: exports.getOutsideTextFontKey('lineposition', trace, pt, layoutFont),
shadow: exports.getOutsideTextFontKey('shadow', trace, pt, layoutFont)
};
}
function determineInsideTextFont(trace, pt, layoutFont, opts) {
var onPathbar = (opts || {}).onPathbar;
var cdi = pt.data.data;
var ptNumber = cdi.i;
var customColor = Lib.castOption(trace, ptNumber, (onPathbar ? 'pathbar.textfont' : 'insidetextfont') + '.color');
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 = Lib.castOption(trace._input, ptNumber, 'textfont.color');
}
return {
color: customColor || Color.contrast(cdi.color),
family: exports.getInsideTextFontKey('family', trace, pt, layoutFont, opts),
size: exports.getInsideTextFontKey('size', trace, pt, layoutFont, opts),
weight: exports.getInsideTextFontKey('weight', trace, pt, layoutFont, opts),
style: exports.getInsideTextFontKey('style', trace, pt, layoutFont, opts),
variant: exports.getInsideTextFontKey('variant', trace, pt, layoutFont, opts),
textcase: exports.getInsideTextFontKey('textcase', trace, pt, layoutFont, opts),
lineposition: exports.getInsideTextFontKey('lineposition', trace, pt, layoutFont, opts),
shadow: exports.getInsideTextFontKey('shadow', trace, pt, layoutFont, opts)
};
}
exports.getInsideTextFontKey = function (keyStr, trace, pt, layoutFont, opts) {
var onPathbar = (opts || {}).onPathbar;
var cont = onPathbar ? 'pathbar.textfont' : 'insidetextfont';
var ptNumber = pt.data.data.i;
return Lib.castOption(trace, ptNumber, cont + '.' + keyStr) || Lib.castOption(trace, ptNumber, 'textfont.' + keyStr) || layoutFont.size;
};
exports.getOutsideTextFontKey = function (keyStr, trace, pt, layoutFont) {
var ptNumber = pt.data.data.i;
return Lib.castOption(trace, ptNumber, 'outsidetextfont.' + keyStr) || Lib.castOption(trace, ptNumber, 'textfont.' + keyStr) || layoutFont.size;
};
exports.isOutsideText = function (trace, pt) {
return !trace._hasColorscale && exports.isHierarchyRoot(pt);
};
exports.determineTextFont = function (trace, pt, layoutFont, opts) {
return exports.isOutsideText(trace, pt) ? determineOutsideTextFont(trace, pt, layoutFont) : determineInsideTextFont(trace, pt, layoutFont, opts);
};
exports.hasTransition = function (transitionOpts) {
// We could optimize hasTransition per trace,
// as sunburst, treemap & icicle have no cross-trace logic!
return !!(transitionOpts && transitionOpts.duration > 0);
};
exports.getMaxDepth = function (trace) {
return trace.maxdepth >= 0 ? trace.maxdepth : Infinity;
};
exports.isHeader = function (pt, trace) {
// it is only used in treemap.
return !(exports.isLeaf(pt) || pt.depth === trace._maxDepth - 1);
};
function getParentId(pt) {
return pt.data.data.pid;
}
exports.getParent = function (hierarchy, pt) {
return exports.findEntryWithLevel(hierarchy, getParentId(pt));
};
exports.listPath = function (d, keyStr) {
var parent = d.parent;
if (!parent) return [];
var list = keyStr ? [parent.data[keyStr]] : [parent];
return exports.listPath(parent, keyStr).concat(list);
};
exports.getPath = function (d) {
return exports.listPath(d, 'label').join('/') + '/';
};
exports.formatValue = pieHelpers.formatPieValue;
// TODO: should combine the two in a separate PR - Also please note Lib.formatPercent should support separators.
exports.formatPercent = function (v, separators) {
var tx = Lib.formatPercent(v, 0); // use funnel(area) version
if (tx === '0%') tx = pieHelpers.formatPiePercent(v, separators); // use pie version
return tx;
};
/***/ }),
/***/ 5621:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'sunburst',
basePlotModule: __webpack_require__(54904),
categories: [],
animatable: true,
attributes: __webpack_require__(424),
layoutAttributes: __webpack_require__(84920),
supplyDefaults: __webpack_require__(25244),
supplyLayoutDefaults: __webpack_require__(28732),
calc: (__webpack_require__(3776).calc),
crossTraceCalc: (__webpack_require__(3776).crossTraceCalc),
plot: (__webpack_require__(96488).plot),
style: (__webpack_require__(85676).style),
colorbar: __webpack_require__(5528),
meta: {}
};
/***/ }),
/***/ 84920:
/***/ (function(module) {
"use strict";
module.exports = {
sunburstcolorway: {
valType: 'colorlist',
editType: 'calc'
},
extendsunburstcolors: {
valType: 'boolean',
dflt: true,
editType: 'calc'
}
};
/***/ }),
/***/ 28732:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(84920);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
coerce('sunburstcolorway', layoutOut.colorway);
coerce('extendsunburstcolors');
};
/***/ }),
/***/ 96488:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var d3Hierarchy = __webpack_require__(74148);
var interpolate = (__webpack_require__(67756)/* .interpolate */ .qy);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var svgTextUtils = __webpack_require__(72736);
var uniformText = __webpack_require__(82744);
var recordMinTextSize = uniformText.recordMinTextSize;
var clearMinTextSize = uniformText.clearMinTextSize;
var piePlot = __webpack_require__(37820);
var getRotationAngle = (__webpack_require__(69656).getRotationAngle);
var computeTransform = piePlot.computeTransform;
var transformInsideText = piePlot.transformInsideText;
var styleOne = (__webpack_require__(85676).styleOne);
var resizeText = (__webpack_require__(60100).resizeText);
var attachFxHandlers = __webpack_require__(45716);
var constants = __webpack_require__(27328);
var helpers = __webpack_require__(78176);
exports.plot = function (gd, cdmodule, transitionOpts, makeOnCompleteCallback) {
var fullLayout = gd._fullLayout;
var layer = fullLayout._sunburstlayer;
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 = !fullLayout.uniformtext.mode && helpers.hasTransition(transitionOpts);
clearMinTextSize('sunburst', fullLayout);
join = layer.selectAll('g.trace.sunburst').data(cdmodule, function (cd) {
return cd[0].trace.uid;
});
// using same 'stroke-linejoin' as pie traces
join.enter().append('g').classed('trace', true).classed('sunburst', true).attr('stroke-linejoin', 'round');
join.order();
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!
layer.selectAll('g.trace').each(function (cd) {
plotOne(gd, cd, this, transitionOpts);
});
});
} else {
join.each(function (cd) {
plotOne(gd, cd, this, transitionOpts);
});
if (fullLayout.uniformtext.mode) {
resizeText(gd, fullLayout._sunburstlayer.selectAll('.trace'), 'sunburst');
}
}
if (isFullReplot) {
join.exit().remove();
}
};
function plotOne(gd, cd, element, transitionOpts) {
var isStatic = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
var hasTransition = !fullLayout.uniformtext.mode && helpers.hasTransition(transitionOpts);
var gTrace = d3.select(element);
var slices = gTrace.selectAll('g.slice');
var cd0 = cd[0];
var trace = cd0.trace;
var hierarchy = cd0.hierarchy;
var entry = helpers.findEntryWithLevel(hierarchy, trace.level);
var maxDepth = helpers.getMaxDepth(trace);
var gs = fullLayout._size;
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 rMax = 0.5 * Math.min(vpw, vph);
var cx = cd0.cx = gs.l + gs.w * (domain.x[1] + domain.x[0]) / 2;
var cy = cd0.cy = gs.t + gs.h * (1 - domain.y[0]) - vph / 2;
if (!entry) {
return slices.remove();
}
// previous root 'pt' (can be empty)
var prevEntry = null;
// stash of 'previous' position data used by tweening functions
var prevLookup = {};
if (hasTransition) {
// Important: do this before binding new sliceData!
slices.each(function (pt) {
prevLookup[helpers.getPtId(pt)] = {
rpx0: pt.rpx0,
rpx1: pt.rpx1,
x0: pt.x0,
x1: pt.x1,
transform: pt.transform
};
if (!prevEntry && helpers.isEntry(pt)) {
prevEntry = pt;
}
});
}
// N.B. slice data isn't the calcdata,
// grab corresponding calcdata item in sliceData[i].data.data
var sliceData = partition(entry).descendants();
var maxHeight = entry.height + 1;
var yOffset = 0;
var cutoff = maxDepth;
// N.B. handle multiple-root special case
if (cd0.hasMultipleRoots && helpers.isHierarchyRoot(entry)) {
sliceData = sliceData.slice(1);
maxHeight -= 1;
yOffset = 1;
cutoff += 1;
}
// filter out slices that won't show up on graph
sliceData = sliceData.filter(function (pt) {
return pt.y1 <= cutoff;
});
var baseX = getRotationAngle(trace.rotation);
if (baseX) {
sliceData.forEach(function (pt) {
pt.x0 += baseX;
pt.x1 += baseX;
});
}
// partition span ('y') to sector radial px value
var maxY = Math.min(maxHeight, maxDepth);
var y2rpx = function (y) {
return (y - yOffset) / maxY * rMax;
};
// (radial px value, partition angle ('x')) to px [x,y]
var rx2px = function (r, x) {
return [r * Math.cos(x), -r * Math.sin(x)];
};
// slice path generation fn
var pathSlice = function (d) {
return Lib.pathAnnulus(d.rpx0, d.rpx1, d.x0, d.x1, cx, cy);
};
// slice text translate x/y
var getTargetX = function (d) {
return cx + getTextXY(d)[0] * (d.transform.rCenter || 0) + (d.transform.x || 0);
};
var getTargetY = function (d) {
return cy + getTextXY(d)[1] * (d.transform.rCenter || 0) + (d.transform.y || 0);
};
slices = slices.data(sliceData, helpers.getPtId);
slices.enter().append('g').classed('slice', true);
if (hasTransition) {
slices.exit().transition().each(function () {
var sliceTop = d3.select(this);
var slicePath = sliceTop.select('path.surface');
slicePath.transition().attrTween('d', function (pt2) {
var interp = makeExitSliceInterpolator(pt2);
return function (t) {
return pathSlice(interp(t));
};
});
var sliceTextGroup = sliceTop.select('g.slicetext');
sliceTextGroup.attr('opacity', 0);
}).remove();
} else {
slices.exit().remove();
}
slices.order();
// next x1 (i.e. sector end angle) of previous entry
var nextX1ofPrevEntry = null;
if (hasTransition && prevEntry) {
var prevEntryId = helpers.getPtId(prevEntry);
slices.each(function (pt) {
if (nextX1ofPrevEntry === null && helpers.getPtId(pt) === prevEntryId) {
nextX1ofPrevEntry = pt.x1;
}
});
}
var updateSlices = slices;
if (hasTransition) {
updateSlices = updateSlices.transition().each('end', function () {
// N.B. gd._transitioning is (still) *true* by the time
// transition updates get here
var sliceTop = d3.select(this);
helpers.setSliceCursor(sliceTop, gd, {
hideOnRoot: true,
hideOnLeaves: true,
isTransitioning: false
});
});
}
updateSlices.each(function (pt) {
var sliceTop = d3.select(this);
var slicePath = Lib.ensureSingle(sliceTop, 'path', 'surface', function (s) {
s.style('pointer-events', isStatic ? 'none' : 'all');
});
pt.rpx0 = y2rpx(pt.y0);
pt.rpx1 = y2rpx(pt.y1);
pt.xmid = (pt.x0 + pt.x1) / 2;
pt.pxmid = rx2px(pt.rpx1, pt.xmid);
pt.midangle = -(pt.xmid - Math.PI / 2);
pt.startangle = -(pt.x0 - Math.PI / 2);
pt.stopangle = -(pt.x1 - Math.PI / 2);
pt.halfangle = 0.5 * Math.min(Lib.angleDelta(pt.x0, pt.x1) || Math.PI, Math.PI);
pt.ring = 1 - pt.rpx0 / pt.rpx1;
pt.rInscribed = getInscribedRadiusFraction(pt, trace);
if (hasTransition) {
slicePath.transition().attrTween('d', function (pt2) {
var interp = makeUpdateSliceInterpolator(pt2);
return function (t) {
return pathSlice(interp(t));
};
});
} else {
slicePath.attr('d', pathSlice);
}
sliceTop.call(attachFxHandlers, entry, gd, cd, {
eventDataKeys: constants.eventDataKeys,
transitionTime: constants.CLICK_TRANSITION_TIME,
transitionEasing: constants.CLICK_TRANSITION_EASING
}).call(helpers.setSliceCursor, gd, {
hideOnRoot: true,
hideOnLeaves: true,
isTransitioning: gd._transitioning
});
slicePath.call(styleOne, pt, trace, gd);
var sliceTextGroup = Lib.ensureSingle(sliceTop, 'g', 'slicetext');
var sliceText = Lib.ensureSingle(sliceTextGroup, '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, helpers.determineTextFont(trace, pt, fullLayout.font));
sliceText.text(exports.formatSliceLabel(pt, entry, trace, cd, fullLayout)).classed('slicetext', true).attr('text-anchor', 'middle').call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
// position the text relative to the slice
var textBB = Drawing.bBox(sliceText.node());
pt.transform = transformInsideText(textBB, pt, cd0);
pt.transform.targetX = getTargetX(pt);
pt.transform.targetY = getTargetY(pt);
var strTransform = function (d, textBB) {
var transform = d.transform;
computeTransform(transform, textBB);
transform.fontSize = font.size;
recordMinTextSize(trace.type, transform, fullLayout);
return Lib.getTextTransform(transform);
};
if (hasTransition) {
sliceText.transition().attrTween('transform', function (pt2) {
var interp = makeUpdateTextInterpolator(pt2);
return function (t) {
return strTransform(interp(t), textBB);
};
});
} else {
sliceText.attr('transform', strTransform(pt, textBB));
}
});
function makeExitSliceInterpolator(pt) {
var id = helpers.getPtId(pt);
var prev = prevLookup[id];
var entryPrev = prevLookup[helpers.getPtId(entry)];
var next;
if (entryPrev) {
var a = (pt.x1 > entryPrev.x1 ? 2 * Math.PI : 0) + baseX;
// if pt to remove:
// - if 'below' where the root-node used to be: shrink it radially inward
// - otherwise, collapse it clockwise or counterclockwise which ever is shortest to theta=0
next = pt.rpx1 < entryPrev.rpx1 ? {
x0: pt.x0,
x1: pt.x1,
rpx0: 0,
rpx1: 0
} : {
x0: a,
x1: a,
rpx0: pt.rpx0,
rpx1: pt.rpx1
};
} else {
// this happens when maxdepth is set, when leaves must
// be removed and the rootPt is new (i.e. does not have a 'prev' object)
var parent;
var parentId = helpers.getPtId(pt.parent);
slices.each(function (pt2) {
if (helpers.getPtId(pt2) === parentId) {
return parent = pt2;
}
});
var parentChildren = parent.children;
var ci;
parentChildren.forEach(function (pt2, i) {
if (helpers.getPtId(pt2) === id) {
return ci = i;
}
});
var n = parentChildren.length;
var interp = interpolate(parent.x0, parent.x1);
next = {
rpx0: rMax,
rpx1: rMax,
x0: interp(ci / n),
x1: interp((ci + 1) / n)
};
}
return interpolate(prev, next);
}
function makeUpdateSliceInterpolator(pt) {
var prev0 = prevLookup[helpers.getPtId(pt)];
var prev;
var next = {
x0: pt.x0,
x1: pt.x1,
rpx0: pt.rpx0,
rpx1: pt.rpx1
};
if (prev0) {
// if pt already on graph, this is easy
prev = prev0;
} else {
// for new pts:
if (prevEntry) {
// if trace was visible before
if (pt.parent) {
if (nextX1ofPrevEntry) {
// if new branch, twist it in clockwise or
// counterclockwise which ever is shorter to
// its final angle
var a = (pt.x1 > nextX1ofPrevEntry ? 2 * Math.PI : 0) + baseX;
prev = {
x0: a,
x1: a
};
} else {
// if new leaf (when maxdepth is set),
// grow it radially and angularly from
// its parent node
prev = {
rpx0: rMax,
rpx1: rMax
};
Lib.extendFlat(prev, interpX0X1FromParent(pt));
}
} else {
// if new root-node, grow it radially
prev = {
rpx0: 0,
rpx1: 0
};
}
} else {
// start sector of new traces from theta=0
prev = {
x0: baseX,
x1: baseX
};
}
}
return interpolate(prev, next);
}
function makeUpdateTextInterpolator(pt) {
var prev0 = prevLookup[helpers.getPtId(pt)];
var prev;
var transform = pt.transform;
if (prev0) {
prev = prev0;
} else {
prev = {
rpx1: pt.rpx1,
transform: {
textPosAngle: transform.textPosAngle,
scale: 0,
rotate: transform.rotate,
rCenter: transform.rCenter,
x: transform.x,
y: transform.y
}
};
// for new pts:
if (prevEntry) {
// if trace was visible before
if (pt.parent) {
if (nextX1ofPrevEntry) {
// if new branch, twist it in clockwise or
// counterclockwise which ever is shorter to
// its final angle
var a = pt.x1 > nextX1ofPrevEntry ? 2 * Math.PI : 0;
prev.x0 = prev.x1 = a;
} else {
// if leaf
Lib.extendFlat(prev, interpX0X1FromParent(pt));
}
} else {
// if new root-node
prev.x0 = prev.x1 = baseX;
}
} else {
// on new traces
prev.x0 = prev.x1 = baseX;
}
}
var textPosAngleFn = interpolate(prev.transform.textPosAngle, pt.transform.textPosAngle);
var rpx1Fn = interpolate(prev.rpx1, pt.rpx1);
var x0Fn = interpolate(prev.x0, pt.x0);
var x1Fn = interpolate(prev.x1, pt.x1);
var scaleFn = interpolate(prev.transform.scale, transform.scale);
var rotateFn = interpolate(prev.transform.rotate, transform.rotate);
// smooth out start/end from entry, to try to keep text inside sector
// while keeping transition smooth
var pow = transform.rCenter === 0 ? 3 : prev.transform.rCenter === 0 ? 1 / 3 : 1;
var _rCenterFn = interpolate(prev.transform.rCenter, transform.rCenter);
var rCenterFn = function (t) {
return _rCenterFn(Math.pow(t, pow));
};
return function (t) {
var rpx1 = rpx1Fn(t);
var x0 = x0Fn(t);
var x1 = x1Fn(t);
var rCenter = rCenterFn(t);
var pxmid = rx2px(rpx1, (x0 + x1) / 2);
var textPosAngle = textPosAngleFn(t);
var d = {
pxmid: pxmid,
rpx1: rpx1,
transform: {
textPosAngle: textPosAngle,
rCenter: rCenter,
x: transform.x,
y: transform.y
}
};
recordMinTextSize(trace.type, transform, fullLayout);
return {
transform: {
targetX: getTargetX(d),
targetY: getTargetY(d),
scale: scaleFn(t),
rotate: rotateFn(t),
rCenter: rCenter
}
};
};
}
function interpX0X1FromParent(pt) {
var parent = pt.parent;
var parentPrev = prevLookup[helpers.getPtId(parent)];
var out = {};
if (parentPrev) {
// if parent is visible
var parentChildren = parent.children;
var ci = parentChildren.indexOf(pt);
var n = parentChildren.length;
var interp = interpolate(parentPrev.x0, parentPrev.x1);
out.x0 = interp(ci / n);
out.x1 = interp(ci / n);
} else {
// w/o visible parent
// TODO !!! HOW ???
out.x0 = out.x1 = 0;
}
return out;
}
}
// x[0-1] keys are angles [radians]
// y[0-1] keys are hierarchy heights [integers]
function partition(entry) {
return d3Hierarchy.partition().size([2 * Math.PI, entry.height + 1])(entry);
}
exports.formatSliceLabel = function (pt, entry, trace, cd, fullLayout) {
var texttemplate = trace.texttemplate;
var textinfo = trace.textinfo;
if (!texttemplate && (!textinfo || textinfo === 'none')) {
return '';
}
var separators = fullLayout.separators;
var cd0 = cd[0];
var cdi = pt.data.data;
var hierarchy = cd0.hierarchy;
var isRoot = helpers.isHierarchyRoot(pt);
var parent = helpers.getParent(hierarchy, pt);
var val = helpers.getValue(pt);
if (!texttemplate) {
var parts = textinfo.split('+');
var hasFlag = function (flag) {
return parts.indexOf(flag) !== -1;
};
var thisText = [];
var tx;
if (hasFlag('label') && cdi.label) {
thisText.push(cdi.label);
}
if (cdi.hasOwnProperty('v') && hasFlag('value')) {
thisText.push(helpers.formatValue(cdi.v, separators));
}
if (!isRoot) {
if (hasFlag('current path')) {
thisText.push(helpers.getPath(pt.data));
}
var nPercent = 0;
if (hasFlag('percent parent')) nPercent++;
if (hasFlag('percent entry')) nPercent++;
if (hasFlag('percent root')) nPercent++;
var hasMultiplePercents = nPercent > 1;
if (nPercent) {
var percent;
var addPercent = function (key) {
tx = helpers.formatPercent(percent, separators);
if (hasMultiplePercents) tx += ' of ' + key;
thisText.push(tx);
};
if (hasFlag('percent parent') && !isRoot) {
percent = val / helpers.getValue(parent);
addPercent('parent');
}
if (hasFlag('percent entry')) {
percent = val / helpers.getValue(entry);
addPercent('entry');
}
if (hasFlag('percent root')) {
percent = val / helpers.getValue(hierarchy);
addPercent('root');
}
}
}
if (hasFlag('text')) {
tx = Lib.castOption(trace, cdi.i, 'text');
if (Lib.isValidTextValue(tx)) thisText.push(tx);
}
return thisText.join(' ');
}
var txt = Lib.castOption(trace, cdi.i, 'texttemplate');
if (!txt) return '';
var obj = {};
if (cdi.label) obj.label = cdi.label;
if (cdi.hasOwnProperty('v')) {
obj.value = cdi.v;
obj.valueLabel = helpers.formatValue(cdi.v, separators);
}
obj.currentPath = helpers.getPath(pt.data);
if (!isRoot) {
obj.percentParent = val / helpers.getValue(parent);
obj.percentParentLabel = helpers.formatPercent(obj.percentParent, separators);
obj.parent = helpers.getPtLabel(parent);
}
obj.percentEntry = val / helpers.getValue(entry);
obj.percentEntryLabel = helpers.formatPercent(obj.percentEntry, separators);
obj.entry = helpers.getPtLabel(entry);
obj.percentRoot = val / helpers.getValue(hierarchy);
obj.percentRootLabel = helpers.formatPercent(obj.percentRoot, separators);
obj.root = helpers.getPtLabel(hierarchy);
if (cdi.hasOwnProperty('color')) {
obj.color = cdi.color;
}
var ptTx = Lib.castOption(trace, cdi.i, 'text');
if (Lib.isValidTextValue(ptTx) || ptTx === '') obj.text = ptTx;
obj.customdata = Lib.castOption(trace, cdi.i, 'customdata');
return Lib.texttemplateString(txt, obj, fullLayout._d3locale, obj, trace._meta || {});
};
function getInscribedRadiusFraction(pt) {
if (pt.rpx0 === 0 && Lib.isFullCircle([pt.x0, pt.x1])) {
// special case of 100% with no hole
return 1;
} else {
return Math.max(0, Math.min(1 / (1 + 1 / Math.sin(pt.halfangle)), pt.ring / 2));
}
}
function getTextXY(d) {
return getCoords(d.rpx1, d.transform.textPosAngle);
}
function getCoords(r, angle) {
return [r * Math.sin(angle), -r * Math.cos(angle)];
}
/***/ }),
/***/ 85676:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
var Lib = __webpack_require__(3400);
var resizeText = (__webpack_require__(82744).resizeText);
var fillOne = __webpack_require__(60404);
function style(gd) {
var s = gd._fullLayout._sunburstlayer.selectAll('.trace');
resizeText(gd, s, 'sunburst');
s.each(function (cd) {
var gTrace = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
gTrace.style('opacity', trace.opacity);
gTrace.selectAll('path.surface').each(function (pt) {
d3.select(this).call(styleOne, pt, trace, gd);
});
});
}
function styleOne(s, pt, trace, gd) {
var cdi = pt.data.data;
var isLeaf = !pt.children;
var ptNumber = cdi.i;
var lineColor = Lib.castOption(trace, ptNumber, 'marker.line.color') || Color.defaultLine;
var lineWidth = Lib.castOption(trace, ptNumber, 'marker.line.width') || 0;
s.call(fillOne, pt, trace, gd).style('stroke-width', lineWidth).call(Color.stroke, lineColor).style('opacity', isLeaf ? trace.leaf.opacity : null);
}
module.exports = {
style: style,
styleOne: styleOne
};
/***/ }),
/***/ 16716:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var colorScaleAttrs = __webpack_require__(49084);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var baseAttrs = __webpack_require__(45464);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
function makeContourProjAttr(axLetter) {
return {
valType: 'boolean',
dflt: false
};
}
function makeContourAttr(axLetter) {
return {
show: {
valType: 'boolean',
dflt: false
},
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},
},
project: {
x: makeContourProjAttr('x'),
y: makeContourProjAttr('y'),
z: makeContourProjAttr('z')
},
color: {
valType: 'color',
dflt: Color.defaultLine
},
usecolormap: {
valType: 'boolean',
dflt: false
},
width: {
valType: 'number',
min: 1,
max: 16,
dflt: 2
},
highlight: {
valType: 'boolean',
dflt: true
},
highlightcolor: {
valType: 'color',
dflt: Color.defaultLine
},
highlightwidth: {
valType: 'number',
min: 1,
max: 16,
dflt: 2
}
};
}
var attrs = module.exports = overrideAll(extendFlat({
z: {
valType: 'data_array'
},
x: {
valType: 'data_array'
},
y: {
valType: 'data_array'
},
text: {
valType: 'string',
dflt: '',
arrayOk: true
},
hovertext: {
valType: 'string',
dflt: '',
arrayOk: true
},
hovertemplate: hovertemplateAttrs(),
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z'),
connectgaps: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
surfacecolor: {
valType: 'data_array'
}
}, colorScaleAttrs('', {
colorAttr: 'z or surfacecolor',
showScaleDflt: true,
autoColorDflt: false,
editTypeOverride: 'calc'
}), {
contours: {
x: makeContourAttr('x'),
y: makeContourAttr('y'),
z: makeContourAttr('z')
},
hidesurface: {
valType: 'boolean',
dflt: false
},
lightposition: {
x: {
valType: 'number',
min: -1e5,
max: 1e5,
dflt: 10
},
y: {
valType: 'number',
min: -1e5,
max: 1e5,
dflt: 1e4
},
z: {
valType: 'number',
min: -1e5,
max: 1e5,
dflt: 0
}
},
lighting: {
ambient: {
valType: 'number',
min: 0.00,
max: 1.0,
dflt: 0.8
},
diffuse: {
valType: 'number',
min: 0.00,
max: 1.00,
dflt: 0.8
},
specular: {
valType: 'number',
min: 0.00,
max: 2.00,
dflt: 0.05
},
roughness: {
valType: 'number',
min: 0.00,
max: 1.00,
dflt: 0.5
},
fresnel: {
valType: 'number',
min: 0.00,
max: 5.00,
dflt: 0.2
}
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1
},
opacityscale: {
valType: 'any',
editType: 'calc'
},
_deprecated: {
zauto: extendFlat({}, colorScaleAttrs.zauto, {}),
zmin: extendFlat({}, colorScaleAttrs.zmin, {}),
zmax: extendFlat({}, colorScaleAttrs.zmax, {})
},
hoverinfo: extendFlat({}, baseAttrs.hoverinfo),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
}), 'calc', 'nested');
attrs.x.editType = attrs.y.editType = attrs.z.editType = 'calc+clearAxisTypes';
attrs.transforms = undefined;
/***/ }),
/***/ 56576:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorscaleCalc = __webpack_require__(47128);
// Compute auto-z and autocolorscale if applicable
module.exports = function calc(gd, trace) {
if (trace.surfacecolor) {
colorscaleCalc(gd, trace, {
vals: trace.surfacecolor,
containerStr: '',
cLetter: 'c'
});
} else {
colorscaleCalc(gd, trace, {
vals: trace.z,
containerStr: '',
cLetter: 'c'
});
}
};
/***/ }),
/***/ 79164:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createSurface = (__webpack_require__(67792).gl_surface3d);
var ndarray = (__webpack_require__(67792).ndarray);
var ndarrayInterp2d = (__webpack_require__(67792).ndarray_linear_interpolate).d2;
var interp2d = __webpack_require__(70448);
var findEmpties = __webpack_require__(11240);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var parseColorScale = (__webpack_require__(33040).parseColorScale);
var str2RgbaArray = __webpack_require__(43080);
var extractOpts = (__webpack_require__(8932).extractOpts);
function SurfaceTrace(scene, surface, uid) {
this.scene = scene;
this.uid = uid;
this.surface = surface;
this.data = null;
this.showContour = [false, false, false];
this.contourStart = [null, null, null];
this.contourEnd = [null, null, null];
this.contourSize = [0, 0, 0];
this.minValues = [Infinity, Infinity, Infinity];
this.maxValues = [-Infinity, -Infinity, -Infinity];
this.dataScaleX = 1.0;
this.dataScaleY = 1.0;
this.refineData = true;
this.objectOffset = [0, 0, 0];
}
var proto = SurfaceTrace.prototype;
proto.getXat = function (a, b, calendar, axis) {
var v = !isArrayOrTypedArray(this.data.x) ? a : isArrayOrTypedArray(this.data.x[0]) ? this.data.x[b][a] : this.data.x[a];
return calendar === undefined ? v : axis.d2l(v, 0, calendar);
};
proto.getYat = function (a, b, calendar, axis) {
var v = !isArrayOrTypedArray(this.data.y) ? b : isArrayOrTypedArray(this.data.y[0]) ? this.data.y[b][a] : this.data.y[b];
return calendar === undefined ? v : axis.d2l(v, 0, calendar);
};
proto.getZat = function (a, b, calendar, axis) {
var v = this.data.z[b][a];
if (v === null && this.data.connectgaps && this.data._interpolatedZ) {
v = this.data._interpolatedZ[b][a];
}
return calendar === undefined ? v : axis.d2l(v, 0, calendar);
};
proto.handlePick = function (selection) {
if (selection.object === this.surface) {
var xRatio = (selection.data.index[0] - 1) / this.dataScaleX - 1;
var yRatio = (selection.data.index[1] - 1) / this.dataScaleY - 1;
var j = Math.max(Math.min(Math.round(xRatio), this.data.z[0].length - 1), 0);
var k = Math.max(Math.min(Math.round(yRatio), this.data._ylength - 1), 0);
selection.index = [j, k];
selection.traceCoordinate = [this.getXat(j, k), this.getYat(j, k), this.getZat(j, k)];
selection.dataCoordinate = [this.getXat(j, k, this.data.xcalendar, this.scene.fullSceneLayout.xaxis), this.getYat(j, k, this.data.ycalendar, this.scene.fullSceneLayout.yaxis), this.getZat(j, k, this.data.zcalendar, this.scene.fullSceneLayout.zaxis)];
for (var i = 0; i < 3; i++) {
var v = selection.dataCoordinate[i];
if (v !== null && v !== undefined) {
selection.dataCoordinate[i] *= this.scene.dataScale[i];
}
}
var text = this.data.hovertext || this.data.text;
if (isArrayOrTypedArray(text) && text[k] && text[k][j] !== undefined) {
selection.textLabel = text[k][j];
} else if (text) {
selection.textLabel = text;
} else {
selection.textLabel = '';
}
selection.data.dataCoordinate = selection.dataCoordinate.slice();
this.surface.highlight(selection.data);
// Snap spikes to data coordinate
this.scene.glplot.spikes.position = selection.dataCoordinate;
return true;
}
};
function isColormapCircular(colormap) {
var first = colormap[0].rgb;
var last = colormap[colormap.length - 1].rgb;
return first[0] === last[0] && first[1] === last[1] && first[2] === last[2] && first[3] === last[3];
}
var shortPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999];
function getPow(a, b) {
if (a < b) return 0;
var n = 0;
while (Math.floor(a % b) === 0) {
a /= b;
n++;
}
return n;
}
function getFactors(a) {
var powers = [];
for (var i = 0; i < shortPrimes.length; i++) {
var b = shortPrimes[i];
powers.push(getPow(a, b));
}
return powers;
}
function smallestDivisor(a) {
var A = getFactors(a);
var result = a;
for (var i = 0; i < shortPrimes.length; i++) {
if (A[i] > 0) {
result = shortPrimes[i];
break;
}
}
return result;
}
function leastCommonMultiple(a, b) {
if (a < 1 || b < 1) return undefined;
var A = getFactors(a);
var B = getFactors(b);
var n = 1;
for (var i = 0; i < shortPrimes.length; i++) {
n *= Math.pow(shortPrimes[i], Math.max(A[i], B[i]));
}
return n;
}
function arrayLCM(A) {
if (A.length === 0) return undefined;
var n = 1;
for (var i = 0; i < A.length; i++) {
n = leastCommonMultiple(n, A[i]);
}
return n;
}
proto.calcXnums = function (xlen) {
var i;
var nums = [];
for (i = 1; i < xlen; i++) {
var a = this.getXat(i - 1, 0);
var b = this.getXat(i, 0);
if (b !== a && a !== undefined && a !== null && b !== undefined && b !== null) {
nums[i - 1] = Math.abs(b - a);
} else {
nums[i - 1] = 0;
}
}
var totalDist = 0;
for (i = 1; i < xlen; i++) {
totalDist += nums[i - 1];
}
for (i = 1; i < xlen; i++) {
if (nums[i - 1] === 0) {
nums[i - 1] = 1;
} else {
nums[i - 1] = Math.round(totalDist / nums[i - 1]);
}
}
return nums;
};
proto.calcYnums = function (ylen) {
var i;
var nums = [];
for (i = 1; i < ylen; i++) {
var a = this.getYat(0, i - 1);
var b = this.getYat(0, i);
if (b !== a && a !== undefined && a !== null && b !== undefined && b !== null) {
nums[i - 1] = Math.abs(b - a);
} else {
nums[i - 1] = 0;
}
}
var totalDist = 0;
for (i = 1; i < ylen; i++) {
totalDist += nums[i - 1];
}
for (i = 1; i < ylen; i++) {
if (nums[i - 1] === 0) {
nums[i - 1] = 1;
} else {
nums[i - 1] = Math.round(totalDist / nums[i - 1]);
}
}
return nums;
};
var highlyComposites = [1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260];
var MIN_RESOLUTION = highlyComposites[9];
var MAX_RESOLUTION = highlyComposites[13];
proto.estimateScale = function (resSrc, axis) {
var nums = axis === 0 ? this.calcXnums(resSrc) : this.calcYnums(resSrc);
var resDst = 1 + arrayLCM(nums);
while (resDst < MIN_RESOLUTION) {
resDst *= 2;
}
while (resDst > MAX_RESOLUTION) {
resDst--;
resDst /= smallestDivisor(resDst);
resDst++;
if (resDst < MIN_RESOLUTION) {
// resDst = MIN_RESOLUTION; // option 1: use min resolution
resDst = MAX_RESOLUTION; // option 2: use max resolution
}
}
var scale = Math.round(resDst / resSrc);
return scale > 1 ? scale : 1;
};
// based on Mikola Lysenko's ndarray-homography
// see https://github.com/scijs/ndarray-homography
function fnHomography(out, inp, X) {
var w = X[8] + X[2] * inp[0] + X[5] * inp[1];
out[0] = (X[6] + X[0] * inp[0] + X[3] * inp[1]) / w;
out[1] = (X[7] + X[1] * inp[0] + X[4] * inp[1]) / w;
return out;
}
function homography(dest, src, X) {
warp(dest, src, fnHomography, X);
return dest;
}
// based on Mikola Lysenko's ndarray-warp
// see https://github.com/scijs/ndarray-warp
function warp(dest, src, func, X) {
var warped = [0, 0];
var ni = dest.shape[0];
var nj = dest.shape[1];
for (var i = 0; i < ni; i++) {
for (var j = 0; j < nj; j++) {
func(warped, [i, j], X);
dest.set(i, j, ndarrayInterp2d(src, warped[0], warped[1]));
}
}
return dest;
}
proto.refineCoords = function (coords) {
var scaleW = this.dataScaleX;
var scaleH = this.dataScaleY;
var width = coords[0].shape[0];
var height = coords[0].shape[1];
var newWidth = Math.floor(coords[0].shape[0] * scaleW + 1) | 0;
var newHeight = Math.floor(coords[0].shape[1] * scaleH + 1) | 0;
// Pad coords by +1
var padWidth = 1 + width + 1;
var padHeight = 1 + height + 1;
var padImg = ndarray(new Float32Array(padWidth * padHeight), [padWidth, padHeight]);
var X = [1 / scaleW, 0, 0, 0, 1 / scaleH, 0, 0, 0, 1];
for (var i = 0; i < coords.length; ++i) {
this.surface.padField(padImg, coords[i]);
var scaledImg = ndarray(new Float32Array(newWidth * newHeight), [newWidth, newHeight]);
homography(scaledImg, padImg, X);
coords[i] = scaledImg;
}
};
function insertIfNewLevel(arr, newValue) {
var found = false;
for (var k = 0; k < arr.length; k++) {
if (newValue === arr[k]) {
found = true;
break;
}
}
if (found === false) arr.push(newValue);
}
proto.setContourLevels = function () {
var newLevels = [[], [], []];
var useNewLevels = [false, false, false];
var needsUpdate = false;
var i, j, value;
for (i = 0; i < 3; ++i) {
if (this.showContour[i]) {
needsUpdate = true;
if (this.contourSize[i] > 0 && this.contourStart[i] !== null && this.contourEnd[i] !== null && this.contourEnd[i] > this.contourStart[i]) {
useNewLevels[i] = true;
for (j = this.contourStart[i]; j < this.contourEnd[i]; j += this.contourSize[i]) {
value = j * this.scene.dataScale[i];
insertIfNewLevel(newLevels[i], value);
}
}
}
}
if (needsUpdate) {
var allLevels = [[], [], []];
for (i = 0; i < 3; ++i) {
if (this.showContour[i]) {
allLevels[i] = useNewLevels[i] ? newLevels[i] : this.scene.contourLevels[i];
}
}
this.surface.update({
levels: allLevels
});
}
};
proto.update = function (data) {
var scene = this.scene;
var sceneLayout = scene.fullSceneLayout;
var surface = this.surface;
var colormap = parseColorScale(data);
var scaleFactor = scene.dataScale;
var xlen = data.z[0].length;
var ylen = data._ylength;
var contourLevels = scene.contourLevels;
// Save data
this.data = data;
/*
* Fill and transpose zdata.
* Consistent with 'heatmap' and 'contour', plotly 'surface'
* 'z' are such that sub-arrays correspond to y-coords
* and that the sub-array entries correspond to a x-coords,
* which is the transpose of 'gl-surface-plot'.
*/
var i, j, k, v;
var rawCoords = [];
for (i = 0; i < 3; i++) {
rawCoords[i] = [];
for (j = 0; j < xlen; j++) {
rawCoords[i][j] = [];
/*
for(k = 0; k < ylen; k++) {
rawCoords[i][j][k] = undefined;
}
*/
}
}
// coords x, y & z
for (j = 0; j < xlen; j++) {
for (k = 0; k < ylen; k++) {
rawCoords[0][j][k] = this.getXat(j, k, data.xcalendar, sceneLayout.xaxis);
rawCoords[1][j][k] = this.getYat(j, k, data.ycalendar, sceneLayout.yaxis);
rawCoords[2][j][k] = this.getZat(j, k, data.zcalendar, sceneLayout.zaxis);
}
}
if (data.connectgaps) {
data._emptypoints = findEmpties(rawCoords[2]);
interp2d(rawCoords[2], data._emptypoints);
data._interpolatedZ = [];
for (j = 0; j < xlen; j++) {
data._interpolatedZ[j] = [];
for (k = 0; k < ylen; k++) {
data._interpolatedZ[j][k] = rawCoords[2][j][k];
}
}
}
// Note: log axes are not defined in surfaces yet.
// but they could be defined here...
for (i = 0; i < 3; i++) {
for (j = 0; j < xlen; j++) {
for (k = 0; k < ylen; k++) {
v = rawCoords[i][j][k];
if (v === null || v === undefined) {
rawCoords[i][j][k] = NaN;
} else {
v = rawCoords[i][j][k] *= scaleFactor[i];
}
}
}
}
for (i = 0; i < 3; i++) {
for (j = 0; j < xlen; j++) {
for (k = 0; k < ylen; k++) {
v = rawCoords[i][j][k];
if (v !== null && v !== undefined) {
if (this.minValues[i] > v) {
this.minValues[i] = v;
}
if (this.maxValues[i] < v) {
this.maxValues[i] = v;
}
}
}
}
}
for (i = 0; i < 3; i++) {
this.objectOffset[i] = 0.5 * (this.minValues[i] + this.maxValues[i]);
}
for (i = 0; i < 3; i++) {
for (j = 0; j < xlen; j++) {
for (k = 0; k < ylen; k++) {
v = rawCoords[i][j][k];
if (v !== null && v !== undefined) {
rawCoords[i][j][k] -= this.objectOffset[i];
}
}
}
}
// convert processed raw data to Float32 matrices
var coords = [ndarray(new Float32Array(xlen * ylen), [xlen, ylen]), ndarray(new Float32Array(xlen * ylen), [xlen, ylen]), ndarray(new Float32Array(xlen * ylen), [xlen, ylen])];
for (i = 0; i < 3; i++) {
for (j = 0; j < xlen; j++) {
for (k = 0; k < ylen; k++) {
coords[i].set(j, k, rawCoords[i][j][k]);
}
}
}
rawCoords = []; // free memory
var params = {
colormap: colormap,
levels: [[], [], []],
showContour: [true, true, true],
showSurface: !data.hidesurface,
contourProject: [[false, false, false], [false, false, false], [false, false, false]],
contourWidth: [1, 1, 1],
contourColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
contourTint: [1, 1, 1],
dynamicColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
dynamicWidth: [1, 1, 1],
dynamicTint: [1, 1, 1],
opacityscale: data.opacityscale,
opacity: data.opacity
};
var cOpts = extractOpts(data);
params.intensityBounds = [cOpts.min, cOpts.max];
// Refine surface color if necessary
if (data.surfacecolor) {
var intensity = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]);
for (j = 0; j < xlen; j++) {
for (k = 0; k < ylen; k++) {
intensity.set(j, k, data.surfacecolor[k][j]);
}
}
coords.push(intensity);
} else {
// when 'z' is used as 'intensity',
// we must scale its value
params.intensityBounds[0] *= scaleFactor[2];
params.intensityBounds[1] *= scaleFactor[2];
}
if (MAX_RESOLUTION < coords[0].shape[0] || MAX_RESOLUTION < coords[0].shape[1]) {
this.refineData = false;
}
if (this.refineData === true) {
this.dataScaleX = this.estimateScale(coords[0].shape[0], 0);
this.dataScaleY = this.estimateScale(coords[0].shape[1], 1);
if (this.dataScaleX !== 1 || this.dataScaleY !== 1) {
this.refineCoords(coords);
}
}
if (data.surfacecolor) {
params.intensity = coords.pop();
}
var highlightEnable = [true, true, true];
var axis = ['x', 'y', 'z'];
for (i = 0; i < 3; ++i) {
var contourParams = data.contours[axis[i]];
highlightEnable[i] = contourParams.highlight;
params.showContour[i] = contourParams.show || contourParams.highlight;
if (!params.showContour[i]) continue;
params.contourProject[i] = [contourParams.project.x, contourParams.project.y, contourParams.project.z];
if (contourParams.show) {
this.showContour[i] = true;
params.levels[i] = contourLevels[i];
surface.highlightColor[i] = params.contourColor[i] = str2RgbaArray(contourParams.color);
if (contourParams.usecolormap) {
surface.highlightTint[i] = params.contourTint[i] = 0;
} else {
surface.highlightTint[i] = params.contourTint[i] = 1;
}
params.contourWidth[i] = contourParams.width;
this.contourStart[i] = contourParams.start;
this.contourEnd[i] = contourParams.end;
this.contourSize[i] = contourParams.size;
} else {
this.showContour[i] = false;
this.contourStart[i] = null;
this.contourEnd[i] = null;
this.contourSize[i] = 0;
}
if (contourParams.highlight) {
params.dynamicColor[i] = str2RgbaArray(contourParams.highlightcolor);
params.dynamicWidth[i] = contourParams.highlightwidth;
}
}
// see https://github.com/plotly/plotly.js/issues/940
if (isColormapCircular(colormap)) {
params.vertexColor = true;
}
params.objectOffset = this.objectOffset;
params.coords = coords;
surface.update(params);
surface.visible = data.visible;
surface.enableDynamic = highlightEnable;
surface.enableHighlight = highlightEnable;
surface.snapToData = true;
if ('lighting' in data) {
surface.ambientLight = data.lighting.ambient;
surface.diffuseLight = data.lighting.diffuse;
surface.specularLight = data.lighting.specular;
surface.roughness = data.lighting.roughness;
surface.fresnel = data.lighting.fresnel;
}
if ('lightposition' in data) {
surface.lightPosition = [data.lightposition.x, data.lightposition.y, data.lightposition.z];
}
};
proto.dispose = function () {
this.scene.glplot.remove(this.surface);
this.surface.dispose();
};
function createSurfaceTrace(scene, data) {
var gl = scene.glplot.gl;
var surface = createSurface({
gl: gl
});
var result = new SurfaceTrace(scene, surface, data.uid);
surface._trace = result;
result.update(data);
scene.glplot.add(surface);
return result;
}
module.exports = createSurfaceTrace;
/***/ }),
/***/ 60192:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(16716);
var MIN = 0.1; // Note: often we don't want the data cube to be disappeared
function createWave(n, minOpacity) {
var arr = [];
var steps = 32; // Max: 256
for (var i = 0; i < steps; i++) {
var u = i / (steps - 1);
var v = minOpacity + (1 - minOpacity) * (1 - Math.pow(Math.sin(n * u * Math.PI), 2));
arr.push([u, Math.max(0, Math.min(1, v))]);
}
return arr;
}
function isValidScaleArray(scl) {
var highestVal = 0;
if (!Array.isArray(scl) || scl.length < 2) return false;
if (!scl[0] || !scl[scl.length - 1]) return false;
if (+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;
for (var i = 0; i < scl.length; i++) {
var si = scl[i];
if (si.length !== 2 || +si[0] < highestVal) {
return false;
}
highestVal = +si[0];
}
return true;
}
function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
var i, j;
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var x = coerce('x');
var y = coerce('y');
var z = coerce('z');
if (!z || !z.length || (x ? x.length < 1 : false) || (y ? y.length < 1 : false)) {
traceOut.visible = false;
return;
}
traceOut._xlength = Array.isArray(x) && Lib.isArrayOrTypedArray(x[0]) ? z.length : z[0].length;
traceOut._ylength = z.length;
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
coerce('xhoverformat');
coerce('yhoverformat');
coerce('zhoverformat');
// Coerce remaining properties
['lighting.ambient', 'lighting.diffuse', 'lighting.specular', 'lighting.roughness', 'lighting.fresnel', 'lightposition.x', 'lightposition.y', 'lightposition.z', 'hidesurface', 'connectgaps', 'opacity'].forEach(function (x) {
coerce(x);
});
var surfaceColor = coerce('surfacecolor');
var dims = ['x', 'y', 'z'];
for (i = 0; i < 3; ++i) {
var contourDim = 'contours.' + dims[i];
var show = coerce(contourDim + '.show');
var highlight = coerce(contourDim + '.highlight');
if (show || highlight) {
for (j = 0; j < 3; ++j) {
coerce(contourDim + '.project.' + dims[j]);
}
}
if (show) {
coerce(contourDim + '.color');
coerce(contourDim + '.width');
coerce(contourDim + '.usecolormap');
}
if (highlight) {
coerce(contourDim + '.highlightcolor');
coerce(contourDim + '.highlightwidth');
}
coerce(contourDim + '.start');
coerce(contourDim + '.end');
coerce(contourDim + '.size');
}
// backward compatibility block
if (!surfaceColor) {
mapLegacy(traceIn, 'zmin', 'cmin');
mapLegacy(traceIn, 'zmax', 'cmax');
mapLegacy(traceIn, 'zauto', 'cauto');
}
// TODO if contours.?.usecolormap are false and hidesurface is true
// the colorbar shouldn't be shown by default
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'c'
});
opacityscaleDefaults(traceIn, traceOut, layout, coerce);
// disable 1D transforms - currently surface does NOT support column data like heatmap does
// you can use mesh3d for this use case, but not surface
traceOut._length = null;
}
function opacityscaleDefaults(traceIn, traceOut, layout, coerce) {
var opacityscale = coerce('opacityscale');
if (opacityscale === 'max') {
traceOut.opacityscale = [[0, MIN], [1, 1]];
} else if (opacityscale === 'min') {
traceOut.opacityscale = [[0, 1], [1, MIN]];
} else if (opacityscale === 'extremes') {
traceOut.opacityscale = createWave(1, MIN);
} else if (!isValidScaleArray(opacityscale)) {
traceOut.opacityscale = undefined;
}
}
function mapLegacy(traceIn, oldAttr, newAttr) {
if (oldAttr in traceIn && !(newAttr in traceIn)) {
traceIn[newAttr] = traceIn[oldAttr];
}
}
module.exports = {
supplyDefaults: supplyDefaults,
opacityscaleDefaults: opacityscaleDefaults
};
/***/ }),
/***/ 91304:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(16716),
supplyDefaults: (__webpack_require__(60192).supplyDefaults),
colorbar: {
min: 'cmin',
max: 'cmax'
},
calc: __webpack_require__(56576),
plot: __webpack_require__(79164),
moduleType: 'trace',
name: 'surface',
basePlotModule: __webpack_require__(12536),
categories: ['gl3d', '2dMap', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 60520:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var annAttrs = __webpack_require__(13916);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var fontAttrs = __webpack_require__(25376);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var descriptionOnlyNumbers = (__webpack_require__(29736).descriptionOnlyNumbers);
var attrs = module.exports = overrideAll({
domain: domainAttrs({
name: 'table',
trace: true
}),
columnwidth: {
valType: 'number',
arrayOk: true,
dflt: null
},
columnorder: {
valType: 'data_array'
},
header: {
values: {
valType: 'data_array',
dflt: []
},
format: {
valType: 'data_array',
dflt: [],
description: descriptionOnlyNumbers('cell value')
},
prefix: {
valType: 'string',
arrayOk: true,
dflt: null
},
suffix: {
valType: 'string',
arrayOk: true,
dflt: null
},
height: {
valType: 'number',
dflt: 28
},
align: extendFlat({}, annAttrs.align, {
arrayOk: true
}),
line: {
width: {
valType: 'number',
arrayOk: true,
dflt: 1
},
color: {
valType: 'color',
arrayOk: true,
dflt: 'grey'
}
},
fill: {
color: {
valType: 'color',
arrayOk: true,
dflt: 'white'
}
},
font: extendFlat({}, fontAttrs({
arrayOk: true
}))
},
cells: {
values: {
valType: 'data_array',
dflt: []
},
format: {
valType: 'data_array',
dflt: [],
description: descriptionOnlyNumbers('cell value')
},
prefix: {
valType: 'string',
arrayOk: true,
dflt: null
},
suffix: {
valType: 'string',
arrayOk: true,
dflt: null
},
height: {
valType: 'number',
dflt: 20
},
align: extendFlat({}, annAttrs.align, {
arrayOk: true
}),
line: {
width: {
valType: 'number',
arrayOk: true,
dflt: 1
},
color: {
valType: 'color',
arrayOk: true,
dflt: 'grey'
}
},
fill: {
color: {
valType: 'color',
arrayOk: true,
dflt: 'white'
}
},
font: extendFlat({}, fontAttrs({
arrayOk: true
}))
}
}, 'calc', 'from-root');
attrs.transforms = undefined;
/***/ }),
/***/ 85852:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var getModuleCalcData = (__webpack_require__(84888)/* .getModuleCalcData */ ._M);
var tablePlot = __webpack_require__(24752);
var TABLE = 'table';
exports.name = TABLE;
exports.plot = function (gd) {
var calcData = getModuleCalcData(gd.calcdata, TABLE)[0];
if (calcData.length) tablePlot(gd, calcData);
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var hadTable = oldFullLayout._has && oldFullLayout._has(TABLE);
var hasTable = newFullLayout._has && newFullLayout._has(TABLE);
if (hadTable && !hasTable) {
oldFullLayout._paperdiv.selectAll('.table').remove();
}
};
/***/ }),
/***/ 39312:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var wrap = (__webpack_require__(71688).wrap);
module.exports = function calc() {
// we don't actually need to include the trace here, since that will be added
// by Plots.doCalcdata, and that's all we actually need later.
return wrap({});
};
/***/ }),
/***/ 23536:
/***/ (function(module) {
"use strict";
module.exports = {
cellPad: 8,
columnExtentOffset: 10,
columnTitleOffset: 28,
emptyHeaderHeight: 16,
latexCheck: /^\$.*\$$/,
goldenRatio: 1.618,
lineBreaker: ' ',
maxDimensionCount: 60,
overdrag: 45,
releaseTransitionDuration: 120,
releaseTransitionEase: 'cubic-out',
scrollbarCaptureWidth: 18,
scrollbarHideDelay: 1000,
scrollbarHideDuration: 1000,
scrollbarOffset: 5,
scrollbarWidth: 8,
transitionDuration: 100,
transitionEase: 'cubic-out',
uplift: 5,
wrapSpacer: ' ',
wrapSplitCharacter: ' ',
cn: {
// general class names
table: 'table',
tableControlView: 'table-control-view',
scrollBackground: 'scroll-background',
yColumn: 'y-column',
columnBlock: 'column-block',
scrollAreaClip: 'scroll-area-clip',
scrollAreaClipRect: 'scroll-area-clip-rect',
columnBoundary: 'column-boundary',
columnBoundaryClippath: 'column-boundary-clippath',
columnBoundaryRect: 'column-boundary-rect',
columnCells: 'column-cells',
columnCell: 'column-cell',
cellRect: 'cell-rect',
cellText: 'cell-text',
cellTextHolder: 'cell-text-holder',
// scroll related class names
scrollbarKit: 'scrollbar-kit',
scrollbar: 'scrollbar',
scrollbarSlider: 'scrollbar-slider',
scrollbarGlyph: 'scrollbar-glyph',
scrollbarCaptureZone: 'scrollbar-capture-zone'
}
};
/***/ }),
/***/ 55992:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var c = __webpack_require__(23536);
var extendFlat = (__webpack_require__(92880).extendFlat);
var isNumeric = __webpack_require__(38248);
var isTypedArray = (__webpack_require__(38116).isTypedArray);
var isArrayOrTypedArray = (__webpack_require__(38116).isArrayOrTypedArray);
// pure functions, don't alter but passes on `gd` and parts of `trace` without deep copying
module.exports = function calc(gd, trace) {
var cellsValues = squareStringMatrix(trace.cells.values);
var slicer = function (a) {
return a.slice(trace.header.values.length, a.length);
};
var headerValuesIn = squareStringMatrix(trace.header.values);
if (headerValuesIn.length && !headerValuesIn[0].length) {
headerValuesIn[0] = [''];
headerValuesIn = squareStringMatrix(headerValuesIn);
}
var headerValues = headerValuesIn.concat(slicer(cellsValues).map(function () {
return emptyStrings((headerValuesIn[0] || ['']).length);
}));
var domain = trace.domain;
var groupWidth = Math.floor(gd._fullLayout._size.w * (domain.x[1] - domain.x[0]));
var groupHeight = Math.floor(gd._fullLayout._size.h * (domain.y[1] - domain.y[0]));
var headerRowHeights = trace.header.values.length ? headerValues[0].map(function () {
return trace.header.height;
}) : [c.emptyHeaderHeight];
var rowHeights = cellsValues.length ? cellsValues[0].map(function () {
return trace.cells.height;
}) : [];
var headerHeight = headerRowHeights.reduce(sum, 0);
var scrollHeight = groupHeight - headerHeight;
var minimumFillHeight = scrollHeight + c.uplift;
var anchorToRowBlock = makeAnchorToRowBlock(rowHeights, minimumFillHeight);
var anchorToHeaderRowBlock = makeAnchorToRowBlock(headerRowHeights, headerHeight);
var headerRowBlocks = makeRowBlock(anchorToHeaderRowBlock, []);
var rowBlocks = makeRowBlock(anchorToRowBlock, headerRowBlocks);
var uniqueKeys = {};
var columnOrder = trace._fullInput.columnorder;
if (isArrayOrTypedArray(columnOrder)) columnOrder = Array.from(columnOrder);
columnOrder = columnOrder.concat(slicer(cellsValues.map(function (d, i) {
return i;
})));
var columnWidths = headerValues.map(function (d, i) {
var value = isArrayOrTypedArray(trace.columnwidth) ? trace.columnwidth[Math.min(i, trace.columnwidth.length - 1)] : trace.columnwidth;
return isNumeric(value) ? Number(value) : 1;
});
var totalColumnWidths = columnWidths.reduce(sum, 0);
// fit columns in the available vertical space as there's no vertical scrolling now
columnWidths = columnWidths.map(function (d) {
return d / totalColumnWidths * groupWidth;
});
var maxLineWidth = Math.max(arrayMax(trace.header.line.width), arrayMax(trace.cells.line.width));
var calcdata = {
// include staticPlot in the key so if it changes we delete and redraw
key: trace.uid + gd._context.staticPlot,
translateX: domain.x[0] * gd._fullLayout._size.w,
translateY: gd._fullLayout._size.h * (1 - domain.y[1]),
size: gd._fullLayout._size,
width: groupWidth,
maxLineWidth: maxLineWidth,
height: groupHeight,
columnOrder: columnOrder,
// will be mutated on column move, todo use in callback
groupHeight: groupHeight,
rowBlocks: rowBlocks,
headerRowBlocks: headerRowBlocks,
scrollY: 0,
// will be mutated on scroll
cells: extendFlat({}, trace.cells, {
values: cellsValues
}),
headerCells: extendFlat({}, trace.header, {
values: headerValues
}),
gdColumns: headerValues.map(function (d) {
return d[0];
}),
gdColumnsOriginalOrder: headerValues.map(function (d) {
return d[0];
}),
prevPages: [0, 0],
scrollbarState: {
scrollbarScrollInProgress: false
},
columns: headerValues.map(function (label, i) {
var foundKey = uniqueKeys[label];
uniqueKeys[label] = (foundKey || 0) + 1;
var key = label + '__' + uniqueKeys[label];
return {
key: key,
label: label,
specIndex: i,
xIndex: columnOrder[i],
xScale: xScale,
x: undefined,
// initialized below
calcdata: undefined,
// initialized below
columnWidth: columnWidths[i]
};
})
};
calcdata.columns.forEach(function (col) {
col.calcdata = calcdata;
col.x = xScale(col);
});
return calcdata;
};
function arrayMax(maybeArray) {
if (isArrayOrTypedArray(maybeArray)) {
var max = 0;
for (var i = 0; i < maybeArray.length; i++) {
max = Math.max(max, arrayMax(maybeArray[i]));
}
return max;
}
return maybeArray;
}
function sum(a, b) {
return a + b;
}
// fill matrix in place to equal lengths
// and ensure it's uniformly 2D
function squareStringMatrix(matrixIn) {
var matrix = matrixIn.slice();
var minLen = Infinity;
var maxLen = 0;
var i;
for (i = 0; i < matrix.length; i++) {
if (isTypedArray(matrix[i])) matrix[i] = Array.from(matrix[i]);else if (!isArrayOrTypedArray(matrix[i])) matrix[i] = [matrix[i]];
minLen = Math.min(minLen, matrix[i].length);
maxLen = Math.max(maxLen, matrix[i].length);
}
if (minLen !== maxLen) {
for (i = 0; i < matrix.length; i++) {
var padLen = maxLen - matrix[i].length;
if (padLen) matrix[i] = matrix[i].concat(emptyStrings(padLen));
}
}
return matrix;
}
function emptyStrings(len) {
var padArray = new Array(len);
for (var j = 0; j < len; j++) padArray[j] = '';
return padArray;
}
function xScale(d) {
return d.calcdata.columns.reduce(function (prev, next) {
return next.xIndex < d.xIndex ? prev + next.columnWidth : prev;
}, 0);
}
function makeRowBlock(anchorToRowBlock, auxiliary) {
var blockAnchorKeys = Object.keys(anchorToRowBlock);
return blockAnchorKeys.map(function (k) {
return extendFlat({}, anchorToRowBlock[k], {
auxiliaryBlocks: auxiliary
});
});
}
function makeAnchorToRowBlock(rowHeights, minimumFillHeight) {
var anchorToRowBlock = {};
var currentRowHeight;
var currentAnchor = 0;
var currentBlockHeight = 0;
var currentBlock = makeIdentity();
var currentFirstRowIndex = 0;
var blockCounter = 0;
for (var i = 0; i < rowHeights.length; i++) {
currentRowHeight = rowHeights[i];
currentBlock.rows.push({
rowIndex: i,
rowHeight: currentRowHeight
});
currentBlockHeight += currentRowHeight;
if (currentBlockHeight >= minimumFillHeight || i === rowHeights.length - 1) {
anchorToRowBlock[currentAnchor] = currentBlock;
currentBlock.key = blockCounter++;
currentBlock.firstRowIndex = currentFirstRowIndex;
currentBlock.lastRowIndex = i;
currentBlock = makeIdentity();
currentAnchor += currentBlockHeight;
currentFirstRowIndex = i + 1;
currentBlockHeight = 0;
}
}
return anchorToRowBlock;
}
function makeIdentity() {
return {
firstRowIndex: null,
lastRowIndex: null,
rows: []
};
}
/***/ }),
/***/ 53056:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var extendFlat = (__webpack_require__(92880).extendFlat);
// pure functions, don't alter but passes on `gd` and parts of `trace` without deep copying
exports.splitToPanels = function (d) {
var prevPages = [0, 0];
var headerPanel = extendFlat({}, d, {
key: 'header',
type: 'header',
page: 0,
prevPages: prevPages,
currentRepaint: [null, null],
dragHandle: true,
values: d.calcdata.headerCells.values[d.specIndex],
rowBlocks: d.calcdata.headerRowBlocks,
calcdata: extendFlat({}, d.calcdata, {
cells: d.calcdata.headerCells
})
});
var revolverPanel1 = extendFlat({}, d, {
key: 'cells1',
type: 'cells',
page: 0,
prevPages: prevPages,
currentRepaint: [null, null],
dragHandle: false,
values: d.calcdata.cells.values[d.specIndex],
rowBlocks: d.calcdata.rowBlocks
});
var revolverPanel2 = extendFlat({}, d, {
key: 'cells2',
type: 'cells',
page: 1,
prevPages: prevPages,
currentRepaint: [null, null],
dragHandle: false,
values: d.calcdata.cells.values[d.specIndex],
rowBlocks: d.calcdata.rowBlocks
});
// order due to SVG using painter's algo:
return [revolverPanel1, revolverPanel2, headerPanel];
};
exports.splitToCells = function (d) {
var fromTo = rowFromTo(d);
return (d.values || []).slice(fromTo[0], fromTo[1]).map(function (v, i) {
// By keeping identical key, a DOM node removal, creation and addition is spared, important when visible
// grid has a lot of elements (quadratic with xcol/ycol count).
// But it has to be busted when `svgUtil.convertToTspans` is used as it reshapes cell subtrees asynchronously,
// and by that time the user may have scrolled away, resulting in stale overwrites. The real solution will be
// to turn `svgUtil.convertToTspans` into a cancelable request, in which case no key busting is needed.
var buster = typeof v === 'string' && v.match(/[<$&> ]/) ? '_keybuster_' + Math.random() : '';
return {
// keyWithinBlock: /*fromTo[0] + */i, // optimized future version - no busting
// keyWithinBlock: fromTo[0] + i, // initial always-unoptimized version - janky scrolling with 5+ columns
keyWithinBlock: i + buster,
// current compromise: regular content is very fast; async content is possible
key: fromTo[0] + i,
column: d,
calcdata: d.calcdata,
page: d.page,
rowBlocks: d.rowBlocks,
value: v
};
});
};
function rowFromTo(d) {
var rowBlock = d.rowBlocks[d.page];
// fixme rowBlock truthiness check is due to ugly hack of placing 2nd panel as d.page = -1
var rowFrom = rowBlock ? rowBlock.rows[0].rowIndex : 0;
var rowTo = rowBlock ? rowFrom + rowBlock.rows.length : 0;
return [rowFrom, rowTo];
}
/***/ }),
/***/ 53212:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(60520);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
function defaultColumnOrder(traceOut, coerce) {
var specifiedColumnOrder = traceOut.columnorder || [];
var commonLength = traceOut.header.values.length;
var truncated = specifiedColumnOrder.slice(0, commonLength);
var sorted = truncated.slice().sort(function (a, b) {
return a - b;
});
var oneStepped = truncated.map(function (d) {
return sorted.indexOf(d);
});
for (var i = oneStepped.length; i < commonLength; i++) {
oneStepped.push(i);
}
coerce('columnorder', oneStepped);
}
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
handleDomainDefaults(traceOut, layout, coerce);
coerce('columnwidth');
coerce('header.values');
coerce('header.format');
coerce('header.align');
coerce('header.prefix');
coerce('header.suffix');
coerce('header.height');
coerce('header.line.width');
coerce('header.line.color');
coerce('header.fill.color');
Lib.coerceFont(coerce, 'header.font', layout.font);
defaultColumnOrder(traceOut, coerce);
coerce('cells.values');
coerce('cells.format');
coerce('cells.align');
coerce('cells.prefix');
coerce('cells.suffix');
coerce('cells.height');
coerce('cells.line.width');
coerce('cells.line.color');
coerce('cells.fill.color');
Lib.coerceFont(coerce, 'cells.font', layout.font);
// disable 1D transforms
traceOut._length = null;
};
/***/ }),
/***/ 41724:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(60520),
supplyDefaults: __webpack_require__(53212),
calc: __webpack_require__(39312),
plot: __webpack_require__(24752),
moduleType: 'trace',
name: 'table',
basePlotModule: __webpack_require__(85852),
categories: ['noOpacity'],
meta: {}
};
/***/ }),
/***/ 24752:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var c = __webpack_require__(23536);
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var numberFormat = Lib.numberFormat;
var gup = __webpack_require__(71688);
var Drawing = __webpack_require__(43616);
var svgUtil = __webpack_require__(72736);
var raiseToTop = (__webpack_require__(3400).raiseToTop);
var strTranslate = (__webpack_require__(3400).strTranslate);
var cancelEeaseColumn = (__webpack_require__(3400).cancelTransition);
var prepareData = __webpack_require__(55992);
var splitData = __webpack_require__(53056);
var Color = __webpack_require__(76308);
module.exports = function plot(gd, wrappedTraceHolders) {
var dynamic = !gd._context.staticPlot;
var table = gd._fullLayout._paper.selectAll('.' + c.cn.table).data(wrappedTraceHolders.map(function (wrappedTraceHolder) {
var traceHolder = gup.unwrap(wrappedTraceHolder);
var trace = traceHolder.trace;
return prepareData(gd, trace);
}), gup.keyFun);
table.exit().remove();
table.enter().append('g').classed(c.cn.table, true).attr('overflow', 'visible').style('box-sizing', 'content-box').style('position', 'absolute').style('left', 0).style('overflow', 'visible').style('shape-rendering', 'crispEdges').style('pointer-events', 'all');
table.attr('width', function (d) {
return d.width + d.size.l + d.size.r;
}).attr('height', function (d) {
return d.height + d.size.t + d.size.b;
}).attr('transform', function (d) {
return strTranslate(d.translateX, d.translateY);
});
var tableControlView = table.selectAll('.' + c.cn.tableControlView).data(gup.repeat, gup.keyFun);
var cvEnter = tableControlView.enter().append('g').classed(c.cn.tableControlView, true).style('box-sizing', 'content-box');
if (dynamic) {
var wheelEvent = 'onwheel' in document ? 'wheel' : 'mousewheel';
cvEnter.on('mousemove', function (d) {
tableControlView.filter(function (dd) {
return d === dd;
}).call(renderScrollbarKit, gd);
}).on(wheelEvent, function (d) {
if (d.scrollbarState.wheeling) return;
d.scrollbarState.wheeling = true;
var newY = d.scrollY + d3.event.deltaY;
var noChange = makeDragRow(gd, tableControlView, null, newY)(d);
if (!noChange) {
d3.event.stopPropagation();
d3.event.preventDefault();
}
d.scrollbarState.wheeling = false;
}).call(renderScrollbarKit, gd, true);
}
tableControlView.attr('transform', function (d) {
return strTranslate(d.size.l, d.size.t);
});
// scrollBackground merely ensures that mouse events are captured even on crazy fast scrollwheeling
// otherwise rendering glitches may occur
var scrollBackground = tableControlView.selectAll('.' + c.cn.scrollBackground).data(gup.repeat, gup.keyFun);
scrollBackground.enter().append('rect').classed(c.cn.scrollBackground, true).attr('fill', 'none');
scrollBackground.attr('width', function (d) {
return d.width;
}).attr('height', function (d) {
return d.height;
});
tableControlView.each(function (d) {
Drawing.setClipUrl(d3.select(this), scrollAreaBottomClipKey(gd, d), gd);
});
var yColumn = tableControlView.selectAll('.' + c.cn.yColumn).data(function (vm) {
return vm.columns;
}, gup.keyFun);
yColumn.enter().append('g').classed(c.cn.yColumn, true);
yColumn.exit().remove();
yColumn.attr('transform', function (d) {
return strTranslate(d.x, 0);
});
if (dynamic) {
yColumn.call(d3.behavior.drag().origin(function (d) {
var movedColumn = d3.select(this);
easeColumn(movedColumn, d, -c.uplift);
raiseToTop(this);
d.calcdata.columnDragInProgress = true;
renderScrollbarKit(tableControlView.filter(function (dd) {
return d.calcdata.key === dd.key;
}), gd);
return d;
}).on('drag', function (d) {
var movedColumn = d3.select(this);
var getter = function (dd) {
return (d === dd ? d3.event.x : dd.x) + dd.columnWidth / 2;
};
d.x = Math.max(-c.overdrag, Math.min(d.calcdata.width + c.overdrag - d.columnWidth, d3.event.x));
var sortableColumns = flatData(yColumn).filter(function (dd) {
return dd.calcdata.key === d.calcdata.key;
});
var newOrder = sortableColumns.sort(function (a, b) {
return getter(a) - getter(b);
});
newOrder.forEach(function (dd, i) {
dd.xIndex = i;
dd.x = d === dd ? dd.x : dd.xScale(dd);
});
yColumn.filter(function (dd) {
return d !== dd;
}).transition().ease(c.transitionEase).duration(c.transitionDuration).attr('transform', function (d) {
return strTranslate(d.x, 0);
});
movedColumn.call(cancelEeaseColumn).attr('transform', strTranslate(d.x, -c.uplift));
}).on('dragend', function (d) {
var movedColumn = d3.select(this);
var p = d.calcdata;
d.x = d.xScale(d);
d.calcdata.columnDragInProgress = false;
easeColumn(movedColumn, d, 0);
columnMoved(gd, p, p.columns.map(function (dd) {
return dd.xIndex;
}));
}));
}
yColumn.each(function (d) {
Drawing.setClipUrl(d3.select(this), columnBoundaryClipKey(gd, d), gd);
});
var columnBlock = yColumn.selectAll('.' + c.cn.columnBlock).data(splitData.splitToPanels, gup.keyFun);
columnBlock.enter().append('g').classed(c.cn.columnBlock, true).attr('id', function (d) {
return d.key;
});
columnBlock.style('cursor', function (d) {
return d.dragHandle ? 'ew-resize' : d.calcdata.scrollbarState.barWiggleRoom ? 'ns-resize' : 'default';
});
var headerColumnBlock = columnBlock.filter(headerBlock);
var cellsColumnBlock = columnBlock.filter(cellsBlock);
if (dynamic) {
cellsColumnBlock.call(d3.behavior.drag().origin(function (d) {
d3.event.stopPropagation();
return d;
}).on('drag', makeDragRow(gd, tableControlView, -1)).on('dragend', function () {
// fixme emit plotly notification
}));
}
// initial rendering: header is rendered first, as it may may have async LaTeX (show header first)
// but blocks are _entered_ the way they are due to painter's algo (header on top)
renderColumnCellTree(gd, tableControlView, headerColumnBlock, columnBlock);
renderColumnCellTree(gd, tableControlView, cellsColumnBlock, columnBlock);
var scrollAreaClip = tableControlView.selectAll('.' + c.cn.scrollAreaClip).data(gup.repeat, gup.keyFun);
scrollAreaClip.enter().append('clipPath').classed(c.cn.scrollAreaClip, true).attr('id', function (d) {
return scrollAreaBottomClipKey(gd, d);
});
var scrollAreaClipRect = scrollAreaClip.selectAll('.' + c.cn.scrollAreaClipRect).data(gup.repeat, gup.keyFun);
scrollAreaClipRect.enter().append('rect').classed(c.cn.scrollAreaClipRect, true).attr('x', -c.overdrag).attr('y', -c.uplift).attr('fill', 'none');
scrollAreaClipRect.attr('width', function (d) {
return d.width + 2 * c.overdrag;
}).attr('height', function (d) {
return d.height + c.uplift;
});
var columnBoundary = yColumn.selectAll('.' + c.cn.columnBoundary).data(gup.repeat, gup.keyFun);
columnBoundary.enter().append('g').classed(c.cn.columnBoundary, true);
var columnBoundaryClippath = yColumn.selectAll('.' + c.cn.columnBoundaryClippath).data(gup.repeat, gup.keyFun);
// SVG spec doesn't mandate wrapping into a and doesn't seem to cause a speed difference
columnBoundaryClippath.enter().append('clipPath').classed(c.cn.columnBoundaryClippath, true);
columnBoundaryClippath.attr('id', function (d) {
return columnBoundaryClipKey(gd, d);
});
var columnBoundaryRect = columnBoundaryClippath.selectAll('.' + c.cn.columnBoundaryRect).data(gup.repeat, gup.keyFun);
columnBoundaryRect.enter().append('rect').classed(c.cn.columnBoundaryRect, true).attr('fill', 'none');
columnBoundaryRect.attr('width', function (d) {
return d.columnWidth + 2 * roundHalfWidth(d);
}).attr('height', function (d) {
return d.calcdata.height + 2 * roundHalfWidth(d) + c.uplift;
}).attr('x', function (d) {
return -roundHalfWidth(d);
}).attr('y', function (d) {
return -roundHalfWidth(d);
});
updateBlockYPosition(null, cellsColumnBlock, tableControlView);
};
function roundHalfWidth(d) {
return Math.ceil(d.calcdata.maxLineWidth / 2);
}
function scrollAreaBottomClipKey(gd, d) {
return 'clip' + gd._fullLayout._uid + '_scrollAreaBottomClip_' + d.key;
}
function columnBoundaryClipKey(gd, d) {
return 'clip' + gd._fullLayout._uid + '_columnBoundaryClippath_' + d.calcdata.key + '_' + d.specIndex;
}
function flatData(selection) {
return [].concat.apply([], selection.map(function (g) {
return g;
})).map(function (g) {
return g.__data__;
});
}
function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) {
function calcTotalHeight(d) {
var blocks = d.rowBlocks;
return firstRowAnchor(blocks, blocks.length - 1) + (blocks.length ? rowsHeight(blocks[blocks.length - 1], Infinity) : 1);
}
var scrollbarKit = tableControlView.selectAll('.' + c.cn.scrollbarKit).data(gup.repeat, gup.keyFun);
scrollbarKit.enter().append('g').classed(c.cn.scrollbarKit, true).style('shape-rendering', 'geometricPrecision');
scrollbarKit.each(function (d) {
var s = d.scrollbarState;
s.totalHeight = calcTotalHeight(d);
s.scrollableAreaHeight = d.groupHeight - headerHeight(d);
s.currentlyVisibleHeight = Math.min(s.totalHeight, s.scrollableAreaHeight);
s.ratio = s.currentlyVisibleHeight / s.totalHeight;
s.barLength = Math.max(s.ratio * s.currentlyVisibleHeight, c.goldenRatio * c.scrollbarWidth);
s.barWiggleRoom = s.currentlyVisibleHeight - s.barLength;
s.wiggleRoom = Math.max(0, s.totalHeight - s.scrollableAreaHeight);
s.topY = s.barWiggleRoom === 0 ? 0 : d.scrollY / s.wiggleRoom * s.barWiggleRoom;
s.bottomY = s.topY + s.barLength;
s.dragMultiplier = s.wiggleRoom / s.barWiggleRoom;
}).attr('transform', function (d) {
var xPosition = d.width + c.scrollbarWidth / 2 + c.scrollbarOffset;
return strTranslate(xPosition, headerHeight(d));
});
var scrollbar = scrollbarKit.selectAll('.' + c.cn.scrollbar).data(gup.repeat, gup.keyFun);
scrollbar.enter().append('g').classed(c.cn.scrollbar, true);
var scrollbarSlider = scrollbar.selectAll('.' + c.cn.scrollbarSlider).data(gup.repeat, gup.keyFun);
scrollbarSlider.enter().append('g').classed(c.cn.scrollbarSlider, true);
scrollbarSlider.attr('transform', function (d) {
return strTranslate(0, d.scrollbarState.topY || 0);
});
var scrollbarGlyph = scrollbarSlider.selectAll('.' + c.cn.scrollbarGlyph).data(gup.repeat, gup.keyFun);
scrollbarGlyph.enter().append('line').classed(c.cn.scrollbarGlyph, true).attr('stroke', 'black').attr('stroke-width', c.scrollbarWidth).attr('stroke-linecap', 'round').attr('y1', c.scrollbarWidth / 2);
scrollbarGlyph.attr('y2', function (d) {
return d.scrollbarState.barLength - c.scrollbarWidth / 2;
}).attr('stroke-opacity', function (d) {
return d.columnDragInProgress || !d.scrollbarState.barWiggleRoom || bypassVisibleBar ? 0 : 0.4;
});
// cancel transition: possible pending (also, delayed) transition
scrollbarGlyph.transition().delay(0).duration(0);
scrollbarGlyph.transition().delay(c.scrollbarHideDelay).duration(c.scrollbarHideDuration).attr('stroke-opacity', 0);
var scrollbarCaptureZone = scrollbar.selectAll('.' + c.cn.scrollbarCaptureZone).data(gup.repeat, gup.keyFun);
scrollbarCaptureZone.enter().append('line').classed(c.cn.scrollbarCaptureZone, true).attr('stroke', 'white').attr('stroke-opacity', 0.01) // some browser might get rid of a 0 opacity element
.attr('stroke-width', c.scrollbarCaptureWidth).attr('stroke-linecap', 'butt').attr('y1', 0).on('mousedown', function (d) {
var y = d3.event.y;
var bbox = this.getBoundingClientRect();
var s = d.scrollbarState;
var pixelVal = y - bbox.top;
var inverseScale = d3.scale.linear().domain([0, s.scrollableAreaHeight]).range([0, s.totalHeight]).clamp(true);
if (!(s.topY <= pixelVal && pixelVal <= s.bottomY)) {
makeDragRow(gd, tableControlView, null, inverseScale(pixelVal - s.barLength / 2))(d);
}
}).call(d3.behavior.drag().origin(function (d) {
d3.event.stopPropagation();
d.scrollbarState.scrollbarScrollInProgress = true;
return d;
}).on('drag', makeDragRow(gd, tableControlView)).on('dragend', function () {
// fixme emit Plotly event
}));
scrollbarCaptureZone.attr('y2', function (d) {
return d.scrollbarState.scrollableAreaHeight;
});
// Remove scroll glyph and capture zone on static plots
// as they don't render properly when converted to PDF
// in the Chrome PDF viewer
// https://github.com/plotly/streambed/issues/11618
if (gd._context.staticPlot) {
scrollbarGlyph.remove();
scrollbarCaptureZone.remove();
}
}
function renderColumnCellTree(gd, tableControlView, columnBlock, allColumnBlock) {
// fixme this perf hotspot
// this is performance critical code as scrolling calls it on every revolver switch
// it appears sufficiently fast but there are plenty of low-hanging fruits for performance optimization
var columnCells = renderColumnCells(columnBlock);
var columnCell = renderColumnCell(columnCells);
supplyStylingValues(columnCell);
var cellRect = renderCellRect(columnCell);
sizeAndStyleRect(cellRect);
var cellTextHolder = renderCellTextHolder(columnCell);
var cellText = renderCellText(cellTextHolder);
setFont(cellText);
populateCellText(cellText, tableControlView, allColumnBlock, gd);
// doing this at the end when text, and text stlying are set
setCellHeightAndPositionY(columnCell);
}
function renderColumnCells(columnBlock) {
var columnCells = columnBlock.selectAll('.' + c.cn.columnCells).data(gup.repeat, gup.keyFun);
columnCells.enter().append('g').classed(c.cn.columnCells, true);
columnCells.exit().remove();
return columnCells;
}
function renderColumnCell(columnCells) {
var columnCell = columnCells.selectAll('.' + c.cn.columnCell).data(splitData.splitToCells, function (d) {
return d.keyWithinBlock;
});
columnCell.enter().append('g').classed(c.cn.columnCell, true);
columnCell.exit().remove();
return columnCell;
}
function renderCellRect(columnCell) {
var cellRect = columnCell.selectAll('.' + c.cn.cellRect).data(gup.repeat, function (d) {
return d.keyWithinBlock;
});
cellRect.enter().append('rect').classed(c.cn.cellRect, true);
return cellRect;
}
function renderCellText(cellTextHolder) {
var cellText = cellTextHolder.selectAll('.' + c.cn.cellText).data(gup.repeat, function (d) {
return d.keyWithinBlock;
});
cellText.enter().append('text').classed(c.cn.cellText, true).style('cursor', function () {
return 'auto';
}).on('mousedown', function () {
d3.event.stopPropagation();
});
return cellText;
}
function renderCellTextHolder(columnCell) {
var cellTextHolder = columnCell.selectAll('.' + c.cn.cellTextHolder).data(gup.repeat, function (d) {
return d.keyWithinBlock;
});
cellTextHolder.enter().append('g').classed(c.cn.cellTextHolder, true).style('shape-rendering', 'geometricPrecision');
return cellTextHolder;
}
function supplyStylingValues(columnCell) {
columnCell.each(function (d, i) {
var spec = d.calcdata.cells.font;
var col = d.column.specIndex;
var font = {
size: gridPick(spec.size, col, i),
color: gridPick(spec.color, col, i),
family: gridPick(spec.family, col, i),
weight: gridPick(spec.weight, col, i),
style: gridPick(spec.style, col, i),
variant: gridPick(spec.variant, col, i),
textcase: gridPick(spec.textcase, col, i),
lineposition: gridPick(spec.lineposition, col, i),
shadow: gridPick(spec.shadow, col, i)
};
d.rowNumber = d.key;
d.align = gridPick(d.calcdata.cells.align, col, i);
d.cellBorderWidth = gridPick(d.calcdata.cells.line.width, col, i);
d.font = font;
});
}
function setFont(cellText) {
cellText.each(function (d) {
Drawing.font(d3.select(this), d.font);
});
}
function sizeAndStyleRect(cellRect) {
cellRect.attr('width', function (d) {
return d.column.columnWidth;
}).attr('stroke-width', function (d) {
return d.cellBorderWidth;
}).each(function (d) {
var atomicSelection = d3.select(this);
Color.stroke(atomicSelection, gridPick(d.calcdata.cells.line.color, d.column.specIndex, d.rowNumber));
Color.fill(atomicSelection, gridPick(d.calcdata.cells.fill.color, d.column.specIndex, d.rowNumber));
});
}
function populateCellText(cellText, tableControlView, allColumnBlock, gd) {
cellText.text(function (d) {
var col = d.column.specIndex;
var row = d.rowNumber;
var userSuppliedContent = d.value;
var stringSupplied = typeof userSuppliedContent === 'string';
var hasBreaks = stringSupplied && userSuppliedContent.match(/ /i);
var userBrokenText = !stringSupplied || hasBreaks;
d.mayHaveMarkup = stringSupplied && userSuppliedContent.match(/[<&>]/);
var latex = isLatex(userSuppliedContent);
d.latex = latex;
var prefix = latex ? '' : gridPick(d.calcdata.cells.prefix, col, row) || '';
var suffix = latex ? '' : gridPick(d.calcdata.cells.suffix, col, row) || '';
var format = latex ? null : gridPick(d.calcdata.cells.format, col, row) || null;
var prefixSuffixedText = prefix + (format ? numberFormat(format)(d.value) : d.value) + suffix;
var hasWrapSplitCharacter;
d.wrappingNeeded = !d.wrapped && !userBrokenText && !latex && (hasWrapSplitCharacter = hasWrapCharacter(prefixSuffixedText));
d.cellHeightMayIncrease = hasBreaks || latex || d.mayHaveMarkup || (hasWrapSplitCharacter === void 0 ? hasWrapCharacter(prefixSuffixedText) : hasWrapSplitCharacter);
d.needsConvertToTspans = d.mayHaveMarkup || d.wrappingNeeded || d.latex;
var textToRender;
if (d.wrappingNeeded) {
var hrefPreservedText = c.wrapSplitCharacter === ' ' ? prefixSuffixedText.replace(/ pTop) {
pages.push(blockIndex);
}
pTop += rowsHeight;
// consider this nice final optimization; put it in `for` condition - caveat, currently the
// block.allRowsHeight relies on being invalidated, so enabling this opt may not be safe
// if(pages.length > 1) break;
}
return pages;
}
function updateBlockYPosition(gd, cellsColumnBlock, tableControlView) {
var d = flatData(cellsColumnBlock)[0];
if (d === undefined) return;
var blocks = d.rowBlocks;
var calcdata = d.calcdata;
var bottom = firstRowAnchor(blocks, blocks.length);
var scrollHeight = d.calcdata.groupHeight - headerHeight(d);
var scrollY = calcdata.scrollY = Math.max(0, Math.min(bottom - scrollHeight, calcdata.scrollY));
var pages = findPagesAndCacheHeights(blocks, scrollY, scrollHeight);
if (pages.length === 1) {
if (pages[0] === blocks.length - 1) {
pages.unshift(pages[0] - 1);
} else {
pages.push(pages[0] + 1);
}
}
// make phased out page jump by 2 while leaving stationary page intact
if (pages[0] % 2) {
pages.reverse();
}
cellsColumnBlock.each(function (d, i) {
// these values will also be needed when a block is translated again due to growing cell height
d.page = pages[i];
d.scrollY = scrollY;
});
cellsColumnBlock.attr('transform', function (d) {
var yTranslate = firstRowAnchor(d.rowBlocks, d.page) - d.scrollY;
return strTranslate(0, yTranslate);
});
// conditionally rerendering panel 0 and 1
if (gd) {
conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, d.prevPages, d, 0);
conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, d.prevPages, d, 1);
renderScrollbarKit(tableControlView, gd);
}
}
function makeDragRow(gd, allTableControlView, optionalMultiplier, optionalPosition) {
return function dragRow(eventD) {
// may come from whichever DOM event target: drag, wheel, bar... eventD corresponds to event target
var d = eventD.calcdata ? eventD.calcdata : eventD;
var tableControlView = allTableControlView.filter(function (dd) {
return d.key === dd.key;
});
var multiplier = optionalMultiplier || d.scrollbarState.dragMultiplier;
var initialScrollY = d.scrollY;
d.scrollY = optionalPosition === void 0 ? d.scrollY + multiplier * d3.event.dy : optionalPosition;
var cellsColumnBlock = tableControlView.selectAll('.' + c.cn.yColumn).selectAll('.' + c.cn.columnBlock).filter(cellsBlock);
updateBlockYPosition(gd, cellsColumnBlock, tableControlView);
// return false if we've "used" the scroll, ie it did something,
// so the event shouldn't bubble (if appropriate)
return d.scrollY === initialScrollY;
};
}
function conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, prevPages, d, revolverIndex) {
var shouldComponentUpdate = pages[revolverIndex] !== prevPages[revolverIndex];
if (shouldComponentUpdate) {
clearTimeout(d.currentRepaint[revolverIndex]);
d.currentRepaint[revolverIndex] = setTimeout(function () {
// setTimeout might lag rendering but yields a smoother scroll, because fast scrolling makes
// some repaints invisible ie. wasteful (DOM work blocks the main thread)
var toRerender = cellsColumnBlock.filter(function (d, i) {
return i === revolverIndex && pages[i] !== prevPages[i];
});
renderColumnCellTree(gd, tableControlView, toRerender, cellsColumnBlock);
prevPages[revolverIndex] = pages[revolverIndex];
});
}
}
function wrapTextMaker(columnBlock, element, tableControlView, gd) {
return function wrapText() {
var cellTextHolder = d3.select(element.parentNode);
cellTextHolder.each(function (d) {
var fragments = d.fragments;
cellTextHolder.selectAll('tspan.line').each(function (dd, i) {
fragments[i].width = this.getComputedTextLength();
});
// last element is only for measuring the separator character, so it's ignored:
var separatorLength = fragments[fragments.length - 1].width;
var rest = fragments.slice(0, -1);
var currentRow = [];
var currentAddition, currentAdditionLength;
var currentRowLength = 0;
var rowLengthLimit = d.column.columnWidth - 2 * c.cellPad;
d.value = '';
while (rest.length) {
currentAddition = rest.shift();
currentAdditionLength = currentAddition.width + separatorLength;
if (currentRowLength + currentAdditionLength > rowLengthLimit) {
d.value += currentRow.join(c.wrapSpacer) + c.lineBreaker;
currentRow = [];
currentRowLength = 0;
}
currentRow.push(currentAddition.text);
currentRowLength += currentAdditionLength;
}
if (currentRowLength) {
d.value += currentRow.join(c.wrapSpacer);
}
d.wrapped = true;
});
// the pre-wrapped text was rendered only for the text measurements
cellTextHolder.selectAll('tspan.line').remove();
// resupply text, now wrapped
populateCellText(cellTextHolder.select('.' + c.cn.cellText), tableControlView, columnBlock, gd);
d3.select(element.parentNode.parentNode).call(setCellHeightAndPositionY);
};
}
function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) {
return function updateYPosition() {
if (d.settledY) return;
var cellTextHolder = d3.select(element.parentNode);
var l = getBlock(d);
var rowIndex = d.key - l.firstRowIndex;
var declaredRowHeight = l.rows[rowIndex].rowHeight;
var requiredHeight = d.cellHeightMayIncrease ? element.parentNode.getBoundingClientRect().height + 2 * c.cellPad : declaredRowHeight;
var finalHeight = Math.max(requiredHeight, declaredRowHeight);
var increase = finalHeight - l.rows[rowIndex].rowHeight;
if (increase) {
// current row height increased
l.rows[rowIndex].rowHeight = finalHeight;
columnBlock.selectAll('.' + c.cn.columnCell).call(setCellHeightAndPositionY);
updateBlockYPosition(null, columnBlock.filter(cellsBlock), 0);
// if d.column.type === 'header', then the scrollbar has to be pushed downward to the scrollable area
// if d.column.type === 'cells', it can still be relevant if total scrolling content height is less than the
// scrollable window, as increases to row heights may need scrollbar updates
renderScrollbarKit(tableControlView, gd, true);
}
cellTextHolder.attr('transform', function () {
// this code block is only invoked for items where d.cellHeightMayIncrease is truthy
var element = this;
var columnCellElement = element.parentNode;
var box = columnCellElement.getBoundingClientRect();
var rectBox = d3.select(element.parentNode).select('.' + c.cn.cellRect).node().getBoundingClientRect();
var currentTransform = element.transform.baseVal.consolidate();
var yPosition = rectBox.top - box.top + (currentTransform ? currentTransform.matrix.f : c.cellPad);
return strTranslate(xPosition(d, d3.select(element.parentNode).select('.' + c.cn.cellTextHolder).node().getBoundingClientRect().width), yPosition);
});
d.settledY = true;
};
}
function xPosition(d, optionalWidth) {
switch (d.align) {
case 'left':
return c.cellPad;
case 'right':
return d.column.columnWidth - (optionalWidth || 0) - c.cellPad;
case 'center':
return (d.column.columnWidth - (optionalWidth || 0)) / 2;
default:
return c.cellPad;
}
}
function setCellHeightAndPositionY(columnCell) {
columnCell.attr('transform', function (d) {
var headerHeight = d.rowBlocks[0].auxiliaryBlocks.reduce(function (p, n) {
return p + rowsHeight(n, Infinity);
}, 0);
var l = getBlock(d);
var rowAnchor = rowsHeight(l, d.key);
var yOffset = rowAnchor + headerHeight;
return strTranslate(0, yOffset);
}).selectAll('.' + c.cn.cellRect).attr('height', function (d) {
return getRow(getBlock(d), d.key).rowHeight;
});
}
function firstRowAnchor(blocks, page) {
var total = 0;
for (var i = page - 1; i >= 0; i--) {
total += allRowsHeight(blocks[i]);
}
return total;
}
function rowsHeight(rowBlock, key) {
var total = 0;
for (var i = 0; i < rowBlock.rows.length && rowBlock.rows[i].rowIndex < key; i++) {
total += rowBlock.rows[i].rowHeight;
}
return total;
}
function allRowsHeight(rowBlock) {
var cached = rowBlock.allRowsHeight;
if (cached !== void 0) {
return cached;
}
var total = 0;
for (var i = 0; i < rowBlock.rows.length; i++) {
total += rowBlock.rows[i].rowHeight;
}
rowBlock.allRowsHeight = total;
return total;
}
function getBlock(d) {
return d.rowBlocks[d.page];
}
function getRow(l, i) {
return l.rows[i - l.firstRowIndex];
}
/***/ }),
/***/ 40516:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var colorScaleAttrs = __webpack_require__(49084);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var pieAttrs = __webpack_require__(74996);
var sunburstAttrs = __webpack_require__(424);
var constants = __webpack_require__(32984);
var extendFlat = (__webpack_require__(92880).extendFlat);
var pattern = (__webpack_require__(98192)/* .pattern */ .c);
module.exports = {
labels: sunburstAttrs.labels,
parents: sunburstAttrs.parents,
values: sunburstAttrs.values,
branchvalues: sunburstAttrs.branchvalues,
count: sunburstAttrs.count,
level: sunburstAttrs.level,
maxdepth: sunburstAttrs.maxdepth,
tiling: {
packing: {
valType: 'enumerated',
values: ['squarify', 'binary', 'dice', 'slice', 'slice-dice', 'dice-slice'],
dflt: 'squarify',
editType: 'plot'
},
squarifyratio: {
valType: 'number',
min: 1,
dflt: 1,
editType: 'plot'
},
flip: {
valType: 'flaglist',
flags: ['x', 'y'],
dflt: '',
editType: 'plot'
},
pad: {
valType: 'number',
min: 0,
dflt: 3,
editType: 'plot'
},
editType: 'calc'
},
marker: extendFlat({
pad: {
t: {
valType: 'number',
min: 0,
editType: 'plot'
},
l: {
valType: 'number',
min: 0,
editType: 'plot'
},
r: {
valType: 'number',
min: 0,
editType: 'plot'
},
b: {
valType: 'number',
min: 0,
editType: 'plot'
},
editType: 'calc'
},
colors: sunburstAttrs.marker.colors,
pattern: pattern,
depthfade: {
valType: 'enumerated',
values: [true, false, 'reversed'],
editType: 'style'
},
line: sunburstAttrs.marker.line,
cornerradius: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'plot'
},
editType: 'calc'
}, colorScaleAttrs('marker', {
colorAttr: 'colors',
anim: false // TODO: set to anim: true?
})),
pathbar: {
visible: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
side: {
valType: 'enumerated',
values: ['top', 'bottom'],
dflt: 'top',
editType: 'plot'
},
edgeshape: {
valType: 'enumerated',
values: ['>', '<', '|', '/', '\\'],
dflt: '>',
editType: 'plot'
},
thickness: {
valType: 'number',
min: 12,
editType: 'plot'
},
textfont: extendFlat({}, pieAttrs.textfont, {}),
editType: 'calc'
},
text: pieAttrs.text,
textinfo: sunburstAttrs.textinfo,
// TODO: incorporate `label` and `value` in the eventData
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: constants.eventDataKeys.concat(['label', 'value'])
}),
hovertext: pieAttrs.hovertext,
hoverinfo: sunburstAttrs.hoverinfo,
hovertemplate: hovertemplateAttrs({}, {
keys: constants.eventDataKeys
}),
textfont: pieAttrs.textfont,
insidetextfont: pieAttrs.insidetextfont,
outsidetextfont: extendFlat({}, pieAttrs.outsidetextfont, {}),
textposition: {
valType: 'enumerated',
values: ['top left', 'top center', 'top right', 'middle left', 'middle center', 'middle right', 'bottom left', 'bottom center', 'bottom right'],
dflt: 'top left',
editType: 'plot'
},
sort: pieAttrs.sort,
root: sunburstAttrs.root,
domain: domainAttrs({
name: 'treemap',
trace: true,
editType: 'calc'
})
};
/***/ }),
/***/ 79516:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var plots = __webpack_require__(7316);
exports.name = 'treemap';
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);
};
/***/ }),
/***/ 97840:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var calc = __webpack_require__(3776);
exports.r = function (gd, trace) {
return calc.calc(gd, trace);
};
exports.q = function (gd) {
return calc._runCrossTraceCalc('treemap', gd);
};
/***/ }),
/***/ 32984:
/***/ (function(module) {
"use strict";
module.exports = {
CLICK_TRANSITION_TIME: 750,
CLICK_TRANSITION_EASING: 'poly',
eventDataKeys: [
// string
'currentPath', 'root', 'entry',
// no need to add 'parent' here
// percentages i.e. ratios
'percentRoot', 'percentEntry', 'percentParent'],
gapWithPathbar: 1 // i.e. one pixel
};
/***/ }),
/***/ 34092:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(40516);
var Color = __webpack_require__(76308);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var handleText = (__webpack_require__(31508).handleText);
var TEXTPAD = (__webpack_require__(78048).TEXTPAD);
var handleMarkerDefaults = (__webpack_require__(74174).handleMarkerDefaults);
var Colorscale = __webpack_require__(8932);
var hasColorscale = Colorscale.hasColorscale;
var colorscaleDefaults = Colorscale.handleDefaults;
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var labels = coerce('labels');
var parents = coerce('parents');
if (!labels || !labels.length || !parents || !parents.length) {
traceOut.visible = false;
return;
}
var vals = coerce('values');
if (vals && vals.length) {
coerce('branchvalues');
} else {
coerce('count');
}
coerce('level');
coerce('maxdepth');
var packing = coerce('tiling.packing');
if (packing === 'squarify') {
coerce('tiling.squarifyratio');
}
coerce('tiling.flip');
coerce('tiling.pad');
var text = coerce('text');
coerce('texttemplate');
if (!traceOut.texttemplate) coerce('textinfo', Lib.isArrayOrTypedArray(text) ? 'text+label' : 'label');
coerce('hovertext');
coerce('hovertemplate');
var hasPathbar = coerce('pathbar.visible');
var textposition = 'auto';
handleText(traceIn, traceOut, layout, coerce, textposition, {
hasPathbar: hasPathbar,
moduleHasSelected: false,
moduleHasUnselected: false,
moduleHasConstrain: false,
moduleHasCliponaxis: false,
moduleHasTextangle: false,
moduleHasInsideanchor: false
});
coerce('textposition');
var bottomText = traceOut.textposition.indexOf('bottom') !== -1;
handleMarkerDefaults(traceIn, traceOut, layout, coerce);
var withColorscale = traceOut._hasColorscale = hasColorscale(traceIn, 'marker', 'colors') || (traceIn.marker || {}).coloraxis // N.B. special logic to consider "values" colorscales
;
if (withColorscale) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'marker.',
cLetter: 'c'
});
} else {
coerce('marker.depthfade', !(traceOut.marker.colors || []).length);
}
var headerSize = traceOut.textfont.size * 2;
coerce('marker.pad.t', bottomText ? headerSize / 4 : headerSize);
coerce('marker.pad.l', headerSize / 4);
coerce('marker.pad.r', headerSize / 4);
coerce('marker.pad.b', bottomText ? headerSize : headerSize / 4);
coerce('marker.cornerradius');
traceOut._hovered = {
marker: {
line: {
width: 2,
color: Color.contrast(layout.paper_bgcolor)
}
}
};
if (hasPathbar) {
// This works even for multi-line labels as treemap pathbar trim out line breaks
coerce('pathbar.thickness', traceOut.pathbar.textfont.size + 2 * TEXTPAD);
coerce('pathbar.side');
coerce('pathbar.edgeshape');
}
coerce('sort');
coerce('root.color');
handleDomainDefaults(traceOut, layout, coerce);
// do not support transforms for now
traceOut._length = null;
};
/***/ }),
/***/ 95808:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var helpers = __webpack_require__(78176);
var uniformText = __webpack_require__(82744);
var clearMinTextSize = uniformText.clearMinTextSize;
var resizeText = (__webpack_require__(60100).resizeText);
var plotOne = __webpack_require__(52960);
module.exports = function _plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback, opts) {
var type = opts.type;
var drawDescendants = opts.drawDescendants;
var fullLayout = gd._fullLayout;
var layer = fullLayout['_' + type + 'layer'];
var join, onComplete;
// If transition config is provided, then it is only a partial replot and traces not
// updated are removed.
var isFullReplot = !transitionOpts;
clearMinTextSize(type, fullLayout);
join = layer.selectAll('g.trace.' + type).data(cdmodule, function (cd) {
return cd[0].trace.uid;
});
join.enter().append('g').classed('trace', true).classed(type, true);
join.order();
if (!fullLayout.uniformtext.mode && helpers.hasTransition(transitionOpts)) {
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!
layer.selectAll('g.trace').each(function (cd) {
plotOne(gd, cd, this, transitionOpts, drawDescendants);
});
});
} else {
join.each(function (cd) {
plotOne(gd, cd, this, transitionOpts, drawDescendants);
});
if (fullLayout.uniformtext.mode) {
resizeText(gd, layer.selectAll('.trace'), type);
}
}
if (isFullReplot) {
join.exit().remove();
}
};
/***/ }),
/***/ 27336:
/***/ (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 svgTextUtils = __webpack_require__(72736);
var partition = __webpack_require__(13832);
var styleOne = (__webpack_require__(66192).styleOne);
var constants = __webpack_require__(32984);
var helpers = __webpack_require__(78176);
var attachFxHandlers = __webpack_require__(45716);
var onPathbar = true; // for Ancestors
module.exports = function drawAncestors(gd, cd, entry, slices, opts) {
var barDifY = opts.barDifY;
var width = opts.width;
var height = opts.height;
var viewX = opts.viewX;
var viewY = opts.viewY;
var pathSlice = opts.pathSlice;
var toMoveInsideSlice = opts.toMoveInsideSlice;
var strTransform = opts.strTransform;
var hasTransition = opts.hasTransition;
var handleSlicesExit = opts.handleSlicesExit;
var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator;
var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator;
var refRect = {};
var isStatic = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
var cd0 = cd[0];
var trace = cd0.trace;
var hierarchy = cd0.hierarchy;
var eachWidth = width / trace._entryDepth;
var pathIds = helpers.listPath(entry.data, 'id');
var sliceData = partition(hierarchy.copy(), [width, height], {
packing: 'dice',
pad: {
inner: 0,
top: 0,
left: 0,
right: 0,
bottom: 0
}
}).descendants();
// edit slices that show up on graph
sliceData = sliceData.filter(function (pt) {
var level = pathIds.indexOf(pt.data.id);
if (level === -1) return false;
pt.x0 = eachWidth * level;
pt.x1 = eachWidth * (level + 1);
pt.y0 = barDifY;
pt.y1 = barDifY + height;
pt.onPathbar = true;
return true;
});
sliceData.reverse();
slices = slices.data(sliceData, helpers.getPtId);
slices.enter().append('g').classed('pathbar', true);
handleSlicesExit(slices, onPathbar, refRect, [width, height], pathSlice);
slices.order();
var updateSlices = slices;
if (hasTransition) {
updateSlices = updateSlices.transition().each('end', function () {
// N.B. gd._transitioning is (still) *true* by the time
// transition updates get here
var sliceTop = d3.select(this);
helpers.setSliceCursor(sliceTop, gd, {
hideOnRoot: false,
hideOnLeaves: false,
isTransitioning: false
});
});
}
updateSlices.each(function (pt) {
// for bbox
pt._x0 = viewX(pt.x0);
pt._x1 = viewX(pt.x1);
pt._y0 = viewY(pt.y0);
pt._y1 = viewY(pt.y1);
pt._hoverX = viewX(pt.x1 - Math.min(width, height) / 2);
pt._hoverY = viewY(pt.y1 - height / 2);
var sliceTop = d3.select(this);
var slicePath = Lib.ensureSingle(sliceTop, 'path', 'surface', function (s) {
s.style('pointer-events', isStatic ? 'none' : 'all');
});
if (hasTransition) {
slicePath.transition().attrTween('d', function (pt2) {
var interp = makeUpdateSliceInterpolator(pt2, onPathbar, refRect, [width, height]);
return function (t) {
return pathSlice(interp(t));
};
});
} else {
slicePath.attr('d', pathSlice);
}
sliceTop.call(attachFxHandlers, entry, gd, cd, {
styleOne: styleOne,
eventDataKeys: constants.eventDataKeys,
transitionTime: constants.CLICK_TRANSITION_TIME,
transitionEasing: constants.CLICK_TRANSITION_EASING
}).call(helpers.setSliceCursor, gd, {
hideOnRoot: false,
hideOnLeaves: false,
isTransitioning: gd._transitioning
});
slicePath.call(styleOne, pt, trace, gd, {
hovered: false
});
pt._text = (helpers.getPtLabel(pt) || '').split(' ').join(' ') || '';
var sliceTextGroup = Lib.ensureSingle(sliceTop, 'g', 'slicetext');
var sliceText = Lib.ensureSingle(sliceTextGroup, '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, helpers.determineTextFont(trace, pt, fullLayout.font, {
onPathbar: true
}));
sliceText.text(pt._text || ' ') // use one space character instead of a blank string to avoid jumps during transition
.classed('slicetext', true).attr('text-anchor', 'start').call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
pt.textBB = Drawing.bBox(sliceText.node());
pt.transform = toMoveInsideSlice(pt, {
fontSize: font.size,
onPathbar: true
});
pt.transform.fontSize = font.size;
if (hasTransition) {
sliceText.transition().attrTween('transform', function (pt2) {
var interp = makeUpdateTextInterpolator(pt2, onPathbar, refRect, [width, height]);
return function (t) {
return strTransform(interp(t));
};
});
} else {
sliceText.attr('transform', strTransform(pt));
}
});
};
/***/ }),
/***/ 76477:
/***/ (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 svgTextUtils = __webpack_require__(72736);
var partition = __webpack_require__(13832);
var styleOne = (__webpack_require__(66192).styleOne);
var constants = __webpack_require__(32984);
var helpers = __webpack_require__(78176);
var attachFxHandlers = __webpack_require__(45716);
var formatSliceLabel = (__webpack_require__(96488).formatSliceLabel);
var onPathbar = false; // for Descendants
module.exports = function drawDescendants(gd, cd, entry, slices, opts) {
var width = opts.width;
var height = opts.height;
var viewX = opts.viewX;
var viewY = opts.viewY;
var pathSlice = opts.pathSlice;
var toMoveInsideSlice = opts.toMoveInsideSlice;
var strTransform = opts.strTransform;
var hasTransition = opts.hasTransition;
var handleSlicesExit = opts.handleSlicesExit;
var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator;
var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator;
var prevEntry = opts.prevEntry;
var refRect = {};
var isStatic = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
var cd0 = cd[0];
var trace = cd0.trace;
var hasLeft = trace.textposition.indexOf('left') !== -1;
var hasRight = trace.textposition.indexOf('right') !== -1;
var hasBottom = trace.textposition.indexOf('bottom') !== -1;
var noRoomForHeader = !hasBottom && !trace.marker.pad.t || hasBottom && !trace.marker.pad.b;
// N.B. slice data isn't the calcdata,
// grab corresponding calcdata item in sliceData[i].data.data
var allData = partition(entry, [width, height], {
packing: trace.tiling.packing,
squarifyratio: trace.tiling.squarifyratio,
flipX: trace.tiling.flip.indexOf('x') > -1,
flipY: trace.tiling.flip.indexOf('y') > -1,
pad: {
inner: trace.tiling.pad,
top: trace.marker.pad.t,
left: trace.marker.pad.l,
right: trace.marker.pad.r,
bottom: trace.marker.pad.b
}
});
var sliceData = allData.descendants();
var minVisibleDepth = Infinity;
var maxVisibleDepth = -Infinity;
sliceData.forEach(function (pt) {
var depth = pt.depth;
if (depth >= trace._maxDepth) {
// hide slices that won't show up on graph
pt.x0 = pt.x1 = (pt.x0 + pt.x1) / 2;
pt.y0 = pt.y1 = (pt.y0 + pt.y1) / 2;
} else {
minVisibleDepth = Math.min(minVisibleDepth, depth);
maxVisibleDepth = Math.max(maxVisibleDepth, depth);
}
});
slices = slices.data(sliceData, helpers.getPtId);
trace._maxVisibleLayers = isFinite(maxVisibleDepth) ? maxVisibleDepth - minVisibleDepth + 1 : 0;
slices.enter().append('g').classed('slice', true);
handleSlicesExit(slices, onPathbar, refRect, [width, height], pathSlice);
slices.order();
// next coords of previous entry
var nextOfPrevEntry = null;
if (hasTransition && prevEntry) {
var prevEntryId = helpers.getPtId(prevEntry);
slices.each(function (pt) {
if (nextOfPrevEntry === null && helpers.getPtId(pt) === prevEntryId) {
nextOfPrevEntry = {
x0: pt.x0,
x1: pt.x1,
y0: pt.y0,
y1: pt.y1
};
}
});
}
var getRefRect = function () {
return nextOfPrevEntry || {
x0: 0,
x1: width,
y0: 0,
y1: height
};
};
var updateSlices = slices;
if (hasTransition) {
updateSlices = updateSlices.transition().each('end', function () {
// N.B. gd._transitioning is (still) *true* by the time
// transition updates get here
var sliceTop = d3.select(this);
helpers.setSliceCursor(sliceTop, gd, {
hideOnRoot: true,
hideOnLeaves: false,
isTransitioning: false
});
});
}
updateSlices.each(function (pt) {
var isHeader = helpers.isHeader(pt, trace);
// for bbox
pt._x0 = viewX(pt.x0);
pt._x1 = viewX(pt.x1);
pt._y0 = viewY(pt.y0);
pt._y1 = viewY(pt.y1);
pt._hoverX = viewX(pt.x1 - trace.marker.pad.r), pt._hoverY = hasBottom ? viewY(pt.y1 - trace.marker.pad.b / 2) : viewY(pt.y0 + trace.marker.pad.t / 2);
var sliceTop = d3.select(this);
var slicePath = Lib.ensureSingle(sliceTop, 'path', 'surface', function (s) {
s.style('pointer-events', isStatic ? 'none' : 'all');
});
if (hasTransition) {
slicePath.transition().attrTween('d', function (pt2) {
var interp = makeUpdateSliceInterpolator(pt2, onPathbar, getRefRect(), [width, height]);
return function (t) {
return pathSlice(interp(t));
};
});
} else {
slicePath.attr('d', pathSlice);
}
sliceTop.call(attachFxHandlers, entry, gd, cd, {
styleOne: styleOne,
eventDataKeys: constants.eventDataKeys,
transitionTime: constants.CLICK_TRANSITION_TIME,
transitionEasing: constants.CLICK_TRANSITION_EASING
}).call(helpers.setSliceCursor, gd, {
isTransitioning: gd._transitioning
});
slicePath.call(styleOne, pt, trace, gd, {
hovered: false
});
if (pt.x0 === pt.x1 || pt.y0 === pt.y1) {
pt._text = '';
} else {
if (isHeader) {
pt._text = noRoomForHeader ? '' : helpers.getPtLabel(pt) || '';
} else {
pt._text = formatSliceLabel(pt, entry, trace, cd, fullLayout) || '';
}
}
var sliceTextGroup = Lib.ensureSingle(sliceTop, 'g', 'slicetext');
var sliceText = Lib.ensureSingle(sliceTextGroup, '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, helpers.determineTextFont(trace, pt, fullLayout.font));
var text = pt._text || ' '; // use one space character instead of a blank string to avoid jumps during transition
var singleLineHeader = isHeader && text.indexOf(' ') === -1;
sliceText.text(text).classed('slicetext', true).attr('text-anchor', hasRight ? 'end' : hasLeft || singleLineHeader ? 'start' : 'middle').call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
pt.textBB = Drawing.bBox(sliceText.node());
pt.transform = toMoveInsideSlice(pt, {
fontSize: font.size,
isHeader: isHeader
});
pt.transform.fontSize = font.size;
if (hasTransition) {
sliceText.transition().attrTween('transform', function (pt2) {
var interp = makeUpdateTextInterpolator(pt2, onPathbar, getRefRect(), [width, height]);
return function (t) {
return strTransform(interp(t));
};
});
} else {
sliceText.attr('transform', strTransform(pt));
}
});
return nextOfPrevEntry;
};
/***/ }),
/***/ 83024:
/***/ (function(module) {
"use strict";
module.exports = function flipTree(node, size, opts) {
var tmp;
if (opts.swapXY) {
// swap x0 and y0
tmp = node.x0;
node.x0 = node.y0;
node.y0 = tmp;
// swap x1 and y1
tmp = node.x1;
node.x1 = node.y1;
node.y1 = tmp;
}
if (opts.flipX) {
tmp = node.x0;
node.x0 = size[0] - node.x1;
node.x1 = size[0] - tmp;
}
if (opts.flipY) {
tmp = node.y0;
node.y0 = size[1] - node.y1;
node.y1 = size[1] - tmp;
}
var children = node.children;
if (children) {
for (var i = 0; i < children.length; i++) {
flipTree(children[i], size, opts);
}
}
};
/***/ }),
/***/ 31991:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
moduleType: 'trace',
name: 'treemap',
basePlotModule: __webpack_require__(79516),
categories: [],
animatable: true,
attributes: __webpack_require__(40516),
layoutAttributes: __webpack_require__(45392),
supplyDefaults: __webpack_require__(34092),
supplyLayoutDefaults: __webpack_require__(77480),
calc: (__webpack_require__(97840)/* .calc */ .r),
crossTraceCalc: (__webpack_require__(97840)/* .crossTraceCalc */ .q),
plot: __webpack_require__(53264),
style: (__webpack_require__(66192).style),
colorbar: __webpack_require__(5528),
meta: {}
};
/***/ }),
/***/ 45392:
/***/ (function(module) {
"use strict";
module.exports = {
treemapcolorway: {
valType: 'colorlist',
editType: 'calc'
},
extendtreemapcolors: {
valType: 'boolean',
dflt: true,
editType: 'calc'
}
};
/***/ }),
/***/ 77480:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(45392);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
coerce('treemapcolorway', layoutOut.colorway);
coerce('extendtreemapcolors');
};
/***/ }),
/***/ 13832:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3Hierarchy = __webpack_require__(74148);
var flipTree = __webpack_require__(83024);
module.exports = function partition(entry, size, opts) {
var flipX = opts.flipX;
var flipY = opts.flipY;
var swapXY = opts.packing === 'dice-slice';
var top = opts.pad[flipY ? 'bottom' : 'top'];
var left = opts.pad[flipX ? 'right' : 'left'];
var right = opts.pad[flipX ? 'left' : 'right'];
var bottom = opts.pad[flipY ? 'top' : 'bottom'];
var tmp;
if (swapXY) {
tmp = left;
left = top;
top = tmp;
tmp = right;
right = bottom;
bottom = tmp;
}
var result = d3Hierarchy.treemap().tile(getTilingMethod(opts.packing, opts.squarifyratio)).paddingInner(opts.pad.inner).paddingLeft(left).paddingRight(right).paddingTop(top).paddingBottom(bottom).size(swapXY ? [size[1], size[0]] : size)(entry);
if (swapXY || flipX || flipY) {
flipTree(result, size, {
swapXY: swapXY,
flipX: flipX,
flipY: flipY
});
}
return result;
};
function getTilingMethod(key, squarifyratio) {
switch (key) {
case 'squarify':
return d3Hierarchy.treemapSquarify.ratio(squarifyratio);
case 'binary':
return d3Hierarchy.treemapBinary;
case 'dice':
return d3Hierarchy.treemapDice;
case 'slice':
return d3Hierarchy.treemapSlice;
default:
// i.e. 'slice-dice' | 'dice-slice'
return d3Hierarchy.treemapSliceDice;
}
}
/***/ }),
/***/ 53264:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var draw = __webpack_require__(95808);
var drawDescendants = __webpack_require__(76477);
module.exports = function _plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback) {
return draw(gd, cdmodule, transitionOpts, makeOnCompleteCallback, {
type: 'treemap',
drawDescendants: drawDescendants
});
};
/***/ }),
/***/ 52960:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var interpolate = (__webpack_require__(67756)/* .interpolate */ .qy);
var helpers = __webpack_require__(78176);
var Lib = __webpack_require__(3400);
var TEXTPAD = (__webpack_require__(78048).TEXTPAD);
var barPlot = __webpack_require__(98184);
var toMoveInsideBar = barPlot.toMoveInsideBar;
var uniformText = __webpack_require__(82744);
var recordMinTextSize = uniformText.recordMinTextSize;
var constants = __webpack_require__(32984);
var drawAncestors = __webpack_require__(27336);
function getKey(pt) {
return helpers.isHierarchyRoot(pt) ? '' :
// don't use the dummyId
helpers.getPtId(pt);
}
module.exports = function plotOne(gd, cd, element, transitionOpts, drawDescendants) {
var fullLayout = gd._fullLayout;
var cd0 = cd[0];
var trace = cd0.trace;
var type = trace.type;
var isIcicle = type === 'icicle';
var hierarchy = cd0.hierarchy;
var entry = helpers.findEntryWithLevel(hierarchy, trace.level);
var gTrace = d3.select(element);
var selAncestors = gTrace.selectAll('g.pathbar');
var selDescendants = gTrace.selectAll('g.slice');
if (!entry) {
selAncestors.remove();
selDescendants.remove();
return;
}
var isRoot = helpers.isHierarchyRoot(entry);
var hasTransition = !fullLayout.uniformtext.mode && helpers.hasTransition(transitionOpts);
var maxDepth = helpers.getMaxDepth(trace);
var hasVisibleDepth = function (pt) {
return pt.data.depth - entry.data.depth < maxDepth;
};
var gs = fullLayout._size;
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 barW = vpw;
var barH = trace.pathbar.thickness;
var barPad = trace.marker.line.width + constants.gapWithPathbar;
var barDifY = !trace.pathbar.visible ? 0 : trace.pathbar.side.indexOf('bottom') > -1 ? vph + barPad : -(barH + barPad);
var pathbarOrigin = {
x0: barW,
// slide to the right
x1: barW,
y0: barDifY,
y1: barDifY + barH
};
var findClosestEdge = function (pt, ref, size) {
var e = trace.tiling.pad;
var isLeftOfRect = function (x) {
return x - e <= ref.x0;
};
var isRightOfRect = function (x) {
return x + e >= ref.x1;
};
var isBottomOfRect = function (y) {
return y - e <= ref.y0;
};
var isTopOfRect = function (y) {
return y + e >= ref.y1;
};
if (pt.x0 === ref.x0 && pt.x1 === ref.x1 && pt.y0 === ref.y0 && pt.y1 === ref.y1) {
return {
x0: pt.x0,
x1: pt.x1,
y0: pt.y0,
y1: pt.y1
};
}
return {
x0: isLeftOfRect(pt.x0 - e) ? 0 : isRightOfRect(pt.x0 - e) ? size[0] : pt.x0,
x1: isLeftOfRect(pt.x1 + e) ? 0 : isRightOfRect(pt.x1 + e) ? size[0] : pt.x1,
y0: isBottomOfRect(pt.y0 - e) ? 0 : isTopOfRect(pt.y0 - e) ? size[1] : pt.y0,
y1: isBottomOfRect(pt.y1 + e) ? 0 : isTopOfRect(pt.y1 + e) ? size[1] : pt.y1
};
};
// stash of 'previous' position data used by tweening functions
var prevEntry = null;
var prevLookupPathbar = {};
var prevLookupSlices = {};
var nextOfPrevEntry = null;
var getPrev = function (pt, onPathbar) {
return onPathbar ? prevLookupPathbar[getKey(pt)] : prevLookupSlices[getKey(pt)];
};
var getOrigin = function (pt, onPathbar, refRect, size) {
if (onPathbar) {
return prevLookupPathbar[getKey(hierarchy)] || pathbarOrigin;
} else {
var ref = prevLookupSlices[trace.level] || refRect;
if (hasVisibleDepth(pt)) {
// case of an empty object - happens when maxdepth is set
return findClosestEdge(pt, ref, size);
}
}
return {};
};
// N.B. handle multiple-root special case
if (cd0.hasMultipleRoots && isRoot) {
maxDepth++;
}
trace._maxDepth = maxDepth;
trace._backgroundColor = fullLayout.paper_bgcolor;
trace._entryDepth = entry.data.depth;
trace._atRootLevel = isRoot;
var cenX = -vpw / 2 + gs.l + gs.w * (domain.x[1] + domain.x[0]) / 2;
var cenY = -vph / 2 + gs.t + gs.h * (1 - (domain.y[1] + domain.y[0]) / 2);
var viewMapX = function (x) {
return cenX + x;
};
var viewMapY = function (y) {
return cenY + y;
};
var barY0 = viewMapY(0);
var barX0 = viewMapX(0);
var viewBarX = function (x) {
return barX0 + x;
};
var viewBarY = function (y) {
return barY0 + y;
};
function pos(x, y) {
return x + ',' + y;
}
var xStart = viewBarX(0);
var limitX0 = function (p) {
p.x = Math.max(xStart, p.x);
};
var edgeshape = trace.pathbar.edgeshape;
// pathbar(directory) path generation fn
var pathAncestor = function (d) {
var _x0 = viewBarX(Math.max(Math.min(d.x0, d.x0), 0));
var _x1 = viewBarX(Math.min(Math.max(d.x1, d.x1), barW));
var _y0 = viewBarY(d.y0);
var _y1 = viewBarY(d.y1);
var halfH = barH / 2;
var pL = {};
var pR = {};
pL.x = _x0;
pR.x = _x1;
pL.y = pR.y = (_y0 + _y1) / 2;
var pA = {
x: _x0,
y: _y0
};
var pB = {
x: _x1,
y: _y0
};
var pC = {
x: _x1,
y: _y1
};
var pD = {
x: _x0,
y: _y1
};
if (edgeshape === '>') {
pA.x -= halfH;
pB.x -= halfH;
pC.x -= halfH;
pD.x -= halfH;
} else if (edgeshape === '/') {
pC.x -= halfH;
pD.x -= halfH;
pL.x -= halfH / 2;
pR.x -= halfH / 2;
} else if (edgeshape === '\\') {
pA.x -= halfH;
pB.x -= halfH;
pL.x -= halfH / 2;
pR.x -= halfH / 2;
} else if (edgeshape === '<') {
pL.x -= halfH;
pR.x -= halfH;
}
limitX0(pA);
limitX0(pD);
limitX0(pL);
limitX0(pB);
limitX0(pC);
limitX0(pR);
return 'M' + pos(pA.x, pA.y) + 'L' + pos(pB.x, pB.y) + 'L' + pos(pR.x, pR.y) + 'L' + pos(pC.x, pC.y) + 'L' + pos(pD.x, pD.y) + 'L' + pos(pL.x, pL.y) + 'Z';
};
// Note that `pad` is just an integer for `icicle`` traces where
// `pad` is a hashmap for treemap: pad.t, pad.b, pad.l, and pad.r
var pad = trace[isIcicle ? 'tiling' : 'marker'].pad;
var hasFlag = function (f) {
return trace.textposition.indexOf(f) !== -1;
};
var hasTop = hasFlag('top');
var hasLeft = hasFlag('left');
var hasRight = hasFlag('right');
var hasBottom = hasFlag('bottom');
// slice path generation fn
var pathDescendant = function (d) {
var _x0 = viewMapX(d.x0);
var _x1 = viewMapX(d.x1);
var _y0 = viewMapY(d.y0);
var _y1 = viewMapY(d.y1);
var dx = _x1 - _x0;
var dy = _y1 - _y0;
if (!dx || !dy) return '';
var cornerradius = trace.marker.cornerradius || 0;
var r = Math.min(cornerradius, dx / 2, dy / 2);
if (r && d.data && d.data.data && d.data.data.label) {
if (hasTop) r = Math.min(r, pad.t);
if (hasLeft) r = Math.min(r, pad.l);
if (hasRight) r = Math.min(r, pad.r);
if (hasBottom) r = Math.min(r, pad.b);
}
var arc = function (rx, ry) {
return r ? 'a' + pos(r, r) + ' 0 0 1 ' + pos(rx, ry) : '';
};
return 'M' + pos(_x0, _y0 + r) + arc(r, -r) + 'L' + pos(_x1 - r, _y0) + arc(r, r) + 'L' + pos(_x1, _y1 - r) + arc(-r, r) + 'L' + pos(_x0 + r, _y1) + arc(-r, -r) + 'Z';
};
var toMoveInsideSlice = function (pt, opts) {
var x0 = pt.x0;
var x1 = pt.x1;
var y0 = pt.y0;
var y1 = pt.y1;
var textBB = pt.textBB;
var _hasTop = hasTop || opts.isHeader && !hasBottom;
var anchor = _hasTop ? 'start' : hasBottom ? 'end' : 'middle';
var _hasRight = hasFlag('right');
var _hasLeft = hasFlag('left') || opts.onPathbar;
var leftToRight = _hasLeft ? -1 : _hasRight ? 1 : 0;
if (opts.isHeader) {
x0 += (isIcicle ? pad : pad.l) - TEXTPAD;
x1 -= (isIcicle ? pad : pad.r) - TEXTPAD;
if (x0 >= x1) {
var mid = (x0 + x1) / 2;
x0 = mid;
x1 = mid;
}
// limit the drawing area for headers
var limY;
if (hasBottom) {
limY = y1 - (isIcicle ? pad : pad.b);
if (y0 < limY && limY < y1) y0 = limY;
} else {
limY = y0 + (isIcicle ? pad : pad.t);
if (y0 < limY && limY < y1) y1 = limY;
}
}
// position the text relative to the slice
var transform = toMoveInsideBar(x0, x1, y0, y1, textBB, {
isHorizontal: false,
constrained: true,
angle: 0,
anchor: anchor,
leftToRight: leftToRight
});
transform.fontSize = opts.fontSize;
transform.targetX = viewMapX(transform.targetX);
transform.targetY = viewMapY(transform.targetY);
if (isNaN(transform.targetX) || isNaN(transform.targetY)) {
return {};
}
if (x0 !== x1 && y0 !== y1) {
recordMinTextSize(trace.type, transform, fullLayout);
}
return {
scale: transform.scale,
rotate: transform.rotate,
textX: transform.textX,
textY: transform.textY,
anchorX: transform.anchorX,
anchorY: transform.anchorY,
targetX: transform.targetX,
targetY: transform.targetY
};
};
var interpFromParent = function (pt, onPathbar) {
var parentPrev;
var i = 0;
var Q = pt;
while (!parentPrev && i < maxDepth) {
// loop to find a parent/grandParent on the previous graph
i++;
Q = Q.parent;
if (Q) {
parentPrev = getPrev(Q, onPathbar);
} else i = maxDepth;
}
return parentPrev || {};
};
var makeExitSliceInterpolator = function (pt, onPathbar, refRect, size) {
var prev = getPrev(pt, onPathbar);
var next;
if (onPathbar) {
next = pathbarOrigin;
} else {
var entryPrev = getPrev(entry, onPathbar);
if (entryPrev) {
// 'entryPrev' is here has the previous coordinates of the entry
// node, which corresponds to the last "clicked" node when zooming in
next = findClosestEdge(pt, entryPrev, size);
} else {
// this happens when maxdepth is set, when leaves must
// be removed and the entry is new (i.e. does not have a 'prev' object)
next = {};
}
}
return interpolate(prev, next);
};
var makeUpdateSliceInterpolator = function (pt, onPathbar, refRect, size, opts) {
var prev0 = getPrev(pt, onPathbar);
var prev;
if (prev0) {
// if pt already on graph, this is easy
prev = prev0;
} else {
// for new pts:
if (onPathbar) {
prev = pathbarOrigin;
} else {
if (prevEntry) {
// if trace was visible before
if (pt.parent) {
var ref = nextOfPrevEntry || refRect;
if (ref && !onPathbar) {
prev = findClosestEdge(pt, ref, size);
} else {
// if new leaf (when maxdepth is set),
// grow it from its parent node
prev = {};
Lib.extendFlat(prev, interpFromParent(pt, onPathbar));
}
} else {
prev = Lib.extendFlat({}, pt);
if (isIcicle) {
if (opts.orientation === 'h') {
if (opts.flipX) prev.x0 = pt.x1;else prev.x1 = 0;
} else {
if (opts.flipY) prev.y0 = pt.y1;else prev.y1 = 0;
}
}
}
} else {
prev = {};
}
}
}
return interpolate(prev, {
x0: pt.x0,
x1: pt.x1,
y0: pt.y0,
y1: pt.y1
});
};
var makeUpdateTextInterpolator = function (pt, onPathbar, refRect, size) {
var prev0 = getPrev(pt, onPathbar);
var prev = {};
var origin = getOrigin(pt, onPathbar, refRect, size);
Lib.extendFlat(prev, {
transform: toMoveInsideSlice({
x0: origin.x0,
x1: origin.x1,
y0: origin.y0,
y1: origin.y1,
textBB: pt.textBB,
_text: pt._text
}, {
isHeader: helpers.isHeader(pt, trace)
})
});
if (prev0) {
// if pt already on graph, this is easy
prev = prev0;
} else {
// for new pts:
if (pt.parent) {
Lib.extendFlat(prev, interpFromParent(pt, onPathbar));
}
}
var transform = pt.transform;
if (pt.x0 !== pt.x1 && pt.y0 !== pt.y1) {
recordMinTextSize(trace.type, transform, fullLayout);
}
return interpolate(prev, {
transform: {
scale: transform.scale,
rotate: transform.rotate,
textX: transform.textX,
textY: transform.textY,
anchorX: transform.anchorX,
anchorY: transform.anchorY,
targetX: transform.targetX,
targetY: transform.targetY
}
});
};
var handleSlicesExit = function (slices, onPathbar, refRect, size, pathSlice) {
var width = size[0];
var height = size[1];
if (hasTransition) {
slices.exit().transition().each(function () {
var sliceTop = d3.select(this);
var slicePath = sliceTop.select('path.surface');
slicePath.transition().attrTween('d', function (pt2) {
var interp = makeExitSliceInterpolator(pt2, onPathbar, refRect, [width, height]);
return function (t) {
return pathSlice(interp(t));
};
});
var sliceTextGroup = sliceTop.select('g.slicetext');
sliceTextGroup.attr('opacity', 0);
}).remove();
} else {
slices.exit().remove();
}
};
var strTransform = function (d) {
var transform = d.transform;
if (d.x0 !== d.x1 && d.y0 !== d.y1) {
recordMinTextSize(trace.type, transform, fullLayout);
}
return Lib.getTextTransform({
textX: transform.textX,
textY: transform.textY,
anchorX: transform.anchorX,
anchorY: transform.anchorY,
targetX: transform.targetX,
targetY: transform.targetY,
scale: transform.scale,
rotate: transform.rotate
});
};
if (hasTransition) {
// Important: do this before binding new sliceData!
selAncestors.each(function (pt) {
prevLookupPathbar[getKey(pt)] = {
x0: pt.x0,
x1: pt.x1,
y0: pt.y0,
y1: pt.y1
};
if (pt.transform) {
prevLookupPathbar[getKey(pt)].transform = {
textX: pt.transform.textX,
textY: pt.transform.textY,
anchorX: pt.transform.anchorX,
anchorY: pt.transform.anchorY,
targetX: pt.transform.targetX,
targetY: pt.transform.targetY,
scale: pt.transform.scale,
rotate: pt.transform.rotate
};
}
});
selDescendants.each(function (pt) {
prevLookupSlices[getKey(pt)] = {
x0: pt.x0,
x1: pt.x1,
y0: pt.y0,
y1: pt.y1
};
if (pt.transform) {
prevLookupSlices[getKey(pt)].transform = {
textX: pt.transform.textX,
textY: pt.transform.textY,
anchorX: pt.transform.anchorX,
anchorY: pt.transform.anchorY,
targetX: pt.transform.targetX,
targetY: pt.transform.targetY,
scale: pt.transform.scale,
rotate: pt.transform.rotate
};
}
if (!prevEntry && helpers.isEntry(pt)) {
prevEntry = pt;
}
});
}
nextOfPrevEntry = drawDescendants(gd, cd, entry, selDescendants, {
width: vpw,
height: vph,
viewX: viewMapX,
viewY: viewMapY,
pathSlice: pathDescendant,
toMoveInsideSlice: toMoveInsideSlice,
prevEntry: prevEntry,
makeUpdateSliceInterpolator: makeUpdateSliceInterpolator,
makeUpdateTextInterpolator: makeUpdateTextInterpolator,
handleSlicesExit: handleSlicesExit,
hasTransition: hasTransition,
strTransform: strTransform
});
if (trace.pathbar.visible) {
drawAncestors(gd, cd, entry, selAncestors, {
barDifY: barDifY,
width: barW,
height: barH,
viewX: viewBarX,
viewY: viewBarY,
pathSlice: pathAncestor,
toMoveInsideSlice: toMoveInsideSlice,
makeUpdateSliceInterpolator: makeUpdateSliceInterpolator,
makeUpdateTextInterpolator: makeUpdateTextInterpolator,
handleSlicesExit: handleSlicesExit,
hasTransition: hasTransition,
strTransform: strTransform
});
} else {
selAncestors.remove();
}
};
/***/ }),
/***/ 66192:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
var Lib = __webpack_require__(3400);
var helpers = __webpack_require__(78176);
var resizeText = (__webpack_require__(82744).resizeText);
var fillOne = __webpack_require__(60404);
function style(gd) {
var s = gd._fullLayout._treemaplayer.selectAll('.trace');
resizeText(gd, s, 'treemap');
s.each(function (cd) {
var gTrace = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
gTrace.style('opacity', trace.opacity);
gTrace.selectAll('path.surface').each(function (pt) {
d3.select(this).call(styleOne, pt, trace, gd, {
hovered: false
});
});
});
}
function styleOne(s, pt, trace, gd, opts) {
var hovered = (opts || {}).hovered;
var cdi = pt.data.data;
var ptNumber = cdi.i;
var lineColor;
var lineWidth;
var fillColor = cdi.color;
var isRoot = helpers.isHierarchyRoot(pt);
var opacity = 1;
if (hovered) {
lineColor = trace._hovered.marker.line.color;
lineWidth = trace._hovered.marker.line.width;
} else {
if (isRoot && fillColor === trace.root.color) {
opacity = 100;
lineColor = 'rgba(0,0,0,0)';
lineWidth = 0;
} else {
lineColor = Lib.castOption(trace, ptNumber, 'marker.line.color') || Color.defaultLine;
lineWidth = Lib.castOption(trace, ptNumber, 'marker.line.width') || 0;
if (!trace._hasColorscale && !pt.onPathbar) {
var depthfade = trace.marker.depthfade;
if (depthfade) {
var fadedColor = Color.combine(Color.addOpacity(trace._backgroundColor, 0.75), fillColor);
var n;
if (depthfade === true) {
var maxDepth = helpers.getMaxDepth(trace);
if (isFinite(maxDepth)) {
if (helpers.isLeaf(pt)) {
n = 0;
} else {
n = trace._maxVisibleLayers - (pt.data.depth - trace._entryDepth);
}
} else {
n = pt.data.height + 1;
}
} else {
// i.e. case of depthfade === 'reversed'
n = pt.data.depth - trace._entryDepth;
if (!trace._atRootLevel) n++;
}
if (n > 0) {
for (var i = 0; i < n; i++) {
var ratio = 0.5 * i / n;
fillColor = Color.combine(Color.addOpacity(fadedColor, ratio), fillColor);
}
}
}
}
}
}
s.call(fillOne, pt, trace, gd, fillColor).style('stroke-width', lineWidth).call(Color.stroke, lineColor).style('opacity', opacity);
}
module.exports = {
style: style,
styleOne: styleOne
};
/***/ }),
/***/ 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);
});
};
/***/ }),
/***/ 58168:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorScaleAttrs = __webpack_require__(49084);
var isosurfaceAttrs = __webpack_require__(50048);
var surfaceAttrs = __webpack_require__(16716);
var baseAttrs = __webpack_require__(45464);
var extendFlat = (__webpack_require__(92880).extendFlat);
var overrideAll = (__webpack_require__(67824).overrideAll);
var attrs = module.exports = overrideAll(extendFlat({
x: isosurfaceAttrs.x,
y: isosurfaceAttrs.y,
z: isosurfaceAttrs.z,
value: isosurfaceAttrs.value,
isomin: isosurfaceAttrs.isomin,
isomax: isosurfaceAttrs.isomax,
surface: isosurfaceAttrs.surface,
spaceframe: {
show: {
valType: 'boolean',
dflt: false
},
fill: {
valType: 'number',
min: 0,
max: 1,
dflt: 1
}
},
slices: isosurfaceAttrs.slices,
caps: isosurfaceAttrs.caps,
text: isosurfaceAttrs.text,
hovertext: isosurfaceAttrs.hovertext,
xhoverformat: isosurfaceAttrs.xhoverformat,
yhoverformat: isosurfaceAttrs.yhoverformat,
zhoverformat: isosurfaceAttrs.zhoverformat,
valuehoverformat: isosurfaceAttrs.valuehoverformat,
hovertemplate: isosurfaceAttrs.hovertemplate
}, colorScaleAttrs('', {
colorAttr: '`value`',
showScaleDflt: true,
editTypeOverride: 'calc'
}), {
colorbar: isosurfaceAttrs.colorbar,
opacity: isosurfaceAttrs.opacity,
opacityscale: surfaceAttrs.opacityscale,
lightposition: isosurfaceAttrs.lightposition,
lighting: isosurfaceAttrs.lighting,
flatshading: isosurfaceAttrs.flatshading,
contour: isosurfaceAttrs.contour,
hoverinfo: extendFlat({}, baseAttrs.hoverinfo),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
}), 'calc', 'nested');
attrs.x.editType = attrs.y.editType = attrs.z.editType = attrs.value.editType = 'calc+clearAxisTypes';
attrs.transforms = undefined;
/***/ }),
/***/ 91976:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var createMesh = (__webpack_require__(67792).gl_mesh3d);
var parseColorScale = (__webpack_require__(33040).parseColorScale);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var str2RgbaArray = __webpack_require__(43080);
var extractOpts = (__webpack_require__(8932).extractOpts);
var zip3 = __webpack_require__(52094);
var findNearestOnAxis = (__webpack_require__(31460).findNearestOnAxis);
var generateIsoMeshes = (__webpack_require__(31460).generateIsoMeshes);
function VolumeTrace(scene, mesh, uid) {
this.scene = scene;
this.uid = uid;
this.mesh = mesh;
this.name = '';
this.data = null;
this.showContour = false;
}
var proto = VolumeTrace.prototype;
proto.handlePick = function (selection) {
if (selection.object === this.mesh) {
var rawId = selection.data.index;
var x = this.data._meshX[rawId];
var y = this.data._meshY[rawId];
var z = this.data._meshZ[rawId];
var height = this.data._Ys.length;
var depth = this.data._Zs.length;
var i = findNearestOnAxis(x, this.data._Xs).id;
var j = findNearestOnAxis(y, this.data._Ys).id;
var k = findNearestOnAxis(z, this.data._Zs).id;
var selectIndex = selection.index = k + depth * j + depth * height * i;
selection.traceCoordinate = [this.data._meshX[selectIndex], this.data._meshY[selectIndex], this.data._meshZ[selectIndex], this.data._value[selectIndex]];
var text = this.data.hovertext || this.data.text;
if (isArrayOrTypedArray(text) && text[selectIndex] !== undefined) {
selection.textLabel = text[selectIndex];
} else if (text) {
selection.textLabel = text;
}
return true;
}
};
proto.update = function (data) {
var scene = this.scene;
var layout = scene.fullSceneLayout;
this.data = generateIsoMeshes(data);
// Unpack position data
function toDataCoords(axis, coord, scale, calendar) {
return coord.map(function (x) {
return axis.d2l(x, 0, calendar) * scale;
});
}
var positions = zip3(toDataCoords(layout.xaxis, data._meshX, scene.dataScale[0], data.xcalendar), toDataCoords(layout.yaxis, data._meshY, scene.dataScale[1], data.ycalendar), toDataCoords(layout.zaxis, data._meshZ, scene.dataScale[2], data.zcalendar));
var cells = zip3(data._meshI, data._meshJ, data._meshK);
var config = {
positions: positions,
cells: cells,
lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
ambient: data.lighting.ambient,
diffuse: data.lighting.diffuse,
specular: data.lighting.specular,
roughness: data.lighting.roughness,
fresnel: data.lighting.fresnel,
vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
faceNormalsEpsilon: data.lighting.facenormalsepsilon,
opacity: data.opacity,
opacityscale: data.opacityscale,
contourEnable: data.contour.show,
contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
contourWidth: data.contour.width,
useFacetNormals: data.flatshading
};
var cOpts = extractOpts(data);
config.vertexIntensity = data._meshIntensity;
config.vertexIntensityBounds = [cOpts.min, cOpts.max];
config.colormap = parseColorScale(data);
// Update mesh
this.mesh.update(config);
};
proto.dispose = function () {
this.scene.glplot.remove(this.mesh);
this.mesh.dispose();
};
function createVolumeTrace(scene, data) {
var gl = scene.glplot.gl;
var mesh = createMesh({
gl: gl
});
var result = new VolumeTrace(scene, mesh, data.uid);
mesh._trace = result;
result.update(data);
scene.glplot.add(mesh);
return result;
}
module.exports = createVolumeTrace;
/***/ }),
/***/ 12448:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(58168);
var supplyIsoDefaults = (__webpack_require__(70548).supplyIsoDefaults);
var opacityscaleDefaults = (__webpack_require__(60192).opacityscaleDefaults);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
supplyIsoDefaults(traceIn, traceOut, defaultColor, layout, coerce);
opacityscaleDefaults(traceIn, traceOut, layout, coerce);
};
/***/ }),
/***/ 67776:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(58168),
supplyDefaults: __webpack_require__(12448),
calc: __webpack_require__(62624),
colorbar: {
min: 'cmin',
max: 'cmax'
},
plot: __webpack_require__(91976),
moduleType: 'trace',
name: 'volume',
basePlotModule: __webpack_require__(12536),
categories: ['gl3d', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 65776:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var barAttrs = __webpack_require__(20832);
var lineAttrs = (__webpack_require__(52904).line);
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 constants = __webpack_require__(10213);
var extendFlat = (__webpack_require__(92880).extendFlat);
var Color = __webpack_require__(76308);
function directionAttrs(dirTxt) {
return {
marker: {
color: extendFlat({}, barAttrs.marker.color, {
arrayOk: false,
editType: 'style'
}),
line: {
color: extendFlat({}, barAttrs.marker.line.color, {
arrayOk: false,
editType: 'style'
}),
width: extendFlat({}, barAttrs.marker.line.width, {
arrayOk: false,
editType: 'style'
}),
editType: 'style'
},
editType: 'style'
},
editType: 'style'
};
}
module.exports = {
measure: {
valType: 'data_array',
dflt: [],
editType: 'calc'
},
base: {
valType: 'number',
dflt: null,
arrayOk: false,
editType: 'calc'
},
x: barAttrs.x,
x0: barAttrs.x0,
dx: barAttrs.dx,
y: barAttrs.y,
y0: barAttrs.y0,
dy: barAttrs.dy,
xperiod: barAttrs.xperiod,
yperiod: barAttrs.yperiod,
xperiod0: barAttrs.xperiod0,
yperiod0: barAttrs.yperiod0,
xperiodalignment: barAttrs.xperiodalignment,
yperiodalignment: barAttrs.yperiodalignment,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
hovertext: barAttrs.hovertext,
hovertemplate: hovertemplateAttrs({}, {
keys: constants.eventDataKeys
}),
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['name', 'x', 'y', 'text', 'initial', 'delta', 'final']
}),
textinfo: {
valType: 'flaglist',
flags: ['label', 'text', 'initial', 'delta', 'final'],
extras: ['none'],
editType: 'plot',
arrayOk: false
},
// TODO: incorporate `label` and `value` in the eventData
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: constants.eventDataKeys.concat(['label'])
}),
text: barAttrs.text,
textposition: barAttrs.textposition,
insidetextanchor: barAttrs.insidetextanchor,
textangle: barAttrs.textangle,
textfont: barAttrs.textfont,
insidetextfont: barAttrs.insidetextfont,
outsidetextfont: barAttrs.outsidetextfont,
constraintext: barAttrs.constraintext,
cliponaxis: barAttrs.cliponaxis,
orientation: barAttrs.orientation,
offset: barAttrs.offset,
width: barAttrs.width,
increasing: directionAttrs('increasing'),
decreasing: directionAttrs('decreasing'),
totals: directionAttrs('intermediate sums and total'),
connector: {
line: {
color: extendFlat({}, lineAttrs.color, {
dflt: Color.defaultLine
}),
width: extendFlat({}, lineAttrs.width, {
editType: 'plot' // i.e. to adjust bars is mode: 'between'. See https://github.com/plotly/plotly.js/issues/3787
}),
dash: lineAttrs.dash,
editType: 'plot'
},
mode: {
valType: 'enumerated',
values: ['spanning', 'between'],
dflt: 'between',
editType: 'plot'
},
visible: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
editType: 'plot'
},
offsetgroup: barAttrs.offsetgroup,
alignmentgroup: barAttrs.alignmentgroup,
zorder: barAttrs.zorder
};
/***/ }),
/***/ 73540:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var alignPeriod = __webpack_require__(1220);
var mergeArray = (__webpack_require__(3400).mergeArray);
var calcSelection = __webpack_require__(4500);
var BADNUM = (__webpack_require__(39032).BADNUM);
function isAbsolute(a) {
return a === 'a' || a === 'absolute';
}
function isTotal(a) {
return a === 't' || a === 'total';
}
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;
if (trace.orientation === 'h') {
size = xa.makeCalcdata(trace, 'x');
origPos = ya.makeCalcdata(trace, 'y');
pObj = alignPeriod(trace, ya, 'y', origPos);
hasPeriod = !!trace.yperiodalignment;
pLetter = 'y';
} else {
size = ya.makeCalcdata(trace, 'y');
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 (as well as for waterfall total size)
var previousSum = 0;
var newSize;
// trace-wide flags
var hasTotals = false;
for (var i = 0; i < serieslen; i++) {
var amount = size[i] || 0;
var connectToNext = false;
if (size[i] !== BADNUM || isTotal(trace.measure[i]) || isAbsolute(trace.measure[i])) {
if (i + 1 < serieslen && (size[i + 1] !== BADNUM || isTotal(trace.measure[i + 1]) || isAbsolute(trace.measure[i + 1]))) {
connectToNext = true;
}
}
var cdi = cd[i] = {
i: i,
p: pos[i],
s: amount,
rawS: amount,
cNext: connectToNext
};
if (isAbsolute(trace.measure[i])) {
previousSum = cdi.s;
cdi.isSum = true;
cdi.dir = 'totals';
cdi.s = previousSum;
} else if (isTotal(trace.measure[i])) {
cdi.isSum = true;
cdi.dir = 'totals';
cdi.s = previousSum;
} else {
// default: relative
cdi.isSum = false;
cdi.dir = cdi.rawS < 0 ? 'decreasing' : 'increasing';
newSize = cdi.s;
cdi.s = previousSum + newSize;
previousSum += newSize;
}
if (cdi.dir === 'totals') {
hasTotals = true;
}
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) {
cdi.id = String(trace.ids[i]);
}
cdi.v = (trace.base || 0) + previousSum;
}
if (cd.length) cd[0].hasTotals = hasTotals;
mergeArray(trace.text, cd, 'tx');
mergeArray(trace.hovertext, cd, 'htx');
calcSelection(cd, trace);
return cd;
};
/***/ }),
/***/ 10213:
/***/ (function(module) {
"use strict";
module.exports = {
eventDataKeys: ['initial', 'delta', 'final']
};
/***/ }),
/***/ 50152:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var setGroupPositions = (__webpack_require__(96376).setGroupPositions);
module.exports = function crossTraceCalc(gd, plotinfo) {
var fullLayout = gd._fullLayout;
var fullData = gd._fullData;
var calcdata = gd.calcdata;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var waterfalls = [];
var waterfallsVert = [];
var waterfallsHorz = [];
var cd, i;
for (i = 0; i < fullData.length; i++) {
var fullTrace = fullData[i];
if (fullTrace.visible === true && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id && fullTrace.type === 'waterfall') {
cd = calcdata[i];
if (fullTrace.orientation === 'h') {
waterfallsHorz.push(cd);
} else {
waterfallsVert.push(cd);
}
waterfalls.push(cd);
}
}
var opts = {
mode: fullLayout.waterfallmode,
norm: fullLayout.waterfallnorm,
gap: fullLayout.waterfallgap,
groupgap: fullLayout.waterfallgroupgap
};
setGroupPositions(gd, xa, ya, waterfallsVert, opts);
setGroupPositions(gd, ya, xa, waterfallsHorz, opts);
for (i = 0; i < waterfalls.length; i++) {
cd = waterfalls[i];
for (var j = 0; j < cd.length; j++) {
var di = cd[j];
if (di.isSum === false) {
di.s0 += j === 0 ? 0 : cd[j - 1].s;
}
if (j + 1 < cd.length) {
cd[j].nextP0 = cd[j + 1].p0;
cd[j].nextS0 = cd[j + 1].s0;
}
}
}
};
/***/ }),
/***/ 24224:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleGroupingDefaults = __webpack_require__(20011);
var handleText = (__webpack_require__(31508).handleText);
var handleXYDefaults = __webpack_require__(43980);
var handlePeriodDefaults = __webpack_require__(31147);
var attributes = __webpack_require__(65776);
var Color = __webpack_require__(76308);
var delta = __webpack_require__(48164);
var INCREASING_COLOR = delta.INCREASING.COLOR;
var DECREASING_COLOR = delta.DECREASING.COLOR;
var TOTALS_COLOR = '#4499FF';
function handleDirection(coerce, direction, defaultColor) {
coerce(direction + '.marker.color', defaultColor);
coerce(direction + '.marker.line.color', Color.defaultLine);
coerce(direction + '.marker.line.width');
}
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('measure');
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: false,
moduleHasUnselected: false,
moduleHasConstrain: true,
moduleHasCliponaxis: true,
moduleHasTextangle: true,
moduleHasInsideanchor: true
});
if (traceOut.textposition !== 'none') {
coerce('texttemplate');
if (!traceOut.texttemplate) coerce('textinfo');
}
handleDirection(coerce, 'increasing', INCREASING_COLOR);
handleDirection(coerce, 'decreasing', DECREASING_COLOR);
handleDirection(coerce, 'totals', TOTALS_COLOR);
var connectorVisible = coerce('connector.visible');
if (connectorVisible) {
coerce('connector.mode');
var connectorLineWidth = coerce('connector.line.width');
if (connectorLineWidth) {
coerce('connector.line.color');
coerce('connector.line.dash');
}
}
coerce('zorder');
}
function crossTraceDefaults(fullData, fullLayout) {
var traceIn, traceOut;
function coerce(attr) {
return Lib.coerce(traceOut._input, traceOut, attributes, attr);
}
if (fullLayout.waterfallmode === 'group') {
for (var i = 0; i < fullData.length; i++) {
traceOut = fullData[i];
traceIn = traceOut._input;
handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce);
}
}
}
module.exports = {
supplyDefaults: supplyDefaults,
crossTraceDefaults: crossTraceDefaults
};
/***/ }),
/***/ 53256:
/***/ (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 funnel
if ('initial' in pt) out.initial = pt.initial;
if ('delta' in pt) out.delta = pt.delta;
if ('final' in pt) out.final = pt.final;
if (pt.xa) out.xaxis = pt.xa;
if (pt.ya) out.yaxis = pt.ya;
return out;
};
/***/ }),
/***/ 94196:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hoverLabelText = (__webpack_require__(54460).hoverLabelText);
var opacity = (__webpack_require__(76308).opacity);
var hoverOnBars = (__webpack_require__(63400).hoverOnBars);
var delta = __webpack_require__(48164);
var DIRSYMBOL = {
increasing: delta.INCREASING.SYMBOL,
decreasing: delta.DECREASING.SYMBOL
};
module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
var point = hoverOnBars(pointData, xval, yval, hovermode, opts);
if (!point) return;
var cd = point.cd;
var trace = cd[0].trace;
var isHorizontal = trace.orientation === 'h';
var vLetter = isHorizontal ? 'x' : 'y';
var vAxis = isHorizontal ? pointData.xa : pointData.ya;
function formatNumber(a) {
return hoverLabelText(vAxis, a, trace[vLetter + 'hoverformat']);
}
// the closest data point
var index = point.index;
var di = cd[index];
var size = di.isSum ? di.b + di.s : di.rawS;
point.initial = di.b + di.s - size;
point.delta = size;
point.final = point.initial + point.delta;
var v = formatNumber(Math.abs(point.delta));
point.deltaLabel = size < 0 ? '(' + v + ')' : v;
point.finalLabel = formatNumber(point.final);
point.initialLabel = formatNumber(point.initial);
var hoverinfo = di.hi || trace.hoverinfo;
var text = [];
if (hoverinfo && hoverinfo !== 'none' && hoverinfo !== 'skip') {
var isAll = hoverinfo === 'all';
var parts = hoverinfo.split('+');
var hasFlag = function (flag) {
return isAll || parts.indexOf(flag) !== -1;
};
if (!di.isSum) {
if (hasFlag('final') && (isHorizontal ? !hasFlag('x') : !hasFlag('y')) // don't display redundant info.
) {
text.push(point.finalLabel);
}
if (hasFlag('delta')) {
if (size < 0) {
text.push(point.deltaLabel + ' ' + DIRSYMBOL.decreasing);
} else {
text.push(point.deltaLabel + ' ' + DIRSYMBOL.increasing);
}
}
if (hasFlag('initial')) {
text.push('Initial: ' + point.initialLabel);
}
}
}
if (text.length) point.extraText = text.join(' ');
point.color = getTraceColor(trace, di);
return [point];
};
function getTraceColor(trace, di) {
var cont = trace[di.dir].marker;
var mc = cont.color;
var mlc = cont.line.color;
var mlw = cont.line.width;
if (opacity(mc)) return mc;else if (opacity(mlc) && mlw) return mlc;
}
/***/ }),
/***/ 95952:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(65776),
layoutAttributes: __webpack_require__(91352),
supplyDefaults: (__webpack_require__(24224).supplyDefaults),
crossTraceDefaults: (__webpack_require__(24224).crossTraceDefaults),
supplyLayoutDefaults: __webpack_require__(59464),
calc: __webpack_require__(73540),
crossTraceCalc: __webpack_require__(50152),
plot: __webpack_require__(64488),
style: (__webpack_require__(12252).style),
hoverPoints: __webpack_require__(94196),
eventData: __webpack_require__(53256),
selectPoints: __webpack_require__(45784),
moduleType: 'trace',
name: 'waterfall',
basePlotModule: __webpack_require__(57952),
categories: ['bar-like', 'cartesian', 'svg', 'oriented', 'showLegend', 'zoomScale'],
meta: {}
};
/***/ }),
/***/ 91352:
/***/ (function(module) {
"use strict";
module.exports = {
waterfallmode: {
valType: 'enumerated',
values: ['group', 'overlay'],
dflt: 'group',
editType: 'calc'
},
waterfallgap: {
valType: 'number',
min: 0,
max: 1,
editType: 'calc'
},
waterfallgroupgap: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
editType: 'calc'
}
};
/***/ }),
/***/ 59464:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(91352);
module.exports = function (layoutIn, layoutOut, fullData) {
var hasTraceType = false;
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
for (var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (trace.visible && trace.type === 'waterfall') {
hasTraceType = true;
break;
}
}
if (hasTraceType) {
coerce('waterfallmode');
coerce('waterfallgap', 0.2);
coerce('waterfallgroupgap');
}
};
/***/ }),
/***/ 64488:
/***/ (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 BADNUM = (__webpack_require__(39032).BADNUM);
var barPlot = __webpack_require__(98184);
var clearMinTextSize = (__webpack_require__(82744).clearMinTextSize);
module.exports = function plot(gd, plotinfo, cdModule, traceLayer) {
var fullLayout = gd._fullLayout;
clearMinTextSize('waterfall', fullLayout);
barPlot.plot(gd, plotinfo, cdModule, traceLayer, {
mode: fullLayout.waterfallmode,
norm: fullLayout.waterfallmode,
gap: fullLayout.waterfallgap,
groupgap: fullLayout.waterfallgroupgap
});
plotConnectors(gd, plotinfo, cdModule, traceLayer);
};
function plotConnectors(gd, plotinfo, cdModule, traceLayer) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
Lib.makeTraceGroups(traceLayer, cdModule, 'trace bars').each(function (cd) {
var plotGroup = d3.select(this);
var trace = cd[0].trace;
var group = Lib.ensureSingle(plotGroup, 'g', 'lines');
if (!trace.connector || !trace.connector.visible) {
group.remove();
return;
}
var isHorizontal = trace.orientation === 'h';
var mode = trace.connector.mode;
var connectors = group.selectAll('g.line').data(Lib.identity);
connectors.enter().append('g').classed('line', true);
connectors.exit().remove();
var len = connectors.size();
connectors.each(function (di, i) {
// don't draw lines between nulls
if (i !== len - 1 && !di.cNext) return;
var xy = getXY(di, xa, ya, isHorizontal);
var x = xy[0];
var y = xy[1];
var shape = '';
if (x[0] !== BADNUM && y[0] !== BADNUM && x[1] !== BADNUM && y[1] !== BADNUM) {
if (mode === 'spanning') {
if (!di.isSum && i > 0) {
if (isHorizontal) {
shape += 'M' + x[0] + ',' + y[1] + 'V' + y[0];
} else {
shape += 'M' + x[1] + ',' + y[0] + 'H' + x[0];
}
}
}
if (mode !== 'between') {
if (di.isSum || i < len - 1) {
if (isHorizontal) {
shape += 'M' + x[1] + ',' + y[0] + 'V' + y[1];
} else {
shape += 'M' + x[0] + ',' + y[1] + 'H' + x[1];
}
}
}
if (x[2] !== BADNUM && y[2] !== BADNUM) {
if (isHorizontal) {
shape += 'M' + x[1] + ',' + y[1] + 'V' + y[2];
} else {
shape += 'M' + x[1] + ',' + y[1] + 'H' + x[2];
}
}
}
if (shape === '') shape = 'M0,0Z';
Lib.ensureSingle(d3.select(this), 'path').attr('d', shape).call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
});
});
}
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);
s[2] = sAxis.c2p(di.nextS0, true);
p[2] = pAxis.c2p(di.nextP0, true);
return isHorizontal ? [s, p] : [p, s];
}
/***/ }),
/***/ 12252:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var DESELECTDIM = (__webpack_require__(13448).DESELECTDIM);
var barStyle = __webpack_require__(60100);
var resizeText = (__webpack_require__(82744).resizeText);
var styleTextPoints = barStyle.styleTextPoints;
function style(gd, cd, sel) {
var s = sel ? sel : d3.select(gd).selectAll('g[class^="waterfalllayer"]').selectAll('g.trace');
resizeText(gd, s, 'waterfall');
s.style('opacity', function (d) {
return d[0].trace.opacity;
});
s.each(function (d) {
var gTrace = d3.select(this);
var trace = d[0].trace;
gTrace.selectAll('.point > path').each(function (di) {
if (!di.isBlank) {
var cont = trace[di.dir].marker;
d3.select(this).call(Color.fill, cont.color).call(Color.stroke, cont.line.color).call(Drawing.dashLine, cont.line.dash, cont.line.width).style('opacity', trace.selectedpoints && !di.selected ? DESELECTDIM : 1);
}
});
styleTextPoints(gTrace, trace, gd);
gTrace.selectAll('.lines').each(function () {
var cont = trace.connector.line;
Drawing.lineGroupStyle(d3.select(this).selectAll('path'), cont.width, cont.color, cont.dash);
});
});
}
module.exports = {
style: style
};
/***/ }),
/***/ 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.34.0';
/***/ }),
/***/ 67792:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/* provided dependency */ var process = __webpack_require__(4168);
/******/(function(){// webpackBootstrap
/******/var __webpack_modules__={/***/1964:/***/function(module,__unused_webpack_exports,__nested_webpack_require_129__){module.exports={alpha_shape:__nested_webpack_require_129__(3502),convex_hull:__nested_webpack_require_129__(7352),delaunay_triangulate:__nested_webpack_require_129__(7642),gl_cone3d:__nested_webpack_require_129__(6405),gl_error3d:__nested_webpack_require_129__(9165),gl_heatmap2d:__nested_webpack_require_129__(2510),gl_line3d:__nested_webpack_require_129__(5714),gl_mesh3d:__nested_webpack_require_129__(7201),gl_plot2d:__nested_webpack_require_129__(1850),gl_plot3d:__nested_webpack_require_129__(4100),gl_pointcloud2d:__nested_webpack_require_129__(4696),gl_scatter3d:__nested_webpack_require_129__(8418),gl_select_box:__nested_webpack_require_129__(3161),gl_spikes2d:__nested_webpack_require_129__(4098),gl_streamtube3d:__nested_webpack_require_129__(7815),gl_surface3d:__nested_webpack_require_129__(9499),ndarray:__nested_webpack_require_129__(9618),ndarray_linear_interpolate:__nested_webpack_require_129__(4317)};/***/},/***/4793:/***/function(__unused_webpack_module,exports,__nested_webpack_require_936__){"use strict";var __webpack_unused_export__;/*!
* 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;iK_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=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);ibuffer.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;imax)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= `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;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining;}}var strLen=string.length;if(length>strLen/2){length=strLen/2;}var i;for(i=0;i>>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(i0xEF?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(ilen)end=len;var out='';for(var i=start;ilen){start=len;}if(end<0){end+=len;if(end<0)end=0;}else if(end>len){end=len;}if(endlength)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>>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)<>>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)<>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=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)<>>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)<>>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||valuebuf.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>>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>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=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>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==='number'){for(i=start;iMath.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||value3){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;i0xD7FF&&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>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=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');}/***/},/***/9216:/***/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;}/***/},/***/6296:/***/function(module,__unused_webpack_exports,__nested_webpack_require_53135__){"use strict";module.exports=createViewController;var createTurntable=__nested_webpack_require_53135__(7261);var createOrbit=__nested_webpack_require_53135__(9977);var createMatrix=__nested_webpack_require_53135__(4192);function ViewController(controllers,mode){this._controllerNames=Object.keys(controllers);this._controllerList=this._controllerNames.map(function(n){return controllers[n];});this._mode=mode;this._active=controllers[mode];if(!this._active){this._mode='turntable';this._active=controllers.turntable;}this.modes=this._controllerNames;this.computedMatrix=this._active.computedMatrix;this.computedEye=this._active.computedEye;this.computedUp=this._active.computedUp;this.computedCenter=this._active.computedCenter;this.computedRadius=this._active.computedRadius;}var proto=ViewController.prototype;proto.flush=function(a0){var cc=this._controllerList;for(var i=0;i0){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>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;ilen2?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('');}/***/},/***/3865:/***/function(module,__unused_webpack_exports,__nested_webpack_require_63262__){"use strict";var rationalize=__nested_webpack_require_63262__(869);module.exports=add;function add(a,b){return rationalize(a[0].mul(b[1]).add(b[0].mul(a[1])),a[1].mul(b[1]));}/***/},/***/1318:/***/function(module){"use strict";module.exports=cmp;function cmp(a,b){return a[0].mul(b[1]).cmp(b[0].mul(a[1]));}/***/},/***/8697:/***/function(module,__unused_webpack_exports,__nested_webpack_require_63640__){"use strict";var rationalize=__nested_webpack_require_63640__(869);module.exports=div;function div(a,b){return rationalize(a[0].mul(b[1]),a[1].mul(b[0]));}/***/},/***/7842:/***/function(module,__unused_webpack_exports,__nested_webpack_require_63866__){"use strict";var isRat=__nested_webpack_require_63866__(6330);var isBN=__nested_webpack_require_63866__(1533);var num2bn=__nested_webpack_require_63866__(2651);var str2bn=__nested_webpack_require_63866__(4387);var rationalize=__nested_webpack_require_63866__(869);var div=__nested_webpack_require_63866__(8697);module.exports=makeRational;function makeRational(numer,denom){if(isRat(numer)){if(denom){return div(numer,makeRational(denom));}return[numer[0].clone(),numer[1].clone()];}var shift=0;var a,b;if(isBN(numer)){a=numer.clone();}else if(typeof numer==='string'){a=str2bn(numer);}else if(numer===0){return[num2bn(0),num2bn(1)];}else if(numer===Math.floor(numer)){a=num2bn(numer);}else{while(numer!==Math.floor(numer)){numer=numer*Math.pow(2,256);shift-=256;}a=num2bn(numer);}if(isRat(denom)){a.mul(denom[1]);b=denom[0].clone();}else if(isBN(denom)){b=denom.clone();}else if(typeof denom==='string'){b=str2bn(denom);}else if(!denom){b=num2bn(1);}else if(denom===Math.floor(denom)){b=num2bn(denom);}else{while(denom!==Math.floor(denom)){denom=denom*Math.pow(2,256);shift+=256;}b=num2bn(denom);}if(shift>0){a=a.ushln(shift);}else if(shift<0){b=b.ushln(-shift);}return rationalize(a,b);}/***/},/***/6330:/***/function(module,__unused_webpack_exports,__nested_webpack_require_65061__){"use strict";var isBN=__nested_webpack_require_65061__(1533);module.exports=isRat;function isRat(x){return Array.isArray(x)&&x.length===2&&isBN(x[0])&&isBN(x[1]);}/***/},/***/5716:/***/function(module,__unused_webpack_exports,__nested_webpack_require_65295__){"use strict";var BN=__nested_webpack_require_65295__(6859);module.exports=sign;function sign(x){return x.cmp(new BN(0));}/***/},/***/1369:/***/function(module,__unused_webpack_exports,__nested_webpack_require_65487__){"use strict";var sign=__nested_webpack_require_65487__(5716);module.exports=bn2num;//TODO: Make this better
function bn2num(b){var l=b.length;var words=b.words;var out=0;if(l===1){out=words[0];}else if(l===2){out=words[0]+words[1]*0x4000000;}else{for(var i=0;i20){return 52;}return h+32;}/***/},/***/1533:/***/function(module,__unused_webpack_exports,__nested_webpack_require_66252__){"use strict";var BN=__nested_webpack_require_66252__(6859);module.exports=isBN;//Test if x is a bignumber
//FIXME: obviously this is the wrong way to do it
function isBN(x){return x&&typeof x==='object'&&Boolean(x.words);}/***/},/***/2651:/***/function(module,__unused_webpack_exports,__nested_webpack_require_66545__){"use strict";var BN=__nested_webpack_require_66545__(6859);var db=__nested_webpack_require_66545__(2361);module.exports=num2bn;function num2bn(x){var e=db.exponent(x);if(e<52){return new BN(x);}else{return new BN(x*Math.pow(2,52-e)).ushln(e-52);}}/***/},/***/869:/***/function(module,__unused_webpack_exports,__nested_webpack_require_66849__){"use strict";var num2bn=__nested_webpack_require_66849__(2651);var sign=__nested_webpack_require_66849__(5716);module.exports=rationalize;function rationalize(numer,denom){var snumer=sign(numer);var sdenom=sign(denom);if(snumer===0){return[num2bn(0),num2bn(1)];}if(sdenom===0){return[num2bn(0),num2bn(0)];}if(sdenom<0){numer=numer.neg();denom=denom.neg();}var d=numer.gcd(denom);if(d.cmpn(1)){return[numer.div(d),denom.div(d)];}return[numer,denom];}/***/},/***/4387:/***/function(module,__unused_webpack_exports,__nested_webpack_require_67356__){"use strict";var BN=__nested_webpack_require_67356__(6859);module.exports=str2BN;function str2BN(x){return new BN(x);}/***/},/***/6504:/***/function(module,__unused_webpack_exports,__nested_webpack_require_67545__){"use strict";var rationalize=__nested_webpack_require_67545__(869);module.exports=mul;function mul(a,b){return rationalize(a[0].mul(b[0]),a[1].mul(b[1]));}/***/},/***/7721:/***/function(module,__unused_webpack_exports,__nested_webpack_require_67771__){"use strict";var bnsign=__nested_webpack_require_67771__(5716);module.exports=sign;function sign(x){return bnsign(x[0])*bnsign(x[1]);}/***/},/***/5572:/***/function(module,__unused_webpack_exports,__nested_webpack_require_67976__){"use strict";var rationalize=__nested_webpack_require_67976__(869);module.exports=sub;function sub(a,b){return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])),a[1].mul(b[1]));}/***/},/***/946:/***/function(module,__unused_webpack_exports,__nested_webpack_require_68221__){"use strict";var bn2num=__nested_webpack_require_68221__(1369);var ctz=__nested_webpack_require_68221__(4025);module.exports=roundRat;// Round a rational to the closest float
function roundRat(f){var a=f[0];var b=f[1];if(a.cmpn(0)===0){return 0;}var h=a.abs().divmod(b.abs());var iv=h.div;var x=bn2num(iv);var ir=h.mod;var sgn=a.negative!==b.negative?-1:1;if(ir.cmpn(0)===0){return sgn*x;}if(x){var s=ctz(x)+4;var y=bn2num(ir.ushln(s).divRound(b));return sgn*(x+y*Math.pow(2,-s));}else{var ybits=b.bitLength()-ir.bitLength()+53;var y=bn2num(ir.ushln(ybits).divRound(b));if(ybits<1023){return sgn*y*Math.pow(2,-ybits);}y*=Math.pow(2,-1023);return sgn*y*Math.pow(2,1023-ybits);}}/***/},/***/2478:/***/function(module){"use strict";// (a, y, c, l, h) = (array, y[, cmp, lo, hi])
function ge(a,y,c,l,h){var i=h+1;while(l<=h){var m=l+h>>>1,x=a[m];var p=c!==undefined?c(x,y):x-y;if(p>=0){i=m;h=m-1;}else{l=m+1;}}return i;};function gt(a,y,c,l,h){var i=h+1;while(l<=h){var m=l+h>>>1,x=a[m];var p=c!==undefined?c(x,y):x-y;if(p>0){i=m;h=m-1;}else{l=m+1;}}return i;};function lt(a,y,c,l,h){var i=l-1;while(l<=h){var m=l+h>>>1,x=a[m];var p=c!==undefined?c(x,y):x-y;if(p<0){i=m;l=m+1;}else{h=m-1;}}return i;};function le(a,y,c,l,h){var i=l-1;while(l<=h){var m=l+h>>>1,x=a[m];var p=c!==undefined?c(x,y):x-y;if(p<=0){i=m;l=m+1;}else{h=m-1;}}return i;};function eq(a,y,c,l,h){while(l<=h){var m=l+h>>>1,x=a[m];var p=c!==undefined?c(x,y):x-y;if(p===0){return m;}if(p<=0){l=m+1;}else{h=m-1;}}return-1;};function norm(a,y,c,l,h,f){if(typeof c==='function'){return f(a,y,c,l===undefined?0:l|0,h===undefined?a.length-1:h|0);}return f(a,y,undefined,c===undefined?0:c|0,l===undefined?a.length-1:l|0);}module.exports={ge:function(a,y,c,l,h){return norm(a,y,c,l,h,ge);},gt:function(a,y,c,l,h){return norm(a,y,c,l,h,gt);},lt:function(a,y,c,l,h){return norm(a,y,c,l,h,lt);},le:function(a,y,c,l,h){return norm(a,y,c,l,h,le);},eq:function(a,y,c,l,h){return norm(a,y,c,l,h,eq);}};/***/},/***/8828:/***/function(__unused_webpack_module,exports){"use strict";/**
* Bit twiddling hacks for JavaScript.
*
* Author: Mikola Lysenko
*
* Ported from Stanford bit twiddling hack library:
* http://graphics.stanford.edu/~seander/bithacks.html
*/"use restrict";//Number of bits in an integer
var INT_BITS=32;//Constants
exports.INT_BITS=INT_BITS;exports.INT_MAX=0x7fffffff;exports.INT_MIN=-1<0)-(v<0);};//Computes absolute value of integer
exports.abs=function(v){var mask=v>>INT_BITS-1;return(v^mask)-mask;};//Computes minimum of integers x and y
exports.min=function(x,y){return y^(x^y)&-(x0xFFFF)<<4;v>>>=r;shift=(v>0xFF)<<3;v>>>=shift;r|=shift;shift=(v>0xF)<<2;v>>>=shift;r|=shift;shift=(v>0x3)<<1;v>>>=shift;r|=shift;return r|v>>1;};//Computes log base 10 of v
exports.log10=function(v){return v>=1000000000?9:v>=100000000?8:v>=10000000?7:v>=1000000?6:v>=100000?5:v>=10000?4:v>=1000?3:v>=100?2:v>=10?1:0;};//Counts number of bits
exports.popCount=function(v){v=v-(v>>>1&0x55555555);v=(v&0x33333333)+(v>>>2&0x33333333);return(v+(v>>>4)&0xF0F0F0F)*0x1010101>>>24;};//Counts number of trailing zeros
function countTrailingZeros(v){var c=32;v&=-v;if(v)c--;if(v&0x0000FFFF)c-=16;if(v&0x00FF00FF)c-=8;if(v&0x0F0F0F0F)c-=4;if(v&0x33333333)c-=2;if(v&0x55555555)c-=1;return c;}exports.countTrailingZeros=countTrailingZeros;//Rounds to next power of 2
exports.nextPow2=function(v){v+=v===0;--v;v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v+1;};//Rounds down to previous power of 2
exports.prevPow2=function(v){v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v-(v>>>1);};//Computes parity of word
exports.parity=function(v){v^=v>>>16;v^=v>>>8;v^=v>>>4;v&=0xf;return 0x6996>>>v&1;};var REVERSE_TABLE=new Array(256);(function(tab){for(var i=0;i<256;++i){var v=i,r=i,s=7;for(v>>>=1;v;v>>>=1){r<<=1;r|=v&1;--s;}tab[i]=r<>>8&0xff]<<16|REVERSE_TABLE[v>>>16&0xff]<<8|REVERSE_TABLE[v>>>24&0xff];};//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes
exports.interleave2=function(x,y){x&=0xFFFF;x=(x|x<<8)&0x00FF00FF;x=(x|x<<4)&0x0F0F0F0F;x=(x|x<<2)&0x33333333;x=(x|x<<1)&0x55555555;y&=0xFFFF;y=(y|y<<8)&0x00FF00FF;y=(y|y<<4)&0x0F0F0F0F;y=(y|y<<2)&0x33333333;y=(y|y<<1)&0x55555555;return x|y<<1;};//Extracts the nth interleaved component
exports.deinterleave2=function(v,n){v=v>>>n&0x55555555;v=(v|v>>>1)&0x33333333;v=(v|v>>>2)&0x0F0F0F0F;v=(v|v>>>4)&0x00FF00FF;v=(v|v>>>16)&0x000FFFF;return v<<16>>16;};//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes
exports.interleave3=function(x,y,z){x&=0x3FF;x=(x|x<<16)&4278190335;x=(x|x<<8)&251719695;x=(x|x<<4)&3272356035;x=(x|x<<2)&1227133513;y&=0x3FF;y=(y|y<<16)&4278190335;y=(y|y<<8)&251719695;y=(y|y<<4)&3272356035;y=(y|y<<2)&1227133513;x|=y<<1;z&=0x3FF;z=(z|z<<16)&4278190335;z=(z|z<<8)&251719695;z=(z|z<<4)&3272356035;z=(z|z<<2)&1227133513;return x|z<<2;};//Extracts nth interleaved component of a 3-tuple
exports.deinterleave3=function(v,n){v=v>>>n&1227133513;v=(v|v>>>2)&3272356035;v=(v|v>>>4)&251719695;v=(v|v>>>8)&4278190335;v=(v|v>>>16)&0x3FF;return v<<22>>22;};//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)
exports.nextCombination=function(v){var t=v|v-1;return t+1|(~t&-~t)-1>>>countTrailingZeros(v)+1;};/***/},/***/6859:/***/function(module,__unused_webpack_exports,__nested_webpack_require_74030__){/* module decorator */module=__nested_webpack_require_74030__.nmd(module);(function(module,exports){'use strict';// Utils
function assert(val,msg){if(!val)throw new Error(msg||'Assertion failed');}// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor();ctor.prototype.constructor=ctor;}// BN
function BN(number,base,endian){if(BN.isBN(number)){return number;}this.negative=0;this.words=null;this.length=0;// Reduction context
this.red=null;if(number!==null){if(base==='le'||base==='be'){endian=base;base=10;}this._init(number||0,base||10,endian||'be');}}if(typeof module==='object'){module.exports=BN;}else{exports.BN=BN;}BN.BN=BN;BN.wordSize=26;var Buffer;try{if(typeof window!=='undefined'&&typeof window.Buffer!=='undefined'){Buffer=window.Buffer;}else{Buffer=__nested_webpack_require_74030__(7790).Buffer;}}catch(e){}BN.isBN=function isBN(num){if(num instanceof BN){return true;}return num!==null&&typeof num==='object'&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words);};BN.max=function max(left,right){if(left.cmp(right)>0)return left;return right;};BN.min=function min(left,right){if(left.cmp(right)<0)return left;return right;};BN.prototype._init=function init(number,base,endian){if(typeof number==='number'){return this._initNumber(number,base,endian);}if(typeof number==='object'){return this._initArray(number,base,endian);}if(base==='hex'){base=16;}assert(base===(base|0)&&base>=2&&base<=36);number=number.toString().replace(/\s+/g,'');var start=0;if(number[0]==='-'){start++;this.negative=1;}if(start=0;i-=3){w=number[i]|number[i-1]<<8|number[i-2]<<16;this.words[j]|=w<>>26-off&0x3ffffff;off+=24;if(off>=26){off-=26;j++;}}}else if(endian==='le'){for(i=0,j=0;i>>26-off&0x3ffffff;off+=24;if(off>=26){off-=26;j++;}}}return this.strip();};function parseHex4Bits(string,index){var c=string.charCodeAt(index);// 'A' - 'F'
if(c>=65&&c<=70){return c-55;// 'a' - 'f'
}else if(c>=97&&c<=102){return c-87;// '0' - '9'
}else{return c-48&0xf;}}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);if(index-1>=lowerBound){r|=parseHex4Bits(string,index-1)<<4;}return r;}BN.prototype._parseHex=function _parseHex(number,start,endian){// Create possibly bigger array to ensure that it fits the number
this.length=Math.ceil((number.length-start)/6);this.words=new Array(this.length);for(var i=0;i=start;i-=2){w=parseHexByte(number,start,i)<=18){off-=18;j+=1;this.words[j]|=w>>>26;}else{off+=8;}}}else{var parseLength=number.length-start;for(i=parseLength%2===0?start+1:start;i=18){off-=18;j+=1;this.words[j]|=w>>>26;}else{off+=8;}}}this.strip();};function parseBase(str,start,end,mul){var r=0;var len=Math.min(str.length,end);for(var i=start;i=49){r+=c-49+0xa;// 'A'
}else if(c>=17){r+=c-17+0xa;// '0' - '9'
}else{r+=c;}}return r;}BN.prototype._parseBase=function _parseBase(number,base,start){// Initialize as zero
this.words=[0];this.length=1;// Find length of limb in base
for(var limbLen=0,limbPow=1;limbPow<=0x3ffffff;limbPow*=base){limbLen++;}limbLen--;limbPow=limbPow/base|0;var total=number.length-start;var mod=total%limbLen;var end=Math.min(total,total-mod)+start;var word=0;for(var i=start;i1&&this.words[this.length-1]===0){this.length--;}return this._normSign();};BN.prototype._normSign=function _normSign(){// -0 = 0
if(this.length===1&&this.words[0]===0){this.negative=0;}return this;};BN.prototype.inspect=function inspect(){return(this.red?'';};/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/var zeros=['','0','00','000','0000','00000','000000','0000000','00000000','000000000','0000000000','00000000000','000000000000','0000000000000','00000000000000','000000000000000','0000000000000000','00000000000000000','000000000000000000','0000000000000000000','00000000000000000000','000000000000000000000','0000000000000000000000','00000000000000000000000','000000000000000000000000','0000000000000000000000000'];var groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];var groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,10000000,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10;padding=padding|0||1;var out;if(base===16||base==='hex'){out='';var off=0;var carry=0;for(var i=0;i>>24-off&0xffffff;if(carry!==0||i!==this.length-1){out=zeros[6-word.length]+word+out;}else{out=word+out;}off+=2;if(off>=26){off-=26;i--;}}if(carry!==0){out=carry.toString(16)+out;}while(out.length%padding!==0){out='0'+out;}if(this.negative!==0){out='-'+out;}return out;}if(base===(base|0)&&base>=2&&base<=36){// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize=groupSizes[base];// var groupBase = Math.pow(base, groupSize);
var groupBase=groupBases[base];out='';var c=this.clone();c.negative=0;while(!c.isZero()){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase);if(!c.isZero()){out=zeros[groupSize-r.length]+r+out;}else{out=r+out;}}if(this.isZero()){out='0'+out;}while(out.length%padding!==0){out='0'+out;}if(this.negative!==0){out='-'+out;}return out;}assert(false,'Base should be between 2 and 36');};BN.prototype.toNumber=function toNumber(){var ret=this.words[0];if(this.length===2){ret+=this.words[1]*0x4000000;}else if(this.length===3&&this.words[2]===0x01){// NOTE: at this stage it is known that the top bit is set
ret+=0x10000000000000+this.words[1]*0x4000000;}else if(this.length>2){assert(false,'Number can only safely store up to 53 bits');}return this.negative!==0?-ret:ret;};BN.prototype.toJSON=function toJSON(){return this.toString(16);};BN.prototype.toBuffer=function toBuffer(endian,length){assert(typeof Buffer!=='undefined');return this.toArrayLike(Buffer,endian,length);};BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length);};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength();var reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,'byte array longer than desired length');assert(reqLength>0,'Requested array length <= 0');this.strip();var littleEndian=endian==='le';var res=new ArrayType(reqLength);var b,i;var q=this.clone();if(!littleEndian){// Assume big-endian
for(i=0;i=0x1000){r+=13;t>>>=13;}if(t>=0x40){r+=7;t>>>=7;}if(t>=0x8){r+=4;t>>>=4;}if(t>=0x02){r+=2;t>>>=2;}return r+t;};}BN.prototype._zeroBits=function _zeroBits(w){// Short-cut
if(w===0)return 26;var t=w;var r=0;if((t&0x1fff)===0){r+=13;t>>>=13;}if((t&0x7f)===0){r+=7;t>>>=7;}if((t&0xf)===0){r+=4;t>>>=4;}if((t&0x3)===0){r+=2;t>>>=2;}if((t&0x1)===0){r++;}return r;};// Return number of used bits in a BN
BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1];var hi=this._countBits(w);return(this.length-1)*26+hi;};function toBitArray(num){var w=new Array(num.bitLength());for(var bit=0;bit>>wbit;}return w;}// Number of trailing zero bits
BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;var r=0;for(var i=0;inum.length)return this.clone().ior(num);return num.clone().ior(this);};BN.prototype.uor=function uor(num){if(this.length>num.length)return this.clone().iuor(num);return num.clone().iuor(this);};// And `num` with `this` in-place
BN.prototype.iuand=function iuand(num){// b = min-length(num, this)
var b;if(this.length>num.length){b=num;}else{b=this;}for(var i=0;inum.length)return this.clone().iand(num);return num.clone().iand(this);};BN.prototype.uand=function uand(num){if(this.length>num.length)return this.clone().iuand(num);return num.clone().iuand(this);};// Xor `num` with `this` in-place
BN.prototype.iuxor=function iuxor(num){// a.length > b.length
var a;var b;if(this.length>num.length){a=this;b=num;}else{a=num;b=this;}for(var i=0;inum.length)return this.clone().ixor(num);return num.clone().ixor(this);};BN.prototype.uxor=function uxor(num){if(this.length>num.length)return this.clone().iuxor(num);return num.clone().iuxor(this);};// Not ``this`` with ``width`` bitwidth
BN.prototype.inotn=function inotn(width){assert(typeof width==='number'&&width>=0);var bytesNeeded=Math.ceil(width/26)|0;var bitsLeft=width%26;// Extend the buffer with leading zeroes
this._expand(bytesNeeded);if(bitsLeft>0){bytesNeeded--;}// Handle complete words
for(var i=0;i0){this.words[i]=~this.words[i]&0x3ffffff>>26-bitsLeft;}// And remove leading zeroes
return this.strip();};BN.prototype.notn=function notn(width){return this.clone().inotn(width);};// Set `bit` of `this`
BN.prototype.setn=function setn(bit,val){assert(typeof bit==='number'&&bit>=0);var off=bit/26|0;var wbit=bit%26;this._expand(off+1);if(val){this.words[off]=this.words[off]|1< b.length
var a,b;if(this.length>num.length){a=this;b=num;}else{a=num;b=this;}var carry=0;for(var i=0;i>>26;}for(;carry!==0&&i>>26;}this.length=a.length;if(carry!==0){this.words[this.length]=carry;this.length++;// Copy the rest of the words
}else if(a!==this){for(;inum.length)return this.clone().iadd(num);return num.clone().iadd(this);};// Subtract `num` from `this` in-place
BN.prototype.isub=function isub(num){// this - (-num) = this + num
if(num.negative!==0){num.negative=0;var r=this.iadd(num);num.negative=1;return r._normSign();// -this - num = -(this + num)
}else if(this.negative!==0){this.negative=0;this.iadd(num);this.negative=1;return this._normSign();}// At this point both numbers are positive
var cmp=this.cmp(num);// Optimization - zeroify
if(cmp===0){this.negative=0;this.length=1;this.words[0]=0;return this;}// a > b
var a,b;if(cmp>0){a=this;b=num;}else{a=num;b=this;}var carry=0;for(var i=0;i>26;this.words[i]=r&0x3ffffff;}for(;carry!==0&&i>26;this.words[i]=r&0x3ffffff;}// Copy rest of the words
if(carry===0&&i= 0x3ffffff
var ncarry=carry>>>26;var rword=carry&0x3ffffff;var maxJ=Math.min(k,num.length-1);for(var j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;a=self.words[i]|0;b=num.words[j]|0;r=a*b+rword;ncarry+=r/0x4000000|0;rword=r&0x3ffffff;}out.words[k]=rword|0;carry=ncarry|0;}if(carry!==0){out.words[k]=carry|0;}else{out.length--;}return out.strip();}// TODO(indutny): it may be reasonable to omit it for users who don't need
// to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
// multiplication (like elliptic secp256k1).
var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words;var b=num.words;var o=out.words;var c=0;var lo;var mid;var hi;var a0=a[0]|0;var al0=a0&0x1fff;var ah0=a0>>>13;var a1=a[1]|0;var al1=a1&0x1fff;var ah1=a1>>>13;var a2=a[2]|0;var al2=a2&0x1fff;var ah2=a2>>>13;var a3=a[3]|0;var al3=a3&0x1fff;var ah3=a3>>>13;var a4=a[4]|0;var al4=a4&0x1fff;var ah4=a4>>>13;var a5=a[5]|0;var al5=a5&0x1fff;var ah5=a5>>>13;var a6=a[6]|0;var al6=a6&0x1fff;var ah6=a6>>>13;var a7=a[7]|0;var al7=a7&0x1fff;var ah7=a7>>>13;var a8=a[8]|0;var al8=a8&0x1fff;var ah8=a8>>>13;var a9=a[9]|0;var al9=a9&0x1fff;var ah9=a9>>>13;var b0=b[0]|0;var bl0=b0&0x1fff;var bh0=b0>>>13;var b1=b[1]|0;var bl1=b1&0x1fff;var bh1=b1>>>13;var b2=b[2]|0;var bl2=b2&0x1fff;var bh2=b2>>>13;var b3=b[3]|0;var bl3=b3&0x1fff;var bh3=b3>>>13;var b4=b[4]|0;var bl4=b4&0x1fff;var bh4=b4>>>13;var b5=b[5]|0;var bl5=b5&0x1fff;var bh5=b5>>>13;var b6=b[6]|0;var bl6=b6&0x1fff;var bh6=b6>>>13;var b7=b[7]|0;var bl7=b7&0x1fff;var bh7=b7>>>13;var b8=b[8]|0;var bl8=b8&0x1fff;var bh8=b8>>>13;var b9=b[9]|0;var bl9=b9&0x1fff;var bh9=b9>>>13;out.negative=self.negative^num.negative;out.length=19;/* k = 0 */lo=Math.imul(al0,bl0);mid=Math.imul(al0,bh0);mid=mid+Math.imul(ah0,bl0)|0;hi=Math.imul(ah0,bh0);var w0=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0;w0&=0x3ffffff;/* k = 1 */lo=Math.imul(al1,bl0);mid=Math.imul(al1,bh0);mid=mid+Math.imul(ah1,bl0)|0;hi=Math.imul(ah1,bh0);lo=lo+Math.imul(al0,bl1)|0;mid=mid+Math.imul(al0,bh1)|0;mid=mid+Math.imul(ah0,bl1)|0;hi=hi+Math.imul(ah0,bh1)|0;var w1=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0;w1&=0x3ffffff;/* k = 2 */lo=Math.imul(al2,bl0);mid=Math.imul(al2,bh0);mid=mid+Math.imul(ah2,bl0)|0;hi=Math.imul(ah2,bh0);lo=lo+Math.imul(al1,bl1)|0;mid=mid+Math.imul(al1,bh1)|0;mid=mid+Math.imul(ah1,bl1)|0;hi=hi+Math.imul(ah1,bh1)|0;lo=lo+Math.imul(al0,bl2)|0;mid=mid+Math.imul(al0,bh2)|0;mid=mid+Math.imul(ah0,bl2)|0;hi=hi+Math.imul(ah0,bh2)|0;var w2=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0;w2&=0x3ffffff;/* k = 3 */lo=Math.imul(al3,bl0);mid=Math.imul(al3,bh0);mid=mid+Math.imul(ah3,bl0)|0;hi=Math.imul(ah3,bh0);lo=lo+Math.imul(al2,bl1)|0;mid=mid+Math.imul(al2,bh1)|0;mid=mid+Math.imul(ah2,bl1)|0;hi=hi+Math.imul(ah2,bh1)|0;lo=lo+Math.imul(al1,bl2)|0;mid=mid+Math.imul(al1,bh2)|0;mid=mid+Math.imul(ah1,bl2)|0;hi=hi+Math.imul(ah1,bh2)|0;lo=lo+Math.imul(al0,bl3)|0;mid=mid+Math.imul(al0,bh3)|0;mid=mid+Math.imul(ah0,bl3)|0;hi=hi+Math.imul(ah0,bh3)|0;var w3=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0;w3&=0x3ffffff;/* k = 4 */lo=Math.imul(al4,bl0);mid=Math.imul(al4,bh0);mid=mid+Math.imul(ah4,bl0)|0;hi=Math.imul(ah4,bh0);lo=lo+Math.imul(al3,bl1)|0;mid=mid+Math.imul(al3,bh1)|0;mid=mid+Math.imul(ah3,bl1)|0;hi=hi+Math.imul(ah3,bh1)|0;lo=lo+Math.imul(al2,bl2)|0;mid=mid+Math.imul(al2,bh2)|0;mid=mid+Math.imul(ah2,bl2)|0;hi=hi+Math.imul(ah2,bh2)|0;lo=lo+Math.imul(al1,bl3)|0;mid=mid+Math.imul(al1,bh3)|0;mid=mid+Math.imul(ah1,bl3)|0;hi=hi+Math.imul(ah1,bh3)|0;lo=lo+Math.imul(al0,bl4)|0;mid=mid+Math.imul(al0,bh4)|0;mid=mid+Math.imul(ah0,bl4)|0;hi=hi+Math.imul(ah0,bh4)|0;var w4=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0;w4&=0x3ffffff;/* k = 5 */lo=Math.imul(al5,bl0);mid=Math.imul(al5,bh0);mid=mid+Math.imul(ah5,bl0)|0;hi=Math.imul(ah5,bh0);lo=lo+Math.imul(al4,bl1)|0;mid=mid+Math.imul(al4,bh1)|0;mid=mid+Math.imul(ah4,bl1)|0;hi=hi+Math.imul(ah4,bh1)|0;lo=lo+Math.imul(al3,bl2)|0;mid=mid+Math.imul(al3,bh2)|0;mid=mid+Math.imul(ah3,bl2)|0;hi=hi+Math.imul(ah3,bh2)|0;lo=lo+Math.imul(al2,bl3)|0;mid=mid+Math.imul(al2,bh3)|0;mid=mid+Math.imul(ah2,bl3)|0;hi=hi+Math.imul(ah2,bh3)|0;lo=lo+Math.imul(al1,bl4)|0;mid=mid+Math.imul(al1,bh4)|0;mid=mid+Math.imul(ah1,bl4)|0;hi=hi+Math.imul(ah1,bh4)|0;lo=lo+Math.imul(al0,bl5)|0;mid=mid+Math.imul(al0,bh5)|0;mid=mid+Math.imul(ah0,bl5)|0;hi=hi+Math.imul(ah0,bh5)|0;var w5=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0;w5&=0x3ffffff;/* k = 6 */lo=Math.imul(al6,bl0);mid=Math.imul(al6,bh0);mid=mid+Math.imul(ah6,bl0)|0;hi=Math.imul(ah6,bh0);lo=lo+Math.imul(al5,bl1)|0;mid=mid+Math.imul(al5,bh1)|0;mid=mid+Math.imul(ah5,bl1)|0;hi=hi+Math.imul(ah5,bh1)|0;lo=lo+Math.imul(al4,bl2)|0;mid=mid+Math.imul(al4,bh2)|0;mid=mid+Math.imul(ah4,bl2)|0;hi=hi+Math.imul(ah4,bh2)|0;lo=lo+Math.imul(al3,bl3)|0;mid=mid+Math.imul(al3,bh3)|0;mid=mid+Math.imul(ah3,bl3)|0;hi=hi+Math.imul(ah3,bh3)|0;lo=lo+Math.imul(al2,bl4)|0;mid=mid+Math.imul(al2,bh4)|0;mid=mid+Math.imul(ah2,bl4)|0;hi=hi+Math.imul(ah2,bh4)|0;lo=lo+Math.imul(al1,bl5)|0;mid=mid+Math.imul(al1,bh5)|0;mid=mid+Math.imul(ah1,bl5)|0;hi=hi+Math.imul(ah1,bh5)|0;lo=lo+Math.imul(al0,bl6)|0;mid=mid+Math.imul(al0,bh6)|0;mid=mid+Math.imul(ah0,bl6)|0;hi=hi+Math.imul(ah0,bh6)|0;var w6=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0;w6&=0x3ffffff;/* k = 7 */lo=Math.imul(al7,bl0);mid=Math.imul(al7,bh0);mid=mid+Math.imul(ah7,bl0)|0;hi=Math.imul(ah7,bh0);lo=lo+Math.imul(al6,bl1)|0;mid=mid+Math.imul(al6,bh1)|0;mid=mid+Math.imul(ah6,bl1)|0;hi=hi+Math.imul(ah6,bh1)|0;lo=lo+Math.imul(al5,bl2)|0;mid=mid+Math.imul(al5,bh2)|0;mid=mid+Math.imul(ah5,bl2)|0;hi=hi+Math.imul(ah5,bh2)|0;lo=lo+Math.imul(al4,bl3)|0;mid=mid+Math.imul(al4,bh3)|0;mid=mid+Math.imul(ah4,bl3)|0;hi=hi+Math.imul(ah4,bh3)|0;lo=lo+Math.imul(al3,bl4)|0;mid=mid+Math.imul(al3,bh4)|0;mid=mid+Math.imul(ah3,bl4)|0;hi=hi+Math.imul(ah3,bh4)|0;lo=lo+Math.imul(al2,bl5)|0;mid=mid+Math.imul(al2,bh5)|0;mid=mid+Math.imul(ah2,bl5)|0;hi=hi+Math.imul(ah2,bh5)|0;lo=lo+Math.imul(al1,bl6)|0;mid=mid+Math.imul(al1,bh6)|0;mid=mid+Math.imul(ah1,bl6)|0;hi=hi+Math.imul(ah1,bh6)|0;lo=lo+Math.imul(al0,bl7)|0;mid=mid+Math.imul(al0,bh7)|0;mid=mid+Math.imul(ah0,bl7)|0;hi=hi+Math.imul(ah0,bh7)|0;var w7=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0;w7&=0x3ffffff;/* k = 8 */lo=Math.imul(al8,bl0);mid=Math.imul(al8,bh0);mid=mid+Math.imul(ah8,bl0)|0;hi=Math.imul(ah8,bh0);lo=lo+Math.imul(al7,bl1)|0;mid=mid+Math.imul(al7,bh1)|0;mid=mid+Math.imul(ah7,bl1)|0;hi=hi+Math.imul(ah7,bh1)|0;lo=lo+Math.imul(al6,bl2)|0;mid=mid+Math.imul(al6,bh2)|0;mid=mid+Math.imul(ah6,bl2)|0;hi=hi+Math.imul(ah6,bh2)|0;lo=lo+Math.imul(al5,bl3)|0;mid=mid+Math.imul(al5,bh3)|0;mid=mid+Math.imul(ah5,bl3)|0;hi=hi+Math.imul(ah5,bh3)|0;lo=lo+Math.imul(al4,bl4)|0;mid=mid+Math.imul(al4,bh4)|0;mid=mid+Math.imul(ah4,bl4)|0;hi=hi+Math.imul(ah4,bh4)|0;lo=lo+Math.imul(al3,bl5)|0;mid=mid+Math.imul(al3,bh5)|0;mid=mid+Math.imul(ah3,bl5)|0;hi=hi+Math.imul(ah3,bh5)|0;lo=lo+Math.imul(al2,bl6)|0;mid=mid+Math.imul(al2,bh6)|0;mid=mid+Math.imul(ah2,bl6)|0;hi=hi+Math.imul(ah2,bh6)|0;lo=lo+Math.imul(al1,bl7)|0;mid=mid+Math.imul(al1,bh7)|0;mid=mid+Math.imul(ah1,bl7)|0;hi=hi+Math.imul(ah1,bh7)|0;lo=lo+Math.imul(al0,bl8)|0;mid=mid+Math.imul(al0,bh8)|0;mid=mid+Math.imul(ah0,bl8)|0;hi=hi+Math.imul(ah0,bh8)|0;var w8=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0;w8&=0x3ffffff;/* k = 9 */lo=Math.imul(al9,bl0);mid=Math.imul(al9,bh0);mid=mid+Math.imul(ah9,bl0)|0;hi=Math.imul(ah9,bh0);lo=lo+Math.imul(al8,bl1)|0;mid=mid+Math.imul(al8,bh1)|0;mid=mid+Math.imul(ah8,bl1)|0;hi=hi+Math.imul(ah8,bh1)|0;lo=lo+Math.imul(al7,bl2)|0;mid=mid+Math.imul(al7,bh2)|0;mid=mid+Math.imul(ah7,bl2)|0;hi=hi+Math.imul(ah7,bh2)|0;lo=lo+Math.imul(al6,bl3)|0;mid=mid+Math.imul(al6,bh3)|0;mid=mid+Math.imul(ah6,bl3)|0;hi=hi+Math.imul(ah6,bh3)|0;lo=lo+Math.imul(al5,bl4)|0;mid=mid+Math.imul(al5,bh4)|0;mid=mid+Math.imul(ah5,bl4)|0;hi=hi+Math.imul(ah5,bh4)|0;lo=lo+Math.imul(al4,bl5)|0;mid=mid+Math.imul(al4,bh5)|0;mid=mid+Math.imul(ah4,bl5)|0;hi=hi+Math.imul(ah4,bh5)|0;lo=lo+Math.imul(al3,bl6)|0;mid=mid+Math.imul(al3,bh6)|0;mid=mid+Math.imul(ah3,bl6)|0;hi=hi+Math.imul(ah3,bh6)|0;lo=lo+Math.imul(al2,bl7)|0;mid=mid+Math.imul(al2,bh7)|0;mid=mid+Math.imul(ah2,bl7)|0;hi=hi+Math.imul(ah2,bh7)|0;lo=lo+Math.imul(al1,bl8)|0;mid=mid+Math.imul(al1,bh8)|0;mid=mid+Math.imul(ah1,bl8)|0;hi=hi+Math.imul(ah1,bh8)|0;lo=lo+Math.imul(al0,bl9)|0;mid=mid+Math.imul(al0,bh9)|0;mid=mid+Math.imul(ah0,bl9)|0;hi=hi+Math.imul(ah0,bh9)|0;var w9=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0;w9&=0x3ffffff;/* k = 10 */lo=Math.imul(al9,bl1);mid=Math.imul(al9,bh1);mid=mid+Math.imul(ah9,bl1)|0;hi=Math.imul(ah9,bh1);lo=lo+Math.imul(al8,bl2)|0;mid=mid+Math.imul(al8,bh2)|0;mid=mid+Math.imul(ah8,bl2)|0;hi=hi+Math.imul(ah8,bh2)|0;lo=lo+Math.imul(al7,bl3)|0;mid=mid+Math.imul(al7,bh3)|0;mid=mid+Math.imul(ah7,bl3)|0;hi=hi+Math.imul(ah7,bh3)|0;lo=lo+Math.imul(al6,bl4)|0;mid=mid+Math.imul(al6,bh4)|0;mid=mid+Math.imul(ah6,bl4)|0;hi=hi+Math.imul(ah6,bh4)|0;lo=lo+Math.imul(al5,bl5)|0;mid=mid+Math.imul(al5,bh5)|0;mid=mid+Math.imul(ah5,bl5)|0;hi=hi+Math.imul(ah5,bh5)|0;lo=lo+Math.imul(al4,bl6)|0;mid=mid+Math.imul(al4,bh6)|0;mid=mid+Math.imul(ah4,bl6)|0;hi=hi+Math.imul(ah4,bh6)|0;lo=lo+Math.imul(al3,bl7)|0;mid=mid+Math.imul(al3,bh7)|0;mid=mid+Math.imul(ah3,bl7)|0;hi=hi+Math.imul(ah3,bh7)|0;lo=lo+Math.imul(al2,bl8)|0;mid=mid+Math.imul(al2,bh8)|0;mid=mid+Math.imul(ah2,bl8)|0;hi=hi+Math.imul(ah2,bh8)|0;lo=lo+Math.imul(al1,bl9)|0;mid=mid+Math.imul(al1,bh9)|0;mid=mid+Math.imul(ah1,bl9)|0;hi=hi+Math.imul(ah1,bh9)|0;var w10=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0;w10&=0x3ffffff;/* k = 11 */lo=Math.imul(al9,bl2);mid=Math.imul(al9,bh2);mid=mid+Math.imul(ah9,bl2)|0;hi=Math.imul(ah9,bh2);lo=lo+Math.imul(al8,bl3)|0;mid=mid+Math.imul(al8,bh3)|0;mid=mid+Math.imul(ah8,bl3)|0;hi=hi+Math.imul(ah8,bh3)|0;lo=lo+Math.imul(al7,bl4)|0;mid=mid+Math.imul(al7,bh4)|0;mid=mid+Math.imul(ah7,bl4)|0;hi=hi+Math.imul(ah7,bh4)|0;lo=lo+Math.imul(al6,bl5)|0;mid=mid+Math.imul(al6,bh5)|0;mid=mid+Math.imul(ah6,bl5)|0;hi=hi+Math.imul(ah6,bh5)|0;lo=lo+Math.imul(al5,bl6)|0;mid=mid+Math.imul(al5,bh6)|0;mid=mid+Math.imul(ah5,bl6)|0;hi=hi+Math.imul(ah5,bh6)|0;lo=lo+Math.imul(al4,bl7)|0;mid=mid+Math.imul(al4,bh7)|0;mid=mid+Math.imul(ah4,bl7)|0;hi=hi+Math.imul(ah4,bh7)|0;lo=lo+Math.imul(al3,bl8)|0;mid=mid+Math.imul(al3,bh8)|0;mid=mid+Math.imul(ah3,bl8)|0;hi=hi+Math.imul(ah3,bh8)|0;lo=lo+Math.imul(al2,bl9)|0;mid=mid+Math.imul(al2,bh9)|0;mid=mid+Math.imul(ah2,bl9)|0;hi=hi+Math.imul(ah2,bh9)|0;var w11=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0;w11&=0x3ffffff;/* k = 12 */lo=Math.imul(al9,bl3);mid=Math.imul(al9,bh3);mid=mid+Math.imul(ah9,bl3)|0;hi=Math.imul(ah9,bh3);lo=lo+Math.imul(al8,bl4)|0;mid=mid+Math.imul(al8,bh4)|0;mid=mid+Math.imul(ah8,bl4)|0;hi=hi+Math.imul(ah8,bh4)|0;lo=lo+Math.imul(al7,bl5)|0;mid=mid+Math.imul(al7,bh5)|0;mid=mid+Math.imul(ah7,bl5)|0;hi=hi+Math.imul(ah7,bh5)|0;lo=lo+Math.imul(al6,bl6)|0;mid=mid+Math.imul(al6,bh6)|0;mid=mid+Math.imul(ah6,bl6)|0;hi=hi+Math.imul(ah6,bh6)|0;lo=lo+Math.imul(al5,bl7)|0;mid=mid+Math.imul(al5,bh7)|0;mid=mid+Math.imul(ah5,bl7)|0;hi=hi+Math.imul(ah5,bh7)|0;lo=lo+Math.imul(al4,bl8)|0;mid=mid+Math.imul(al4,bh8)|0;mid=mid+Math.imul(ah4,bl8)|0;hi=hi+Math.imul(ah4,bh8)|0;lo=lo+Math.imul(al3,bl9)|0;mid=mid+Math.imul(al3,bh9)|0;mid=mid+Math.imul(ah3,bl9)|0;hi=hi+Math.imul(ah3,bh9)|0;var w12=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0;w12&=0x3ffffff;/* k = 13 */lo=Math.imul(al9,bl4);mid=Math.imul(al9,bh4);mid=mid+Math.imul(ah9,bl4)|0;hi=Math.imul(ah9,bh4);lo=lo+Math.imul(al8,bl5)|0;mid=mid+Math.imul(al8,bh5)|0;mid=mid+Math.imul(ah8,bl5)|0;hi=hi+Math.imul(ah8,bh5)|0;lo=lo+Math.imul(al7,bl6)|0;mid=mid+Math.imul(al7,bh6)|0;mid=mid+Math.imul(ah7,bl6)|0;hi=hi+Math.imul(ah7,bh6)|0;lo=lo+Math.imul(al6,bl7)|0;mid=mid+Math.imul(al6,bh7)|0;mid=mid+Math.imul(ah6,bl7)|0;hi=hi+Math.imul(ah6,bh7)|0;lo=lo+Math.imul(al5,bl8)|0;mid=mid+Math.imul(al5,bh8)|0;mid=mid+Math.imul(ah5,bl8)|0;hi=hi+Math.imul(ah5,bh8)|0;lo=lo+Math.imul(al4,bl9)|0;mid=mid+Math.imul(al4,bh9)|0;mid=mid+Math.imul(ah4,bl9)|0;hi=hi+Math.imul(ah4,bh9)|0;var w13=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0;w13&=0x3ffffff;/* k = 14 */lo=Math.imul(al9,bl5);mid=Math.imul(al9,bh5);mid=mid+Math.imul(ah9,bl5)|0;hi=Math.imul(ah9,bh5);lo=lo+Math.imul(al8,bl6)|0;mid=mid+Math.imul(al8,bh6)|0;mid=mid+Math.imul(ah8,bl6)|0;hi=hi+Math.imul(ah8,bh6)|0;lo=lo+Math.imul(al7,bl7)|0;mid=mid+Math.imul(al7,bh7)|0;mid=mid+Math.imul(ah7,bl7)|0;hi=hi+Math.imul(ah7,bh7)|0;lo=lo+Math.imul(al6,bl8)|0;mid=mid+Math.imul(al6,bh8)|0;mid=mid+Math.imul(ah6,bl8)|0;hi=hi+Math.imul(ah6,bh8)|0;lo=lo+Math.imul(al5,bl9)|0;mid=mid+Math.imul(al5,bh9)|0;mid=mid+Math.imul(ah5,bl9)|0;hi=hi+Math.imul(ah5,bh9)|0;var w14=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0;w14&=0x3ffffff;/* k = 15 */lo=Math.imul(al9,bl6);mid=Math.imul(al9,bh6);mid=mid+Math.imul(ah9,bl6)|0;hi=Math.imul(ah9,bh6);lo=lo+Math.imul(al8,bl7)|0;mid=mid+Math.imul(al8,bh7)|0;mid=mid+Math.imul(ah8,bl7)|0;hi=hi+Math.imul(ah8,bh7)|0;lo=lo+Math.imul(al7,bl8)|0;mid=mid+Math.imul(al7,bh8)|0;mid=mid+Math.imul(ah7,bl8)|0;hi=hi+Math.imul(ah7,bh8)|0;lo=lo+Math.imul(al6,bl9)|0;mid=mid+Math.imul(al6,bh9)|0;mid=mid+Math.imul(ah6,bl9)|0;hi=hi+Math.imul(ah6,bh9)|0;var w15=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0;w15&=0x3ffffff;/* k = 16 */lo=Math.imul(al9,bl7);mid=Math.imul(al9,bh7);mid=mid+Math.imul(ah9,bl7)|0;hi=Math.imul(ah9,bh7);lo=lo+Math.imul(al8,bl8)|0;mid=mid+Math.imul(al8,bh8)|0;mid=mid+Math.imul(ah8,bl8)|0;hi=hi+Math.imul(ah8,bh8)|0;lo=lo+Math.imul(al7,bl9)|0;mid=mid+Math.imul(al7,bh9)|0;mid=mid+Math.imul(ah7,bl9)|0;hi=hi+Math.imul(ah7,bh9)|0;var w16=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0;w16&=0x3ffffff;/* k = 17 */lo=Math.imul(al9,bl8);mid=Math.imul(al9,bh8);mid=mid+Math.imul(ah9,bl8)|0;hi=Math.imul(ah9,bh8);lo=lo+Math.imul(al8,bl9)|0;mid=mid+Math.imul(al8,bh9)|0;mid=mid+Math.imul(ah8,bl9)|0;hi=hi+Math.imul(ah8,bh9)|0;var w17=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0;w17&=0x3ffffff;/* k = 18 */lo=Math.imul(al9,bl9);mid=Math.imul(al9,bh9);mid=mid+Math.imul(ah9,bl9)|0;hi=Math.imul(ah9,bh9);var w18=(c+lo|0)+((mid&0x1fff)<<13)|0;c=(hi+(mid>>>13)|0)+(w18>>>26)|0;w18&=0x3ffffff;o[0]=w0;o[1]=w1;o[2]=w2;o[3]=w3;o[4]=w4;o[5]=w5;o[6]=w6;o[7]=w7;o[8]=w8;o[9]=w9;o[10]=w10;o[11]=w11;o[12]=w12;o[13]=w13;o[14]=w14;o[15]=w15;o[16]=w16;o[17]=w17;o[18]=w18;if(c!==0){o[19]=c;out.length++;}return out;};// Polyfill comb
if(!Math.imul){comb10MulTo=smallMulTo;}function bigMulTo(self,num,out){out.negative=num.negative^self.negative;out.length=self.length+num.length;var carry=0;var hncarry=0;for(var k=0;k= 0x3ffffff
var ncarry=hncarry;hncarry=0;var rword=carry&0x3ffffff;var maxJ=Math.min(k,num.length-1);for(var j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j;var a=self.words[i]|0;var b=num.words[j]|0;var r=a*b;var lo=r&0x3ffffff;ncarry=ncarry+(r/0x4000000|0)|0;lo=lo+rword|0;rword=lo&0x3ffffff;ncarry=ncarry+(lo>>>26)|0;hncarry+=ncarry>>>26;ncarry&=0x3ffffff;}out.words[k]=rword;carry=ncarry;ncarry=hncarry;}if(carry!==0){out.words[k]=carry;}else{out.length--;}return out.strip();}function jumboMulTo(self,num,out){var fftm=new FFTM();return fftm.mulp(self,num,out);}BN.prototype.mulTo=function mulTo(num,out){var res;var len=this.length+num.length;if(this.length===10&&num.length===10){res=comb10MulTo(this,num,out);}else if(len<63){res=smallMulTo(this,num,out);}else if(len<1024){res=bigMulTo(this,num,out);}else{res=jumboMulTo(this,num,out);}return res;};// Cooley-Tukey algorithm for FFT
// slightly revisited to rely on looping instead of recursion
function FFTM(x,y){this.x=x;this.y=y;}FFTM.prototype.makeRBT=function makeRBT(N){var t=new Array(N);var l=BN.prototype._countBits(N)-1;for(var i=0;i>=1;}return rb;};// Performs "tweedling" phase, therefore 'emulating'
// behaviour of the recursive algorithm
FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>1){i++;}return 1<>>13;rws[2*i+1]=carry&0x1fff;carry=carry>>>13;}// Pad with zeroes
for(i=2*len;i>=26;carry+=w/0x4000000|0;// NOTE: lo is 27bit maximum
carry+=lo>>>26;this.words[i]=lo&0x3ffffff;}if(carry!==0){this.words[i]=carry;this.length++;}return this;};BN.prototype.muln=function muln(num){return this.clone().imuln(num);};// `this` * `this`
BN.prototype.sqr=function sqr(){return this.mul(this);};// `this` * `this` in-place
BN.prototype.isqr=function isqr(){return this.imul(this.clone());};// Math.pow(`this`, `num`)
BN.prototype.pow=function pow(num){var w=toBitArray(num);if(w.length===0)return new BN(1);// Skip leading zeroes
var res=this;for(var i=0;i=0);var r=bits%26;var s=(bits-r)/26;var carryMask=0x3ffffff>>>26-r<<26-r;var i;if(r!==0){var carry=0;for(i=0;i>>26-r;}if(carry){this.words[i]=carry;this.length++;}}if(s!==0){for(i=this.length-1;i>=0;i--){this.words[i+s]=this.words[i];}for(i=0;i=0);var h;if(hint){h=(hint-hint%26)/26;}else{h=0;}var r=bits%26;var s=Math.min((bits-r)/26,this.length);var mask=0x3ffffff^0x3ffffff>>>r<s){this.length-=s;for(i=0;i=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r;carry=word&mask;}// Push carried bits as a mask
if(maskedWords&&carry!==0){maskedWords.words[maskedWords.length++]=carry;}if(this.length===0){this.words[0]=0;this.length=1;}return this.strip();};BN.prototype.ishrn=function ishrn(bits,hint,extended){// TODO(indutny): implement me
assert(this.negative===0);return this.iushrn(bits,hint,extended);};// Shift-left
BN.prototype.shln=function shln(bits){return this.clone().ishln(bits);};BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits);};// Shift-right
BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits);};BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits);};// Test if n bit is set
BN.prototype.testn=function testn(bit){assert(typeof bit==='number'&&bit>=0);var r=bit%26;var s=(bit-r)/26;var q=1<=0);var r=bits%26;var s=(bits-r)/26;assert(this.negative===0,'imaskn works only with positive numbers');if(this.length<=s){return this;}if(r!==0){s++;}this.length=Math.min(s,this.length);if(r!==0){var mask=0x3ffffff^0x3ffffff>>>r<=0x4000000;i++){this.words[i]-=0x4000000;if(i===this.length-1){this.words[i+1]=1;}else{this.words[i+1]++;}}this.length=Math.max(this.length,i+1);return this;};// Subtract plain number `num` from `this`
BN.prototype.isubn=function isubn(num){assert(typeof num==='number');assert(num<0x4000000);if(num<0)return this.iaddn(-num);if(this.negative!==0){this.negative=0;this.iaddn(num);this.negative=1;return this;}this.words[0]-=num;if(this.length===1&&this.words[0]<0){this.words[0]=-this.words[0];this.negative=1;}else{// Carry
for(var i=0;i>26)-(right/0x4000000|0);this.words[i+shift]=w&0x3ffffff;}for(;i>26;this.words[i+shift]=w&0x3ffffff;}if(carry===0)return this.strip();// Subtraction overflow
assert(carry===-1);carry=0;for(i=0;i>26;this.words[i]=w&0x3ffffff;}this.negative=1;return this.strip();};BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length;var a=this.clone();var b=num;// Normalize
var bhi=b.words[b.length-1]|0;var bhiBits=this._countBits(bhi);shift=26-bhiBits;if(shift!==0){b=b.ushln(shift);a.iushln(shift);bhi=b.words[b.length-1]|0;}// Initialize quotient
var m=a.length-b.length;var q;if(mode!=='mod'){q=new BN(null);q.length=m+1;q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=(a.words[b.length+j]|0)*0x4000000+(a.words[b.length+j-1]|0);// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj=Math.min(qj/bhi|0,0x3ffffff);a._ishlnsubmul(b,qj,j);while(a.negative!==0){qj--;a.negative=0;a._ishlnsubmul(b,1,j);if(!a.isZero()){a.negative^=1;}}if(q){q.words[j]=qj;}}if(q){q.strip();}a.strip();// Denormalize
if(mode!=='div'&&shift!==0){a.iushrn(shift);}return{div:q||null,mod:a};};// NOTE: 1) `mode` can be set to `mod` to request mod only,
// to `div` to request div only, or be absent to
// request both div & mod
// 2) `positive` is true if unsigned mod is requested
BN.prototype.divmod=function divmod(num,mode,positive){assert(!num.isZero());if(this.isZero()){return{div:new BN(0),mod:new BN(0)};}var div,mod,res;if(this.negative!==0&&num.negative===0){res=this.neg().divmod(num,mode);if(mode!=='mod'){div=res.div.neg();}if(mode!=='div'){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.iadd(num);}}return{div:div,mod:mod};}if(this.negative===0&&num.negative!==0){res=this.divmod(num.neg(),mode);if(mode!=='mod'){div=res.div.neg();}return{div:div,mod:res.mod};}if((this.negative&num.negative)!==0){res=this.neg().divmod(num.neg(),mode);if(mode!=='div'){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.isub(num);}}return{div:res.div,mod:mod};}// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if(num.length>this.length||this.cmp(num)<0){return{div:new BN(0),mod:this};}// Very short reduction
if(num.length===1){if(mode==='div'){return{div:this.divn(num.words[0]),mod:null};}if(mode==='mod'){return{div:null,mod:new BN(this.modn(num.words[0]))};}return{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))};}return this._wordDiv(num,mode);};// Find `this` / `num`
BN.prototype.div=function div(num){return this.divmod(num,'div',false).div;};// Find `this` % `num`
BN.prototype.mod=function mod(num){return this.divmod(num,'mod',false).mod;};BN.prototype.umod=function umod(num){return this.divmod(num,'mod',true).mod;};// Find Round(`this` / `num`)
BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);// Fast case - exact division
if(dm.mod.isZero())return dm.div;var mod=dm.div.negative!==0?dm.mod.isub(num):dm.mod;var half=num.ushrn(1);var r2=num.andln(1);var cmp=mod.cmp(half);// Round down
if(cmp<0||r2===1&&cmp===0)return dm.div;// Round up
return dm.div.negative!==0?dm.div.isubn(1):dm.div.iaddn(1);};BN.prototype.modn=function modn(num){assert(num<=0x3ffffff);var p=(1<<26)%num;var acc=0;for(var i=this.length-1;i>=0;i--){acc=(p*acc+(this.words[i]|0))%num;}return acc;};// In-place division by number
BN.prototype.idivn=function idivn(num){assert(num<=0x3ffffff);var carry=0;for(var i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*0x4000000;this.words[i]=w/num|0;carry=w%num;}return this.strip();};BN.prototype.divn=function divn(num){return this.clone().idivn(num);};BN.prototype.egcd=function egcd(p){assert(p.negative===0);assert(!p.isZero());var x=this;var y=p.clone();if(x.negative!==0){x=x.umod(p);}else{x=x.clone();}// A * x + B * y = x
var A=new BN(1);var B=new BN(0);// C * x + D * y = y
var C=new BN(0);var D=new BN(1);var g=0;while(x.isEven()&&y.isEven()){x.iushrn(1);y.iushrn(1);++g;}var yp=y.clone();var xp=x.clone();while(!x.isZero()){for(var i=0,im=1;(x.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){x.iushrn(i);while(i-->0){if(A.isOdd()||B.isOdd()){A.iadd(yp);B.isub(xp);}A.iushrn(1);B.iushrn(1);}}for(var j=0,jm=1;(y.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){y.iushrn(j);while(j-->0){if(C.isOdd()||D.isOdd()){C.iadd(yp);D.isub(xp);}C.iushrn(1);D.iushrn(1);}}if(x.cmp(y)>=0){x.isub(y);A.isub(C);B.isub(D);}else{y.isub(x);C.isub(A);D.isub(B);}}return{a:C,b:D,gcd:y.iushln(g)};};// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp=function _invmp(p){assert(p.negative===0);assert(!p.isZero());var a=this;var b=p.clone();if(a.negative!==0){a=a.umod(p);}else{a=a.clone();}var x1=new BN(1);var x2=new BN(0);var delta=b.clone();while(a.cmpn(1)>0&&b.cmpn(1)>0){for(var i=0,im=1;(a.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){a.iushrn(i);while(i-->0){if(x1.isOdd()){x1.iadd(delta);}x1.iushrn(1);}}for(var j=0,jm=1;(b.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){b.iushrn(j);while(j-->0){if(x2.isOdd()){x2.iadd(delta);}x2.iushrn(1);}}if(a.cmp(b)>=0){a.isub(b);x1.isub(x2);}else{b.isub(a);x2.isub(x1);}}var res;if(a.cmpn(1)===0){res=x1;}else{res=x2;}if(res.cmpn(0)<0){res.iadd(p);}return res;};BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone();var b=num.clone();a.negative=0;b.negative=0;// Remove common factor of two
for(var shift=0;a.isEven()&&b.isEven();shift++){a.iushrn(1);b.iushrn(1);}do{while(a.isEven()){a.iushrn(1);}while(b.isEven()){b.iushrn(1);}var r=a.cmp(b);if(r<0){// Swap `a` and `b` to make `a` always bigger than `b`
var t=a;a=b;b=t;}else if(r===0||b.cmpn(1)===0){break;}a.isub(b);}while(true);return b.iushln(shift);};// Invert number in the field F(num)
BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num);};BN.prototype.isEven=function isEven(){return(this.words[0]&1)===0;};BN.prototype.isOdd=function isOdd(){return(this.words[0]&1)===1;};// And first word and num
BN.prototype.andln=function andln(num){return this.words[0]#};// Increment at the bit position in-line
BN.prototype.bincn=function bincn(bit){assert(typeof bit==='number');var r=bit%26;var s=(bit-r)/26;var q=1<>>26;w&=0x3ffffff;this.words[i]=w;}if(carry!==0){this.words[i]=carry;this.length++;}return this;};BN.prototype.isZero=function isZero(){return this.length===1&&this.words[0]===0;};BN.prototype.cmpn=function cmpn(num){var negative=num<0;if(this.negative!==0&&!negative)return-1;if(this.negative===0&&negative)return 1;this.strip();var res;if(this.length>1){res=1;}else{if(negative){num=-num;}assert(num<=0x3ffffff,'Number is too big');var w=this.words[0]|0;res=w===num?0:w `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp=function cmp(num){if(this.negative!==0&&num.negative===0)return-1;if(this.negative===0&&num.negative!==0)return 1;var res=this.ucmp(num);if(this.negative!==0)return-res|0;return res;};// Unsigned comparison
BN.prototype.ucmp=function ucmp(num){// At this point both numbers have the same sign
if(this.length>num.length)return 1;if(this.length=0;i--){var a=this.words[i]|0;var b=num.words[i]|0;if(a===b)continue;if(ab){res=1;}break;}return res;};BN.prototype.gtn=function gtn(num){return this.cmpn(num)===1;};BN.prototype.gt=function gt(num){return this.cmp(num)===1;};BN.prototype.gten=function gten(num){return this.cmpn(num)>=0;};BN.prototype.gte=function gte(num){return this.cmp(num)>=0;};BN.prototype.ltn=function ltn(num){return this.cmpn(num)===-1;};BN.prototype.lt=function lt(num){return this.cmp(num)===-1;};BN.prototype.lten=function lten(num){return this.cmpn(num)<=0;};BN.prototype.lte=function lte(num){return this.cmp(num)<=0;};BN.prototype.eqn=function eqn(num){return this.cmpn(num)===0;};BN.prototype.eq=function eq(num){return this.cmp(num)===0;};//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red=function red(num){return new Red(num);};BN.prototype.toRed=function toRed(ctx){assert(!this.red,'Already a number in reduction context');assert(this.negative===0,'red works only with positives');return ctx.convertTo(this)._forceRed(ctx);};BN.prototype.fromRed=function fromRed(){assert(this.red,'fromRed works only with numbers in reduction context');return this.red.convertFrom(this);};BN.prototype._forceRed=function _forceRed(ctx){this.red=ctx;return this;};BN.prototype.forceRed=function forceRed(ctx){assert(!this.red,'Already a number in reduction context');return this._forceRed(ctx);};BN.prototype.redAdd=function redAdd(num){assert(this.red,'redAdd works only with red numbers');return this.red.add(this,num);};BN.prototype.redIAdd=function redIAdd(num){assert(this.red,'redIAdd works only with red numbers');return this.red.iadd(this,num);};BN.prototype.redSub=function redSub(num){assert(this.red,'redSub works only with red numbers');return this.red.sub(this,num);};BN.prototype.redISub=function redISub(num){assert(this.red,'redISub works only with red numbers');return this.red.isub(this,num);};BN.prototype.redShl=function redShl(num){assert(this.red,'redShl works only with red numbers');return this.red.shl(this,num);};BN.prototype.redMul=function redMul(num){assert(this.red,'redMul works only with red numbers');this.red._verify2(this,num);return this.red.mul(this,num);};BN.prototype.redIMul=function redIMul(num){assert(this.red,'redMul works only with red numbers');this.red._verify2(this,num);return this.red.imul(this,num);};BN.prototype.redSqr=function redSqr(){assert(this.red,'redSqr works only with red numbers');this.red._verify1(this);return this.red.sqr(this);};BN.prototype.redISqr=function redISqr(){assert(this.red,'redISqr works only with red numbers');this.red._verify1(this);return this.red.isqr(this);};// Square root over p
BN.prototype.redSqrt=function redSqrt(){assert(this.red,'redSqrt works only with red numbers');this.red._verify1(this);return this.red.sqrt(this);};BN.prototype.redInvm=function redInvm(){assert(this.red,'redInvm works only with red numbers');this.red._verify1(this);return this.red.invm(this);};// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg=function redNeg(){assert(this.red,'redNeg works only with red numbers');this.red._verify1(this);return this.red.neg(this);};BN.prototype.redPow=function redPow(num){assert(this.red&&!num.red,'redPow(normalNum)');this.red._verify1(this);return this.red.pow(this,num);};// Prime numbers with efficient reduction
var primes={k256:null,p224:null,p192:null,p25519:null};// Pseudo-Mersenne prime
function MPrime(name,p){// P = 2 ^ N - K
this.name=name;this.p=new BN(p,16);this.n=this.p.bitLength();this.k=new BN(1).iushln(this.n).isub(this.p);this.tmp=this._tmp();}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);tmp.words=new Array(Math.ceil(this.n/13));return tmp;};MPrime.prototype.ireduce=function ireduce(num){// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r=num;var rlen;do{this.split(r,this.tmp);r=this.imulK(r);r=r.iadd(this.tmp);rlen=r.bitLength();}while(rlen>this.n);var cmp=rlen0){r.isub(this.p);}else{if(r.strip!==undefined){// r is BN v4 instance
r.strip();}else{// r is BN v5 instance
r._strip();}}return r;};MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out);};MPrime.prototype.imulK=function imulK(num){return num.imul(this.k);};function K256(){MPrime.call(this,'k256','ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');}inherits(K256,MPrime);K256.prototype.split=function split(input,output){// 256 = 9 * 26 + 22
var mask=0x3fffff;var outLen=Math.min(input.length,9);for(var i=0;i>>22;prev=next;}prev>>>=22;input.words[i-10]=prev;if(prev===0&&input.length>10){input.length-=10;}else{input.length-=9;}};K256.prototype.imulK=function imulK(num){// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length]=0;num.words[num.length+1]=0;num.length+=2;// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var lo=0;for(var i=0;i>>=26;num.words[i]=lo;carry=hi;}if(carry!==0){num.words[num.length++]=carry;}return num;};// Exported mostly for testing purposes, use plain name instead
BN._prime=function prime(name){// Cached version of prime
if(primes[name])return primes[name];var prime;if(name==='k256'){prime=new K256();}else if(name==='p224'){prime=new P224();}else if(name==='p192'){prime=new P192();}else if(name==='p25519'){prime=new P25519();}else{throw new Error('Unknown prime '+name);}primes[name]=prime;return prime;};//
// Base reduction engine
//
function Red(m){if(typeof m==='string'){var prime=BN._prime(m);this.m=prime.p;this.prime=prime;}else{assert(m.gtn(1),'modulus must be greater than 1');this.m=m;this.prime=null;}}Red.prototype._verify1=function _verify1(a){assert(a.negative===0,'red works only with positives');assert(a.red,'red works only with red numbers');};Red.prototype._verify2=function _verify2(a,b){assert((a.negative|b.negative)===0,'red works only with positives');assert(a.red&&a.red===b.red,'red works only with red numbers');};Red.prototype.imod=function imod(a){if(this.prime)return this.prime.ireduce(a)._forceRed(this);return a.umod(this.m)._forceRed(this);};Red.prototype.neg=function neg(a){if(a.isZero()){return a.clone();}return this.m.sub(a)._forceRed(this);};Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);if(res.cmp(this.m)>=0){res.isub(this.m);}return res._forceRed(this);};Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);if(res.cmp(this.m)>=0){res.isub(this.m);}return res;};Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);if(res.cmpn(0)<0){res.iadd(this.m);}return res._forceRed(this);};Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);if(res.cmpn(0)<0){res.iadd(this.m);}return res;};Red.prototype.shl=function shl(a,num){this._verify1(a);return this.imod(a.ushln(num));};Red.prototype.imul=function imul(a,b){this._verify2(a,b);return this.imod(a.imul(b));};Red.prototype.mul=function mul(a,b){this._verify2(a,b);return this.imod(a.mul(b));};Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone());};Red.prototype.sqr=function sqr(a){return this.mul(a,a);};Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);assert(mod3%2===1);// Fast case
if(mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow);}// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q=this.m.subn(1);var s=0;while(!q.isZero()&&q.andln(1)===0){s++;q.iushrn(1);}assert(!q.isZero());var one=new BN(1).toRed(this);var nOne=one.redNeg();// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow=this.m.subn(1).iushrn(1);var z=this.m.bitLength();z=new BN(2*z*z).toRed(this);while(this.pow(z,lpow).cmp(nOne)!==0){z.redIAdd(nOne);}var c=this.pow(z,q);var r=this.pow(a,q.addn(1).iushrn(1));var t=this.pow(a,q);var m=s;while(t.cmp(one)!==0){var tmp=t;for(var i=0;tmp.cmp(one)!==0;i++){tmp=tmp.redSqr();}assert(i=0;i--){var word=num.words[i];for(var j=start-1;j>=0;j--){var bit=word>>j&1;if(res!==wnd[0]){res=this.sqr(res);}if(bit===0&¤t===0){currentLen=0;continue;}current<<=1;current|=bit;currentLen++;if(currentLen!==windowSize&&(i!==0||j!==0))continue;res=this.mul(res,wnd[current]);currentLen=0;current=0;}start=26;}return res;};Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r;};Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();res.red=null;return res;};//
// Montgomery method engine
//
BN.mont=function mont(num){return new Mont(num);};function Mont(m){Red.call(this,m);this.shift=this.m.bitLength();if(this.shift%26!==0){this.shift+=26-this.shift%26;}this.r=new BN(1).iushln(this.shift);this.r2=this.imod(this.r.sqr());this.rinv=this.r._invmp(this.m);this.minv=this.rinv.mul(this.r).isubn(1).div(this.m);this.minv=this.minv.umod(this.r);this.minv=this.r.sub(this.minv);}inherits(Mont,Red);Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift));};Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));r.red=null;return r;};Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero()){a.words[0]=0;a.length=1;return a;}var t=a.imul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m);}else if(u.cmpn(0)<0){res=u.iadd(this.m);}return res._forceRed(this);};Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m);}else if(u.cmpn(0)<0){res=u.iadd(this.m);}return res._forceRed(this);};Mont.prototype.invm=function invm(a){// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this);};})( false||module,this);/***/},/***/6204:/***/function(module){"use strict";module.exports=boundary;function boundary(cells){var i,j,k;var n=cells.length;var sz=0;for(i=0;i>>1;if(d<=0){return;}var retval;//Convert red boxes
var redList=pool.mallocDouble(2*d*n);var redIds=pool.mallocInt32(n);n=convertBoxes(red,d,redList,redIds);if(n>0){if(d===1&&full){//Special case: 1d complete
sweep.init(n);retval=sweep.sweepComplete(d,visit,0,n,redList,redIds,0,n,redList,redIds);}else{//Convert blue boxes
var blueList=pool.mallocDouble(2*d*m);var blueIds=pool.mallocInt32(m);m=convertBoxes(blue,d,blueList,blueIds);if(m>0){sweep.init(n+m);if(d===1){//Special case: 1d bipartite
retval=sweep.sweepBipartite(d,visit,0,n,redList,redIds,0,m,blueList,blueIds);}else{//General case: d>1
retval=boxIntersectIter(d,visit,full,n,redList,redIds,m,blueList,blueIds);}pool.free(blueList);pool.free(blueIds);}}pool.free(redList);pool.free(redIds);}return retval;}var RESULT;function appendItem(i,j){RESULT.push([i,j]);}function intersectFullArray(x){RESULT=[];boxIntersect(x,x,appendItem,true);return RESULT;}function intersectBipartiteArray(x,y){RESULT=[];boxIntersect(x,y,appendItem,false);return RESULT;}//User-friendly wrapper, handle full input and no-visitor cases
function boxIntersectWrapper(arg0,arg1,arg2){switch(arguments.length){case 1:return intersectFullArray(arg0);case 2:if(typeof arg1==='function'){return boxIntersect(arg0,arg0,arg1,true);}else{return intersectBipartiteArray(arg0,arg1);}case 3:return boxIntersect(arg0,arg1,arg2,false);default:throw new Error('box-intersect: Invalid arguments');}}/***/},/***/2455:/***/function(__unused_webpack_module,exports){"use strict";function full(){function bruteForceRedFull(d,ax,vv,rs,re,rb,ri,bs,be,bb,bi){var es=2*d;for(var i=rs,rp=es*rs;ibe-bs){return bruteForceRedFull(d,ax,vv,rs,re,rb,ri,bs,be,bb,bi);}else{return bruteForceBlueFull(d,ax,vv,rs,re,rb,ri,bs,be,bb,bi);}}return bruteForceFull;}function partial(){function bruteForceRedFlip(d,ax,vv,rs,re,rb,ri,bs,be,bb,bi){var es=2*d;for(var i=rs,rp=es*rs;ibe-bs){if(fp){return bruteForceRedFlip(d,ax,vv,rs,re,rb,ri,bs,be,bb,bi);}else{return bruteForceRed(d,ax,vv,rs,re,rb,ri,bs,be,bb,bi);}}else{if(fp){return bruteForceBlueFlip(d,ax,vv,rs,re,rb,ri,bs,be,bb,bi);}else{return bruteForceBlue(d,ax,vv,rs,re,rb,ri,bs,be,bb,bi);}}}return bruteForcePartial;}function bruteForcePlanner(isFull){return isFull?full():partial();}exports.partial=bruteForcePlanner(false);exports.full=bruteForcePlanner(true);/***/},/***/7150:/***/function(module,__unused_webpack_exports,__nested_webpack_require_141648__){"use strict";module.exports=boxIntersectIter;var pool=__nested_webpack_require_141648__(1888);var bits=__nested_webpack_require_141648__(8828);var bruteForce=__nested_webpack_require_141648__(2455);var bruteForcePartial=bruteForce.partial;var bruteForceFull=bruteForce.full;var sweep=__nested_webpack_require_141648__(855);var findMedian=__nested_webpack_require_141648__(3545);var genPartition=__nested_webpack_require_141648__(8105);//Twiddle parameters
var BRUTE_FORCE_CUTOFF=128;//Cut off for brute force search
var SCAN_CUTOFF=1<<22;//Cut off for two way scan
var SCAN_COMPLETE_CUTOFF=1<<22;//Partition functions
var partitionInteriorContainsInterval=genPartition('!(lo>=p0)&&!(p1>=hi)');var partitionStartEqual=genPartition('lo===p0');var partitionStartLessThan=genPartition('lo0){top-=1;var iptr=top*IFRAME_SIZE;var axis=BOX_ISTACK[iptr];var redStart=BOX_ISTACK[iptr+1];var redEnd=BOX_ISTACK[iptr+2];var blueStart=BOX_ISTACK[iptr+3];var blueEnd=BOX_ISTACK[iptr+4];var state=BOX_ISTACK[iptr+5];var dptr=top*DFRAME_SIZE;var lo=BOX_DSTACK[dptr];var hi=BOX_DSTACK[dptr+1];//Unpack state info
var flip=state&1;var full=!!(state&16);//Unpack indices
var red=xBoxes;var redIndex=xIndex;var blue=yBoxes;var blueIndex=yIndex;if(flip){red=yBoxes;redIndex=yIndex;blue=xBoxes;blueIndex=xIndex;}if(state&2){redEnd=partitionStartLessThan(d,axis,redStart,redEnd,red,redIndex,hi);if(redStart>=redEnd){continue;}}if(state&4){redStart=partitionEndLessThanEqual(d,axis,redStart,redEnd,red,redIndex,lo);if(redStart>=redEnd){continue;}}var redCount=redEnd-redStart;var blueCount=blueEnd-blueStart;if(full){if(d*redCount*(redCount+blueCount) mid point
//
var blue0=findMedian(d,axis,blueStart,blueEnd,blue,blueIndex);var mid=blue[elemSize*blue0+axis];var blue1=partitionStartEqual(d,axis,blue0,blueEnd,blue,blueIndex,mid);//Right case
if(blue1start&&boxes[ptr+axis]>x;--j,ptr-=elemSize){//Swap
var aPtr=ptr;var bPtr=ptr+elemSize;for(var k=0;k>>1;var elemSize=2*d;var pivot=mid;var value=boxes[elemSize*mid+axis];while(lo=value1){pivot=pivot1;value=value1;}else if(value0>=value2){pivot=pivot0;value=value0;}else{pivot=pivot2;value=value2;}}else{if(value1>=value2){pivot=pivot1;value=value1;}else if(value2>=value0){pivot=pivot0;value=value0;}else{pivot=pivot2;value=value2;}}//Swap pivot to end of array
var aPtr=elemSize*(hi-1);var bPtr=elemSize*pivot;for(var i=0;i=p0)&&!(p1>=hi)':lo_lessThan_p0_and_p1_lessThan_hi};function genPartition(predicate){return P2F[predicate];}// lo===p0
function lo_equal_p0(a,b,c,d,e,f,p0){for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var lo=e[k+n];if(lo===p0)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t;}var u=f[p];f[p]=f[m],f[m++]=u;}}return m;}// lop;++p,k+=j){var lo=e[k+n];if(los;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t;}var u=f[p];f[p]=f[m],f[m++]=u;}}return m;}// lo<=p0
function lo_lessOrEqual_p0(a,b,c,d,e,f,p0){for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var hi=e[k+o];if(hi<=p0)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t;}var u=f[p];f[p]=f[m],f[m++]=u;}}return m;}// hi<=p0
function hi_lessOrEqual_p0(a,b,c,d,e,f,p0){for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var hi=e[k+o];if(hi<=p0)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t;}var u=f[p];f[p]=f[m],f[m++]=u;}}return m;}// lo<=p0&&p0<=hi
function lo_lassOrEqual_p0_and_p0_lessOrEqual_hi(a,b,c,d,e,f,p0){for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var lo=e[k+n],hi=e[k+o];if(lo<=p0&&p0<=hi)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t;}var u=f[p];f[p]=f[m],f[m++]=u;}}return m;}// lop;++p,k+=j){var lo=e[k+n],hi=e[k+o];if(los;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t;}var u=f[p];f[p]=f[m],f[m++]=u;}}return m;}// !(lo>=p0)&&!(p1>=hi)
function lo_lessThan_p0_and_p1_lessThan_hi(a,b,c,d,e,f,p0,p1){for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var lo=e[k+n],hi=e[k+o];if(!(lo>=p0)&&!(p1>=hi))if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t;}var u=f[p];f[p]=f[m],f[m++]=u;}}return m;}/***/},/***/1811:/***/function(module){"use strict";//This code is extracted from ndarray-sort
//It is inlined here as a temporary workaround
module.exports=wrapper;var INSERT_SORT_CUTOFF=32;function wrapper(data,n0){if(n0<=4*INSERT_SORT_CUTOFF){insertionSort(0,n0-1,data);}else{quickSort(0,n0-1,data);}}function insertionSort(left,right,data){var ptr=2*(left+1);for(var i=left+1;i<=right;++i){var a=data[ptr++];var b=data[ptr++];var j=i;var jptr=ptr-2;while(j-->left){var x=data[jptr-2];var y=data[jptr-1];if(xdata[j+1];}return true;}function comparePivot(i,y,b,data){i*=2;var x=data[i];if(x>1,index2=index3-sixth,index4=index3+sixth,el1=index1,el2=index2,el3=index3,el4=index4,el5=index5,less=left+1,great=right-1,tmp=0;if(compare(el1,el2,data)){tmp=el1;el1=el2;el2=tmp;}if(compare(el4,el5,data)){tmp=el4;el4=el5;el5=tmp;}if(compare(el1,el3,data)){tmp=el1;el1=el3;el3=tmp;}if(compare(el2,el3,data)){tmp=el2;el2=el3;el3=tmp;}if(compare(el1,el4,data)){tmp=el1;el1=el4;el4=tmp;}if(compare(el3,el4,data)){tmp=el3;el3=el4;el4=tmp;}if(compare(el2,el5,data)){tmp=el2;el2=el5;el5=tmp;}if(compare(el2,el3,data)){tmp=el2;el2=el3;el3=tmp;}if(compare(el4,el5,data)){tmp=el4;el4=el5;el5=tmp;}var pivot1X=data[2*el2];var pivot1Y=data[2*el2+1];var pivot2X=data[2*el4];var pivot2Y=data[2*el4+1];var ptr0=2*el1;var ptr2=2*el3;var ptr4=2*el5;var ptr5=2*index1;var ptr6=2*index3;var ptr7=2*index5;for(var i1=0;i1<2;++i1){var x=data[ptr0+i1];var y=data[ptr2+i1];var z=data[ptr4+i1];data[ptr5+i1]=x;data[ptr6+i1]=y;data[ptr7+i1]=z;}move(index2,left,data);move(index4,right,data);for(var k=less;k<=great;++k){if(comparePivot(k,pivot1X,pivot1Y,data)){if(k!==less){swap(k,less,data);}++less;}else{if(!comparePivot(k,pivot2X,pivot2Y,data)){while(true){if(!comparePivot(great,pivot2X,pivot2Y,data)){if(--greatright
var n=ptr>>>1;isort(SWEEP_EVENTS,n);var redActive=0;var blueActive=0;for(var i=0;i=BLUE_FLAG){//blue destroy event
e=e-BLUE_FLAG|0;sqPop(BLUE_SWEEP_QUEUE,BLUE_SWEEP_INDEX,blueActive--,e);}else if(e>=0){//red destroy event
sqPop(RED_SWEEP_QUEUE,RED_SWEEP_INDEX,redActive--,e);}else if(e<=-BLUE_FLAG){//blue create event
e=-e-BLUE_FLAG|0;for(var j=0;jright
var n=ptr>>>1;isort(SWEEP_EVENTS,n);var redActive=0;var blueActive=0;var commonActive=0;for(var i=0;i>1===SWEEP_EVENTS[2*i+3]>>1){color=2;i+=1;}if(e<0){//Create event
var id=-(e>>1)-1;//Intersect with common
for(var j=0;j>1)-1;if(color===0){//Red
sqPop(RED_SWEEP_QUEUE,RED_SWEEP_INDEX,redActive--,id);}else if(color===1){//Blue
sqPop(BLUE_SWEEP_QUEUE,BLUE_SWEEP_INDEX,blueActive--,id);}else if(color===2){//Both
sqPop(COMMON_SWEEP_QUEUE,COMMON_SWEEP_INDEX,commonActive--,id);}}}}//Sweep and prune/scanline algorithm:
// Scan along axis, detect intersections
// Brute force all boxes along axis
function scanBipartite(d,axis,visit,flip,redStart,redEnd,red,redIndex,blueStart,blueEnd,blue,blueIndex){var ptr=0;var elemSize=2*d;var istart=axis;var iend=axis+d;var redShift=1;var blueShift=1;if(flip){blueShift=BLUE_FLAG;}else{redShift=BLUE_FLAG;}for(var i=redStart;iright
var n=ptr>>>1;isort(SWEEP_EVENTS,n);var redActive=0;for(var i=0;i=BLUE_FLAG){isRed=!flip;idx-=BLUE_FLAG;}else{isRed=!!flip;idx-=1;}if(isRed){sqPush(RED_SWEEP_QUEUE,RED_SWEEP_INDEX,redActive++,idx);}else{var blueId=blueIndex[idx];var bluePtr=elemSize*idx;var b0=blue[bluePtr+axis+1];var b1=blue[bluePtr+axis+1+d];red_loop:for(var j=0;jright
var n=ptr>>>1;isort(SWEEP_EVENTS,n);var redActive=0;for(var i=0;i=BLUE_FLAG){RED_SWEEP_QUEUE[redActive++]=idx-BLUE_FLAG;}else{idx-=1;var blueId=blueIndex[idx];var bluePtr=elemSize*idx;var b0=blue[bluePtr+axis+1];var b1=blue[bluePtr+axis+1+d];red_loop:for(var j=0;j=0;--j){if(RED_SWEEP_QUEUE[j]===idx){for(var k=j+1;k0){var b=stack.pop();var a=stack.pop();//Find opposite pairs
var x=-1,y=-1;var star=stars[a];for(var i=1;i=0){continue;}//Flip the edge
triangulation.flip(a,b);//Test flipping neighboring edges
testFlip(points,triangulation,stack,x,a,y);testFlip(points,triangulation,stack,a,y,x);testFlip(points,triangulation,stack,y,b,x);testFlip(points,triangulation,stack,b,x,y);}}/***/},/***/5023:/***/function(module,__unused_webpack_exports,__nested_webpack_require_170291__){"use strict";var bsearch=__nested_webpack_require_170291__(2478);module.exports=classifyFaces;function FaceIndex(cells,neighbor,constraint,flags,active,next,boundary){this.cells=cells;this.neighbor=neighbor;this.flags=flags;this.constraint=constraint;this.active=active;this.next=next;this.boundary=boundary;}var proto=FaceIndex.prototype;function compareCell(a,b){return a[0]-b[0]||a[1]-b[1]||a[2]-b[2];}proto.locate=function(){var key=[0,0,0];return function(a,b,c){var x=a,y=b,z=c;if(b0||next.length>0){while(active.length>0){var t=active.pop();if(flags[t]===-side){continue;}flags[t]=side;var c=cells[t];for(var j=0;j<3;++j){var f=neighbor[3*t+j];if(f>=0&&flags[f]===0){if(constraint[3*t+j]){next.push(f);}else{active.push(f);flags[f]=side;}}}}//Swap arrays and loop
var tmp=next;next=active;active=tmp;next.length=0;side=-side;}var result=filterCells(cells,flags,target);if(infinity){return result.concat(index.boundary);}return result;}/***/},/***/8902:/***/function(module,__unused_webpack_exports,__nested_webpack_require_172942__){"use strict";var bsearch=__nested_webpack_require_172942__(2478);var orient=__nested_webpack_require_172942__(3250)[3];var EVENT_POINT=0;var EVENT_END=1;var EVENT_START=2;module.exports=monotoneTriangulate;//A partial convex hull fragment, made of two unimonotone polygons
function PartialHull(a,b,idx,lowerIds,upperIds){this.a=a;this.b=b;this.idx=idx;this.lowerIds=lowerIds;this.upperIds=upperIds;}//An event in the sweep line procedure
function Event(a,b,type,idx){this.a=a;this.b=b;this.type=type;this.idx=idx;}//This is used to compare events for the sweep line procedure
// Points are:
// 1. sorted lexicographically
// 2. sorted by type (point < end < start)
// 3. segments sorted by winding order
// 4. sorted by index
function compareEvent(a,b){var d=a.a[0]-b.a[0]||a.a[1]-b.a[1]||a.type-b.type;if(d){return d;}if(a.type!==EVENT_POINT){d=orient(a.a,a.b,b.b);if(d){return d;}}return a.idx-b.idx;}function testPoint(hull,p){return orient(hull.a,hull.b,p);}function addPoint(cells,hulls,points,p,idx){var lo=bsearch.lt(hulls,p,testPoint);var hi=bsearch.gt(hulls,p,testPoint);for(var i=lo;i1&&orient(points[lowerIds[m-2]],points[lowerIds[m-1]],p)>0){cells.push([lowerIds[m-1],lowerIds[m-2],idx]);m-=1;}lowerIds.length=m;lowerIds.push(idx);//Insert p into upper hull
var upperIds=hull.upperIds;var m=upperIds.length;while(m>1&&orient(points[upperIds[m-2]],points[upperIds[m-1]],p)<0){cells.push([upperIds[m-2],upperIds[m-1],idx]);m-=1;}upperIds.length=m;upperIds.push(idx);}}function findSplit(hull,edge){var d;if(hull.a[0]b[0]){events.push(new Event(b,a,EVENT_START,i),new Event(a,b,EVENT_END,i));}}//Sort events
events.sort(compareEvent);//Initialize hull
var minX=events[0].a[0]-(1+Math.abs(events[0].a[0]))*Math.pow(2,-52);var hull=[new PartialHull([minX,1],[minX,0],-1,[],[],[],[])];//Process events in order
var cells=[];for(var i=0,numEvents=events.length;i=0;};}();proto.removeTriangle=function(i,j,k){var stars=this.stars;removePair(stars[i],j,k);removePair(stars[j],k,i);removePair(stars[k],i,j);};proto.addTriangle=function(i,j,k){var stars=this.stars;stars[i].push(j,k);stars[j].push(k,i);stars[k].push(i,j);};proto.opposite=function(j,i){var list=this.stars[i];for(var k=1,n=list.length;k=0;--i){var junction=junctions[i];e=junction[0];var edge=edges[e];var s=edge[0];var t=edge[1];// Check if edge is not lexicographically sorted
var a=floatPoints[s];var b=floatPoints[t];if((a[0]-b[0]||a[1]-b[1])<0){var tmp=s;s=t;t=tmp;}// Split leading edge
edge[0]=s;var last=edge[1]=junction[1];// If we are grouping edges by color, remember to track data
var color;if(useColor){color=edge[2];}// Split other edges
while(i>0&&junctions[i-1][0]===e){var junction=junctions[--i];var next=junction[1];if(useColor){edges.push([last,next,color]);}else{edges.push([last,next]);}last=next;}// Add final edge
if(useColor){edges.push([last,t,color]);}else{edges.push([last,t]);}}// Return constructed rational points
return ratPoints;}// Merge overlapping points
function dedupPoints(floatPoints,ratPoints,floatBounds){var numPoints=ratPoints.length;var uf=new UnionFind(numPoints);// Compute rational bounds
var bounds=[];for(var i=0;ib[2]){return 1;}return 0;}// Remove duplicate edge labels
function dedupEdges(edges,labels,useColor){if(edges.length===0){return;}if(labels){for(var i=0;i0||tjunctions.length>0;}// More iterations necessary
return true;}// Main loop, runs PSLG clean up until completion
function cleanPSLG(points,edges,colors){// If using colors, augment edges with color data
var prevEdges;if(colors){prevEdges=edges;var augEdges=new Array(edges.length);for(var i=0;inshades+1){throw new Error(colormap+' map requires nshades to be at least size '+cmap.length);}if(!Array.isArray(spec.alpha)){if(typeof spec.alpha==='number'){alpha=[spec.alpha,spec.alpha];}else{alpha=[1,1];}}else if(spec.alpha.length!==2){alpha=[1,1];}else{alpha=spec.alpha.slice();}// map index points from 0..1 to 0..n-1
indicies=cmap.map(function(c){return Math.round(c.index*nshades);});// Add alpha channel to the map
alpha[0]=Math.min(Math.max(alpha[0],0),1);alpha[1]=Math.min(Math.max(alpha[1],0),1);var steps=cmap.map(function(c,i){var index=cmap[i].index;var rgba=cmap[i].rgb.slice();// if user supplies their own map use it
if(rgba.length===4&&rgba[3]>=0&&rgba[3]<=1){return rgba;}rgba[3]=alpha[0]+(alpha[1]-alpha[0])*index;return rgba;});/*
* map increasing linear values between indicies to
* linear steps in colorvalues
*/var colors=[];for(i=0;i=0;}function compareAngle(a,b,c,d){var bcd=orient(b,c,d);if(bcd===0){//Handle degenerate cases
var sabc=sgn(orient(a,b,c));var sabd=sgn(orient(a,b,d));if(sabc===sabd){if(sabc===0){var ic=testInterior(a,b,c);var id=testInterior(a,b,d);if(ic===id){return 0;}else if(ic){return 1;}else{return-1;}}return 0;}else if(sabd===0){if(sabc>0){return-1;}else if(testInterior(a,b,d)){return-1;}else{return 1;}}else if(sabc===0){if(sabd>0){return 1;}else if(testInterior(a,b,c)){return 1;}else{return-1;}}return sgn(sabd-sabc);}var abc=orient(a,b,c);if(abc>0){if(bcd>0&&orient(a,b,d)>0){return 1;}return-1;}else if(abc<0){if(bcd>0||orient(a,b,d)>0){return 1;}return-1;}else{var abd=orient(a,b,d);if(abd>0){return 1;}else{if(testInterior(a,b,c)){return 1;}else{return-1;}}}}/***/},/***/8572:/***/function(module){"use strict";module.exports=function signum(x){if(x<0){return-1;}if(x>0){return 1;}return 0.0;};/***/},/***/8507:/***/function(module){module.exports=compareCells;var min=Math.min;function compareInt(a,b){return a-b;}function compareCells(a,b){var n=a.length,t=a.length-b.length;if(t){return t;}switch(n){case 0:return 0;case 1:return a[0]-b[0];case 2:return a[0]+a[1]-b[0]-b[1]||min(a[0],a[1])-min(b[0],b[1]);case 3:var l1=a[0]+a[1],m1=b[0]+b[1];t=l1+a[2]-(m1+b[2]);if(t){return t;}var l0=min(a[0],a[1]),m0=min(b[0],b[1]);return min(l0,a[2])-min(m0,b[2])||min(l0+a[2],l1)-min(m0+b[2],m1);case 4:var aw=a[0],ax=a[1],ay=a[2],az=a[3],bw=b[0],bx=b[1],by=b[2],bz=b[3];return aw+ax+ay+az-(bw+bx+by+bz)||min(aw,ax,ay,az)-min(bw,bx,by,bz,bw)||min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az)-min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz)||min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az)-min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz);default:var as=a.slice().sort(compareInt);var bs=b.slice().sort(compareInt);for(var i=0;ipoints[hi][0]){hi=i;}}if(lohi){return[[hi],[lo]];}else{return[[lo]];}}/***/},/***/4750:/***/function(module,__unused_webpack_exports,__nested_webpack_require_205357__){"use strict";module.exports=convexHull2D;var monotoneHull=__nested_webpack_require_205357__(3090);function convexHull2D(points){var hull=monotoneHull(points);var h=hull.length;if(h<=2){return[];}var edges=new Array(h);var a=hull[h-1];for(var i=0;i=front[k]){x+=1;}}c[j]=x;}}}return cells;}function convexHullnD(points,d){try{return ich(points,true);}catch(e){//If point set is degenerate, try to find a basis and rerun it
var ah=aff(points);if(ah.length<=d){//No basis, no try
return[];}var npoints=permute(points,ah);var nhull=ich(npoints,true);return invPermute(nhull,ah);}}/***/},/***/4769:/***/function(module){"use strict";function dcubicHermite(p0,v0,p1,v1,t,f){var dh00=6*t*t-6*t,dh10=3*t*t-4*t+1,dh01=-6*t*t+6*t,dh11=3*t*t-2*t;if(p0.length){if(!f){f=new Array(p0.length);}for(var i=p0.length-1;i>=0;--i){f[i]=dh00*p0[i]+dh10*v0[i]+dh01*p1[i]+dh11*v1[i];}return f;}return dh00*p0+dh10*v0+dh01*p1[i]+dh11*v1;}function cubicHermite(p0,v0,p1,v1,t,f){var ti=t-1,t2=t*t,ti2=ti*ti,h00=(1+2*t)*ti2,h10=t*ti2,h01=t2*(3-2*t),h11=t2*ti;if(p0.length){if(!f){f=new Array(p0.length);}for(var i=p0.length-1;i>=0;--i){f[i]=h00*p0[i]+h10*v0[i]+h01*p1[i]+h11*v1[i];}return f;}return h00*p0+h10*v0+h01*p1+h11*v1;}module.exports=cubicHermite;module.exports.derivative=dcubicHermite;/***/},/***/7642:/***/function(module,__unused_webpack_exports,__nested_webpack_require_207403__){"use strict";var ch=__nested_webpack_require_207403__(8954);var uniq=__nested_webpack_require_207403__(1682);module.exports=triangulate;function LiftedPoint(p,i){this.point=p;this.index=i;}function compareLifted(a,b){var ap=a.point;var bp=b.point;var d=ap.length;for(var i=0;i=2){return false;}}cell[j]=v;}return true;});}else{hull=hull.filter(function(cell){for(var i=0;i<=d;++i){var v=dindex[cell[i]];if(v<0){return false;}cell[i]=v;}return true;});}if(d&1){for(var i=0;i>>31;};module.exports.exponent=function(n){var b=module.exports.hi(n);return(b<<1>>>21)-1023;};module.exports.fraction=function(n){var lo=module.exports.lo(n);var hi=module.exports.hi(n);var b=hi&(1<<20)-1;if(hi&0x7ff00000){b+=1<<20;}return[lo,b];};module.exports.denormalized=function(n){var hi=module.exports.hi(n);return!(hi&0x7ff00000);};/***/},/***/1338:/***/function(module){"use strict";function dupe_array(count,value,i){var c=count[i]|0;if(c<=0){return[];}var result=new Array(c),j;if(i===count.length-1){for(j=0;j0){return dupe_number(count|0,value);}break;case"object":if(typeof count.length==="number"){return dupe_array(count,value,0);}break;}return[];}module.exports=dupe;/***/},/***/3134:/***/function(module,__unused_webpack_exports,__nested_webpack_require_212399__){"use strict";module.exports=edgeToAdjacency;var uniq=__nested_webpack_require_212399__(1682);function edgeToAdjacency(edges,numVertices){var numEdges=edges.length;if(typeof numVertices!=="number"){numVertices=0;for(var i=0;i=n-1){var ptr=state.length-1;var tf=t-time[n-1];for(var i=0;i=n-1){var ptr=state.length-1;var tf=t-time[n-1];for(var i=0;i=0;--i){if(velocity[--ptr]){return false;}}return true;};proto.jump=function(t){var t0=this.lastT();var d=this.dimension;if(t0;--i){state.push(clamp(lo[i-1],hi[i-1],arguments[i]));velocity.push(0);}};proto.push=function(t){var t0=this.lastT();var d=this.dimension;if(t1e-6?1/dt:0;this._time.push(t);for(var i=d;i>0;--i){var xc=clamp(lo[i-1],hi[i-1],arguments[i]);state.push(xc);velocity.push((xc-state[ptr++])*sf);}};proto.set=function(t){var d=this.dimension;if(t0;--i){state.push(clamp(lo[i-1],hi[i-1],arguments[i]));velocity.push(0);}};proto.move=function(t){var t0=this.lastT();var d=this.dimension;if(t<=t0||arguments.length!==d+1){return;}var state=this._state;var velocity=this._velocity;var statePtr=state.length-this.dimension;var bounds=this.bounds;var lo=bounds[0];var hi=bounds[1];var dt=t-t0;var sf=dt>1e-6?1/dt:0.0;this._time.push(t);for(var i=d;i>0;--i){var dx=arguments[i];state.push(clamp(lo[i-1],hi[i-1],state[statePtr++]+dx));velocity.push(dx*sf);}};proto.idle=function(t){var t0=this.lastT();if(t=0;--i){state.push(clamp(lo[i],hi[i],state[statePtr]+dt*velocity[statePtr]));velocity.push(0);statePtr+=1;}};function getZero(d){var result=new Array(d);for(var i=0;i=0;--s){var n=n_stack[s];if(d_stack[s]<=0){n_stack[s]=new RBNode(n._color,n.key,n.value,n_stack[s+1],n.right,n._count+1);}else{n_stack[s]=new RBNode(n._color,n.key,n.value,n.left,n_stack[s+1],n._count+1);}}//Rebalance tree using rotations
//console.log("start insert", key, d_stack)
for(var s=n_stack.length-1;s>1;--s){var p=n_stack[s-1];var n=n_stack[s];if(p._color===BLACK||n._color===BLACK){break;}var pp=n_stack[s-2];if(pp.left===p){if(p.left===n){var y=pp.right;if(y&&y._color===RED){//console.log("LLr")
p._color=BLACK;pp.right=repaint(BLACK,y);pp._color=RED;s-=1;}else{//console.log("LLb")
pp._color=RED;pp.left=p.right;p._color=BLACK;p.right=pp;n_stack[s-2]=p;n_stack[s-1]=n;recount(pp);recount(p);if(s>=3){var ppp=n_stack[s-3];if(ppp.left===pp){ppp.left=p;}else{ppp.right=p;}}break;}}else{var y=pp.right;if(y&&y._color===RED){//console.log("LRr")
p._color=BLACK;pp.right=repaint(BLACK,y);pp._color=RED;s-=1;}else{//console.log("LRb")
p.right=n.left;pp._color=RED;pp.left=n.right;n._color=BLACK;n.left=p;n.right=pp;n_stack[s-2]=n;n_stack[s-1]=p;recount(pp);recount(p);recount(n);if(s>=3){var ppp=n_stack[s-3];if(ppp.left===pp){ppp.left=n;}else{ppp.right=n;}}break;}}}else{if(p.right===n){var y=pp.left;if(y&&y._color===RED){//console.log("RRr", y.key)
p._color=BLACK;pp.left=repaint(BLACK,y);pp._color=RED;s-=1;}else{//console.log("RRb")
pp._color=RED;pp.right=p.left;p._color=BLACK;p.left=pp;n_stack[s-2]=p;n_stack[s-1]=n;recount(pp);recount(p);if(s>=3){var ppp=n_stack[s-3];if(ppp.right===pp){ppp.right=p;}else{ppp.left=p;}}break;}}else{var y=pp.left;if(y&&y._color===RED){//console.log("RLr")
p._color=BLACK;pp.left=repaint(BLACK,y);pp._color=RED;s-=1;}else{//console.log("RLb")
p.left=n.right;pp._color=RED;pp.right=n.left;n._color=BLACK;n.right=p;n.left=pp;n_stack[s-2]=n;n_stack[s-1]=p;recount(pp);recount(p);recount(n);if(s>=3){var ppp=n_stack[s-3];if(ppp.right===pp){ppp.right=n;}else{ppp.left=n;}}break;}}}}//Return new tree
n_stack[0]._color=BLACK;return new RedBlackTree(cmp,n_stack[0]);};//Visit all nodes inorder
function doVisitFull(visit,node){if(node.left){var v=doVisitFull(visit,node.left);if(v){return v;}}var v=visit(node.key,node.value);if(v){return v;}if(node.right){return doVisitFull(visit,node.right);}}//Visit half nodes in order
function doVisitHalf(lo,compare,visit,node){var l=compare(lo,node.key);if(l<=0){if(node.left){var v=doVisitHalf(lo,compare,visit,node.left);if(v){return v;}}var v=visit(node.key,node.value);if(v){return v;}}if(node.right){return doVisitHalf(lo,compare,visit,node.right);}}//Visit all nodes within a range
function doVisit(lo,hi,compare,visit,node){var l=compare(lo,node.key);var h=compare(hi,node.key);var v;if(l<=0){if(node.left){v=doVisit(lo,hi,compare,visit,node.left);if(v){return v;}}if(h>0){v=visit(node.key,node.value);if(v){return v;}}}if(h>0&&node.right){return doVisit(lo,hi,compare,visit,node.right);}}proto.forEach=function rbTreeForEach(visit,lo,hi){if(!this.root){return;}switch(arguments.length){case 1:return doVisitFull(visit,this.root);break;case 2:return doVisitHalf(lo,this._compare,visit,this.root);break;case 3:if(this._compare(lo,hi)>=0){return;}return doVisit(lo,hi,this._compare,visit,this.root);break;}};//First item in list
Object.defineProperty(proto,"begin",{get:function(){var stack=[];var n=this.root;while(n){stack.push(n);n=n.left;}return new RedBlackTreeIterator(this,stack);}});//Last item in list
Object.defineProperty(proto,"end",{get:function(){var stack=[];var n=this.root;while(n){stack.push(n);n=n.right;}return new RedBlackTreeIterator(this,stack);}});//Find the ith item in the tree
proto.at=function(idx){if(idx<0){return new RedBlackTreeIterator(this,[]);}var n=this.root;var stack=[];while(true){stack.push(n);if(n.left){if(idx=n.right._count){break;}n=n.right;}else{break;}}return new RedBlackTreeIterator(this,[]);};proto.ge=function(key){var cmp=this._compare;var n=this.root;var stack=[];var last_ptr=0;while(n){var d=cmp(key,n.key);stack.push(n);if(d<=0){last_ptr=stack.length;}if(d<=0){n=n.left;}else{n=n.right;}}stack.length=last_ptr;return new RedBlackTreeIterator(this,stack);};proto.gt=function(key){var cmp=this._compare;var n=this.root;var stack=[];var last_ptr=0;while(n){var d=cmp(key,n.key);stack.push(n);if(d<0){last_ptr=stack.length;}if(d<0){n=n.left;}else{n=n.right;}}stack.length=last_ptr;return new RedBlackTreeIterator(this,stack);};proto.lt=function(key){var cmp=this._compare;var n=this.root;var stack=[];var last_ptr=0;while(n){var d=cmp(key,n.key);stack.push(n);if(d>0){last_ptr=stack.length;}if(d<=0){n=n.left;}else{n=n.right;}}stack.length=last_ptr;return new RedBlackTreeIterator(this,stack);};proto.le=function(key){var cmp=this._compare;var n=this.root;var stack=[];var last_ptr=0;while(n){var d=cmp(key,n.key);stack.push(n);if(d>=0){last_ptr=stack.length;}if(d<0){n=n.left;}else{n=n.right;}}stack.length=last_ptr;return new RedBlackTreeIterator(this,stack);};//Finds the item with key if it exists
proto.find=function(key){var cmp=this._compare;var n=this.root;var stack=[];while(n){var d=cmp(key,n.key);stack.push(n);if(d===0){return new RedBlackTreeIterator(this,stack);}if(d<=0){n=n.left;}else{n=n.right;}}return new RedBlackTreeIterator(this,[]);};//Removes item with key from tree
proto.remove=function(key){var iter=this.find(key);if(iter){return iter.remove();}return this;};//Returns the item at `key`
proto.get=function(key){var cmp=this._compare;var n=this.root;while(n){var d=cmp(key,n.key);if(d===0){return n.value;}if(d<=0){n=n.left;}else{n=n.right;}}return;};//Iterator for red black tree
function RedBlackTreeIterator(tree,stack){this.tree=tree;this._stack=stack;}var iproto=RedBlackTreeIterator.prototype;//Test if iterator is valid
Object.defineProperty(iproto,"valid",{get:function(){return this._stack.length>0;}});//Node of the iterator
Object.defineProperty(iproto,"node",{get:function(){if(this._stack.length>0){return this._stack[this._stack.length-1];}return null;},enumerable:true});//Makes a copy of an iterator
iproto.clone=function(){return new RedBlackTreeIterator(this.tree,this._stack.slice());};//Swaps two nodes
function swapNode(n,v){n.key=v.key;n.value=v.value;n.left=v.left;n.right=v.right;n._color=v._color;n._count=v._count;}//Fix up a double black node in a tree
function fixDoubleBlack(stack){var n,p,s,z;for(var i=stack.length-1;i>=0;--i){n=stack[i];if(i===0){n._color=BLACK;return;}//console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
p=stack[i-1];if(p.left===n){//console.log("left child")
s=p.right;if(s.right&&s.right._color===RED){//console.log("case 1: right sibling child red")
s=p.right=cloneNode(s);z=s.right=cloneNode(s.right);p.right=s.left;s.left=p;s.right=z;s._color=p._color;n._color=BLACK;p._color=BLACK;z._color=BLACK;recount(p);recount(s);if(i>1){var pp=stack[i-2];if(pp.left===p){pp.left=s;}else{pp.right=s;}}stack[i-1]=s;return;}else if(s.left&&s.left._color===RED){//console.log("case 1: left sibling child red")
s=p.right=cloneNode(s);z=s.left=cloneNode(s.left);p.right=z.left;s.left=z.right;z.left=p;z.right=s;z._color=p._color;p._color=BLACK;s._color=BLACK;n._color=BLACK;recount(p);recount(s);recount(z);if(i>1){var pp=stack[i-2];if(pp.left===p){pp.left=z;}else{pp.right=z;}}stack[i-1]=z;return;}if(s._color===BLACK){if(p._color===RED){//console.log("case 2: black sibling, red parent", p.right.value)
p._color=BLACK;p.right=repaint(RED,s);return;}else{//console.log("case 2: black sibling, black parent", p.right.value)
p.right=repaint(RED,s);continue;}}else{//console.log("case 3: red sibling")
s=cloneNode(s);p.right=s.left;s.left=p;s._color=p._color;p._color=RED;recount(p);recount(s);if(i>1){var pp=stack[i-2];if(pp.left===p){pp.left=s;}else{pp.right=s;}}stack[i-1]=s;stack[i]=p;if(i+11){var pp=stack[i-2];if(pp.right===p){pp.right=s;}else{pp.left=s;}}stack[i-1]=s;return;}else if(s.right&&s.right._color===RED){//console.log("case 1: right sibling child red")
s=p.left=cloneNode(s);z=s.right=cloneNode(s.right);p.left=z.right;s.right=z.left;z.right=p;z.left=s;z._color=p._color;p._color=BLACK;s._color=BLACK;n._color=BLACK;recount(p);recount(s);recount(z);if(i>1){var pp=stack[i-2];if(pp.right===p){pp.right=z;}else{pp.left=z;}}stack[i-1]=z;return;}if(s._color===BLACK){if(p._color===RED){//console.log("case 2: black sibling, red parent")
p._color=BLACK;p.left=repaint(RED,s);return;}else{//console.log("case 2: black sibling, black parent")
p.left=repaint(RED,s);continue;}}else{//console.log("case 3: red sibling")
s=cloneNode(s);p.left=s.right;s.right=p;s._color=p._color;p._color=RED;recount(p);recount(s);if(i>1){var pp=stack[i-2];if(pp.right===p){pp.right=s;}else{pp.left=s;}}stack[i-1]=s;stack[i]=p;if(i+1=0;--i){var n=stack[i];if(n.left===stack[i+1]){cstack[i]=new RBNode(n._color,n.key,n.value,cstack[i+1],n.right,n._count);}else{cstack[i]=new RBNode(n._color,n.key,n.value,n.left,cstack[i+1],n._count);}}//Get node
n=cstack[cstack.length-1];//console.log("start remove: ", n.value)
//If not leaf, then swap with previous node
if(n.left&&n.right){//console.log("moving to leaf")
//First walk to previous leaf
var split=cstack.length;n=n.left;while(n.right){cstack.push(n);n=n.right;}//Copy path to leaf
var v=cstack[split-1];cstack.push(new RBNode(n._color,v.key,v.value,n.left,n.right,n._count));cstack[split-1].key=n.key;cstack[split-1].value=n.value;//Fix up stack
for(var i=cstack.length-2;i>=split;--i){n=cstack[i];cstack[i]=new RBNode(n._color,n.key,n.value,n.left,cstack[i+1],n._count);}cstack[split-1].left=cstack[split];}//console.log("stack=", cstack.map(function(v) { return v.value }))
//Remove leaf node
n=cstack[cstack.length-1];if(n._color===RED){//Easy case: removing red leaf
//console.log("RED leaf")
var p=cstack[cstack.length-2];if(p.left===n){p.left=null;}else if(p.right===n){p.right=null;}cstack.pop();for(var i=0;i0){return this._stack[this._stack.length-1].key;}return;},enumerable:true});//Returns value
Object.defineProperty(iproto,"value",{get:function(){if(this._stack.length>0){return this._stack[this._stack.length-1].value;}return;},enumerable:true});//Returns the position of this iterator in the sorted list
Object.defineProperty(iproto,"index",{get:function(){var idx=0;var stack=this._stack;if(stack.length===0){var r=this.tree.root;if(r){return r._count;}return 0;}else if(stack[stack.length-1].left){idx=stack[stack.length-1].left._count;}for(var s=stack.length-2;s>=0;--s){if(stack[s+1]===stack[s].right){++idx;if(stack[s].left){idx+=stack[s].left._count;}}}return idx;},enumerable:true});//Advances iterator to next element in list
iproto.next=function(){var stack=this._stack;if(stack.length===0){return;}var n=stack[stack.length-1];if(n.right){n=n.right;while(n){stack.push(n);n=n.left;}}else{stack.pop();while(stack.length>0&&stack[stack.length-1].right===n){n=stack[stack.length-1];stack.pop();}}};//Checks if iterator is at end of tree
Object.defineProperty(iproto,"hasNext",{get:function(){var stack=this._stack;if(stack.length===0){return false;}if(stack[stack.length-1].right){return true;}for(var s=stack.length-1;s>0;--s){if(stack[s-1].left===stack[s]){return true;}}return false;}});//Update value
iproto.update=function(value){var stack=this._stack;if(stack.length===0){throw new Error("Can't update empty node!");}var cstack=new Array(stack.length);var n=stack[stack.length-1];cstack[cstack.length-1]=new RBNode(n._color,n.key,value,n.left,n.right,n._count);for(var i=stack.length-2;i>=0;--i){n=stack[i];if(n.left===stack[i+1]){cstack[i]=new RBNode(n._color,n.key,n.value,cstack[i+1],n.right,n._count);}else{cstack[i]=new RBNode(n._color,n.key,n.value,n.left,cstack[i+1],n._count);}}return new RedBlackTree(this.tree._compare,cstack[0]);};//Moves iterator backward one element
iproto.prev=function(){var stack=this._stack;if(stack.length===0){return;}var n=stack[stack.length-1];if(n.left){n=n.left;while(n){stack.push(n);n=n.right;}}else{stack.pop();while(stack.length>0&&stack[stack.length-1].left===n){n=stack[stack.length-1];stack.pop();}}};//Checks if iterator is at start of tree
Object.defineProperty(iproto,"hasPrev",{get:function(){var stack=this._stack;if(stack.length===0){return false;}if(stack[stack.length-1].left){return true;}for(var s=stack.length-1;s>0;--s){if(stack[s-1].right===stack[s]){return true;}}return false;}});//Default comparison function
function defaultCompare(a,b){if(ab){return 1;}return 0;}//Build a tree
function createRBTree(compare){return new RedBlackTree(compare||defaultCompare,null);}/***/},/***/3837:/***/function(module,__unused_webpack_exports,__nested_webpack_require_234991__){"use strict";module.exports=createAxes;var createText=__nested_webpack_require_234991__(4935);var createLines=__nested_webpack_require_234991__(501);var createBackground=__nested_webpack_require_234991__(5304);var getCubeProperties=__nested_webpack_require_234991__(6429);var Ticks=__nested_webpack_require_234991__(6444);var identity=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);var ab=ArrayBuffer;var dv=DataView;function isTypedArray(a){return ab.isView(a)&&!(a instanceof dv);}function isArrayOrTypedArray(a){return Array.isArray(a)||isTypedArray(a);}function copyVec3(a,b){a[0]=b[0];a[1]=b[1];a[2]=b[2];return a;}function Axes(gl){this.gl=gl;this.pixelRatio=1;this.bounds=[[-10,-10,-10],[10,10,10]];this.ticks=[[],[],[]];this.autoTicks=true;this.tickSpacing=[1,1,1];this.tickEnable=[true,true,true];this.tickFont=['sans-serif','sans-serif','sans-serif'];this.tickFontStyle=['normal','normal','normal'];this.tickFontWeight=['normal','normal','normal'];this.tickFontVariant=['normal','normal','normal'];this.tickSize=[12,12,12];this.tickAngle=[0,0,0];this.tickAlign=['auto','auto','auto'];this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]];this.tickPad=[10,10,10];this.lastCubeProps={cubeEdges:[0,0,0],axis:[0,0,0]};this.labels=['x','y','z'];this.labelEnable=[true,true,true];this.labelFont=['sans-serif','sans-serif','sans-serif'];this.labelFontStyle=['normal','normal','normal'];this.labelFontWeight=['normal','normal','normal'];this.labelFontVariant=['normal','normal','normal'];this.labelSize=[20,20,20];this.labelAngle=[0,0,0];this.labelAlign=['auto','auto','auto'];this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]];this.labelPad=[10,10,10];this.lineEnable=[true,true,true];this.lineMirror=[false,false,false];this.lineWidth=[1,1,1];this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]];this.lineTickEnable=[true,true,true];this.lineTickMirror=[false,false,false];this.lineTickLength=[0,0,0];this.lineTickWidth=[1,1,1];this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]];this.gridEnable=[true,true,true];this.gridWidth=[1,1,1];this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]];this.zeroEnable=[true,true,true];this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]];this.zeroLineWidth=[2,2,2];this.backgroundEnable=[false,false,false];this.backgroundColor=[[0.8,0.8,0.8,0.5],[0.8,0.8,0.8,0.5],[0.8,0.8,0.8,0.5]];this._firstInit=true;this._text=null;this._lines=null;this._background=createBackground(gl);}var proto=Axes.prototype;proto.update=function(options){options=options||{};//Option parsing helper functions
function parseOption(nest,cons,name){if(name in options){var opt=options[name];var prev=this[name];var next;if(nest?isArrayOrTypedArray(opt)&&isArrayOrTypedArray(opt[0]):isArrayOrTypedArray(opt)){this[name]=next=[cons(opt[0]),cons(opt[1]),cons(opt[2])];}else{this[name]=next=[cons(opt),cons(opt),cons(opt)];}for(var i=0;i<3;++i){if(next[i]!==prev[i]){return true;}}}return false;}var NUMBER=parseOption.bind(this,false,Number);var BOOLEAN=parseOption.bind(this,false,Boolean);var STRING=parseOption.bind(this,false,String);var COLOR=parseOption.bind(this,true,function(v){if(isArrayOrTypedArray(v)){if(v.length===3){return[+v[0],+v[1],+v[2],1.0];}else if(v.length===4){return[+v[0],+v[1],+v[2],+v[3]];}}return[0,0,0,1];});//Tick marks and bounds
var nextTicks;var ticksUpdate=false;var boundsChanged=false;if('bounds'in options){var bounds=options.bounds;i_loop:for(var i=0;i<2;++i){for(var j=0;j<3;++j){if(bounds[i][j]!==this.bounds[i][j]){boundsChanged=true;}this.bounds[i][j]=bounds[i][j];}}}if('ticks'in options){nextTicks=options.ticks;ticksUpdate=true;this.autoTicks=false;for(var i=0;i<3;++i){this.tickSpacing[i]=0.0;}}else if(NUMBER('tickSpacing')){this.autoTicks=true;boundsChanged=true;}if(this._firstInit){if(!('ticks'in options||'tickSpacing'in options)){this.autoTicks=true;}//Force tick recomputation on first update
boundsChanged=true;ticksUpdate=true;this._firstInit=false;}if(boundsChanged&&this.autoTicks){nextTicks=Ticks.create(this.bounds,this.tickSpacing);ticksUpdate=true;}//Compare next ticks to previous ticks, only update if needed
if(ticksUpdate){for(var i=0;i<3;++i){nextTicks[i].sort(function(a,b){return a.x-b.x;});}if(Ticks.equal(nextTicks,this.ticks)){ticksUpdate=false;}else{this.ticks=nextTicks;}}//Parse tick properties
BOOLEAN('tickEnable');//If font changes, must rebuild vbo
if(STRING('tickFont'))ticksUpdate=true;if(STRING('tickFontStyle'))ticksUpdate=true;if(STRING('tickFontWeight'))ticksUpdate=true;if(STRING('tickFontVariant'))ticksUpdate=true;NUMBER('tickSize');NUMBER('tickAngle');NUMBER('tickPad');COLOR('tickColor');//Axis labels
var labelUpdate=STRING('labels');if(STRING('labelFont'))labelUpdate=true;if(STRING('labelFontStyle'))labelUpdate=true;if(STRING('labelFontWeight'))labelUpdate=true;if(STRING('labelFontVariant'))labelUpdate=true;BOOLEAN('labelEnable');NUMBER('labelSize');NUMBER('labelPad');COLOR('labelColor');//Axis lines
BOOLEAN('lineEnable');BOOLEAN('lineMirror');NUMBER('lineWidth');COLOR('lineColor');//Axis line ticks
BOOLEAN('lineTickEnable');BOOLEAN('lineTickMirror');NUMBER('lineTickLength');NUMBER('lineTickWidth');COLOR('lineTickColor');//Grid lines
BOOLEAN('gridEnable');NUMBER('gridWidth');COLOR('gridColor');//Zero line
BOOLEAN('zeroEnable');COLOR('zeroLineColor');NUMBER('zeroLineWidth');//Background
BOOLEAN('backgroundEnable');COLOR('backgroundColor');var labelFontOpts=[{family:this.labelFont[0],style:this.labelFontStyle[0],weight:this.labelFontWeight[0],variant:this.labelFontVariant[0]},{family:this.labelFont[1],style:this.labelFontStyle[1],weight:this.labelFontWeight[1],variant:this.labelFontVariant[1]},{family:this.labelFont[2],style:this.labelFontStyle[2],weight:this.labelFontWeight[2],variant:this.labelFontVariant[2]}];var tickFontOpts=[{family:this.tickFont[0],style:this.tickFontStyle[0],weight:this.tickFontWeight[0],variant:this.tickFontVariant[0]},{family:this.tickFont[1],style:this.tickFontStyle[1],weight:this.tickFontWeight[1],variant:this.tickFontVariant[1]},{family:this.tickFont[2],style:this.tickFontStyle[2],weight:this.tickFontWeight[2],variant:this.tickFontVariant[2]}];//Update text if necessary
if(!this._text){this._text=createText(this.gl,this.bounds,this.labels,labelFontOpts,this.ticks,tickFontOpts);}else if(this._text&&(labelUpdate||ticksUpdate)){this._text.update(this.bounds,this.labels,labelFontOpts,this.ticks,tickFontOpts);}//Update lines if necessary
if(this._lines&&ticksUpdate){this._lines.dispose();this._lines=null;}if(!this._lines){this._lines=createLines(this.gl,this.bounds,this.ticks);}};function OffsetInfo(){this.primalOffset=[0,0,0];this.primalMinor=[0,0,0];this.mirrorOffset=[0,0,0];this.mirrorMinor=[0,0,0];}var LINE_OFFSET=[new OffsetInfo(),new OffsetInfo(),new OffsetInfo()];function computeLineOffset(result,i,bounds,cubeEdges,cubeAxis){var primalOffset=result.primalOffset;var primalMinor=result.primalMinor;var dualOffset=result.mirrorOffset;var dualMinor=result.mirrorMinor;var e=cubeEdges[i];//Calculate offsets
for(var j=0;j<3;++j){if(i===j){continue;}var a=primalOffset,b=dualOffset,c=primalMinor,d=dualMinor;if(e&1<0){c[j]=-1;d[j]=0;}else{c[j]=0;d[j]=+1;}}}var CUBE_ENABLE=[0,0,0];var DEFAULT_PARAMS={model:identity,view:identity,projection:identity,_ortho:false};proto.isOpaque=function(){return true;};proto.isTransparent=function(){return false;};proto.drawTransparent=function(params){};var ALIGN_OPTION_AUTO=0;// i.e. as defined in the shader the text would rotate to stay upwards range: [-90,90]
var PRIMAL_MINOR=[0,0,0];var MIRROR_MINOR=[0,0,0];var PRIMAL_OFFSET=[0,0,0];proto.draw=function(params){params=params||DEFAULT_PARAMS;var gl=this.gl;//Geometry for camera and axes
var model=params.model||identity;var view=params.view||identity;var projection=params.projection||identity;var bounds=this.bounds;var isOrtho=params._ortho||false;//Unpack axis info
var cubeParams=getCubeProperties(model,view,projection,bounds,isOrtho);var cubeEdges=cubeParams.cubeEdges;var cubeAxis=cubeParams.axis;var cx=view[12];var cy=view[13];var cz=view[14];var cw=view[15];var orthoFix=isOrtho?2:1;// double up padding for orthographic ticks & labels
var pixelScaleF=orthoFix*this.pixelRatio*(projection[3]*cx+projection[7]*cy+projection[11]*cz+projection[15]*cw)/gl.drawingBufferHeight;for(var i=0;i<3;++i){this.lastCubeProps.cubeEdges[i]=cubeEdges[i];this.lastCubeProps.axis[i]=cubeAxis[i];}//Compute axis info
var lineOffset=LINE_OFFSET;for(var i=0;i<3;++i){computeLineOffset(LINE_OFFSET[i],i,this.bounds,cubeEdges,cubeAxis);}//Set up state parameters
var gl=this.gl;//Draw background first
var cubeEnable=CUBE_ENABLE;for(var i=0;i<3;++i){if(this.backgroundEnable[i]){cubeEnable[i]=cubeAxis[i];}else{cubeEnable[i]=0;}}this._background.draw(model,view,projection,bounds,cubeEnable,this.backgroundColor);//Draw lines
this._lines.bind(model,view,projection,this);//First draw grid lines and zero lines
for(var i=0;i<3;++i){var x=[0,0,0];if(cubeAxis[i]>0){x[i]=bounds[1][i];}else{x[i]=bounds[0][i];}//Draw grid lines
for(var j=0;j<2;++j){var u=(i+1+j)%3;var v=(i+1+(j^1))%3;if(this.gridEnable[u]){this._lines.drawGrid(u,v,this.bounds,x,this.gridColor[u],this.gridWidth[u]*this.pixelRatio);}}//Draw zero lines (need to do this AFTER all grid lines are drawn)
for(var j=0;j<2;++j){var u=(i+1+j)%3;var v=(i+1+(j^1))%3;if(this.zeroEnable[v]){//Check if zero line in bounds
if(Math.min(bounds[0][v],bounds[1][v])<=0&&Math.max(bounds[0][v],bounds[1][v])>=0){this._lines.drawZero(u,v,this.bounds,x,this.zeroLineColor[v],this.zeroLineWidth[v]*this.pixelRatio);}}}}//Then draw axis lines and tick marks
for(var i=0;i<3;++i){//Draw axis lines
if(this.lineEnable[i]){this._lines.drawAxisLine(i,this.bounds,lineOffset[i].primalOffset,this.lineColor[i],this.lineWidth[i]*this.pixelRatio);}if(this.lineMirror[i]){this._lines.drawAxisLine(i,this.bounds,lineOffset[i].mirrorOffset,this.lineColor[i],this.lineWidth[i]*this.pixelRatio);}//Compute minor axes
var primalMinor=copyVec3(PRIMAL_MINOR,lineOffset[i].primalMinor);var mirrorMinor=copyVec3(MIRROR_MINOR,lineOffset[i].mirrorMinor);var tickLength=this.lineTickLength;for(var j=0;j<3;++j){var scaleFactor=pixelScaleF/model[5*j];primalMinor[j]*=tickLength[j]*scaleFactor;mirrorMinor[j]*=tickLength[j]*scaleFactor;}//Draw axis line ticks
if(this.lineTickEnable[i]){this._lines.drawAxisTicks(i,lineOffset[i].primalOffset,primalMinor,this.lineTickColor[i],this.lineTickWidth[i]*this.pixelRatio);}if(this.lineTickMirror[i]){this._lines.drawAxisTicks(i,lineOffset[i].mirrorOffset,mirrorMinor,this.lineTickColor[i],this.lineTickWidth[i]*this.pixelRatio);}}this._lines.unbind();//Draw text sprites
this._text.bind(model,view,projection,this.pixelRatio);var alignOpt;// options in shader are from this list {-1, 0, 1, 2, 3, ..., n}
// -1: backward compatible
// 0: raw data
// 1: auto align, free angles
// 2: auto align, horizontal or vertical
//3-n: auto align, round to n directions e.g. 12 -> round to angles with 30-degree steps
var hv_ratio=0.5;// can have an effect on the ratio between horizontals and verticals when using option 2
var enableAlign;var alignDir;function alignTo(i){alignDir=[0,0,0];alignDir[i]=1;}function solveTickAlignments(i,minor,major){var i1=(i+1)%3;var i2=(i+2)%3;var A=minor[i1];var B=minor[i2];var C=major[i1];var D=major[i2];if(A>0&&D>0){alignTo(i1);return;}else if(A>0&&D<0){alignTo(i1);return;}else if(A<0&&D>0){alignTo(i1);return;}else if(A<0&&D<0){alignTo(i1);return;}else if(B>0&&C>0){alignTo(i2);return;}else if(B>0&&C<0){alignTo(i2);return;}else if(B<0&&C>0){alignTo(i2);return;}else if(B<0&&C<0){alignTo(i2);return;}}for(var i=0;i<3;++i){var minor=lineOffset[i].primalMinor;var major=lineOffset[i].mirrorMinor;var offset=copyVec3(PRIMAL_OFFSET,lineOffset[i].primalOffset);for(var j=0;j<3;++j){if(this.lineTickEnable[i]){offset[j]+=pixelScaleF*minor[j]*Math.max(this.lineTickLength[j],0)/model[5*j];}}var axis=[0,0,0];axis[i]=1;//Draw tick text
if(this.tickEnable[i]){if(this.tickAngle[i]===-3600){this.tickAngle[i]=0;this.tickAlign[i]='auto';}else{this.tickAlign[i]=-1;}enableAlign=1;alignOpt=[this.tickAlign[i],hv_ratio,enableAlign];if(alignOpt[0]==='auto')alignOpt[0]=ALIGN_OPTION_AUTO;else alignOpt[0]=parseInt(''+alignOpt[0]);alignDir=[0,0,0];solveTickAlignments(i,minor,major);//Add tick padding
for(var j=0;j<3;++j){offset[j]+=pixelScaleF*minor[j]*this.tickPad[j]/model[5*j];}//Draw axis
this._text.drawTicks(i,this.tickSize[i],this.tickAngle[i],offset,this.tickColor[i],axis,alignDir,alignOpt);}//Draw labels
if(this.labelEnable[i]){enableAlign=0;alignDir=[0,0,0];if(this.labels[i].length>4){// for large label axis enable alignDir to axis
alignTo(i);enableAlign=1;}alignOpt=[this.labelAlign[i],hv_ratio,enableAlign];if(alignOpt[0]==='auto')alignOpt[0]=ALIGN_OPTION_AUTO;else alignOpt[0]=parseInt(''+alignOpt[0]);//Add label padding
for(var j=0;j<3;++j){offset[j]+=pixelScaleF*minor[j]*this.labelPad[j]/model[5*j];}offset[i]+=0.5*(bounds[0][i]+bounds[1][i]);//Draw axis
this._text.drawLabel(i,this.labelSize[i],this.labelAngle[i],offset,this.labelColor[i],[0,0,0],alignDir,alignOpt);}}this._text.unbind();};proto.dispose=function(){this._text.dispose();this._lines.dispose();this._background.dispose();this._lines=null;this._text=null;this._background=null;this.gl=null;};function createAxes(gl,options){var axes=new Axes(gl);axes.update(options);return axes;}/***/},/***/5304:/***/function(module,__unused_webpack_exports,__nested_webpack_require_248394__){"use strict";module.exports=createBackgroundCube;var createBuffer=__nested_webpack_require_248394__(2762);var createVAO=__nested_webpack_require_248394__(8116);var createShader=__nested_webpack_require_248394__(1879).bg;function BackgroundCube(gl,buffer,vao,shader){this.gl=gl;this.buffer=buffer;this.vao=vao;this.shader=shader;}var proto=BackgroundCube.prototype;proto.draw=function(model,view,projection,bounds,enable,colors){var needsBG=false;for(var i=0;i<3;++i){needsBG=needsBG||enable[i];}if(!needsBG){return;}var gl=this.gl;gl.enable(gl.POLYGON_OFFSET_FILL);gl.polygonOffset(1,2);this.shader.bind();this.shader.uniforms={model:model,view:view,projection:projection,bounds:bounds,enable:enable,colors:colors};this.vao.bind();this.vao.draw(this.gl.TRIANGLES,36);this.vao.unbind();gl.disable(gl.POLYGON_OFFSET_FILL);};proto.dispose=function(){this.vao.dispose();this.buffer.dispose();this.shader.dispose();};function createBackgroundCube(gl){//Create cube vertices
var vertices=[];var indices=[];var ptr=0;for(var d=0;d<3;++d){var u=(d+1)%3;var v=(d+2)%3;var x=[0,0,0];var c=[0,0,0];for(var s=-1;s<=1;s+=2){indices.push(ptr,ptr+2,ptr+1,ptr+1,ptr+2,ptr+3);x[d]=s;c[d]=s;for(var i=-1;i<=1;i+=2){x[u]=i;for(var j=-1;j<=1;j+=2){x[v]=j;vertices.push(x[0],x[1],x[2],c[0],c[1],c[2]);ptr+=1;}}//Swap u and v
var tt=u;u=v;v=tt;}}//Allocate buffer and vertex array
var buffer=createBuffer(gl,new Float32Array(vertices));var elements=createBuffer(gl,new Uint16Array(indices),gl.ELEMENT_ARRAY_BUFFER);var vao=createVAO(gl,[{buffer:buffer,type:gl.FLOAT,size:3,offset:0,stride:24},{buffer:buffer,type:gl.FLOAT,size:3,offset:12,stride:24}],elements);//Create shader object
var shader=createShader(gl);shader.attributes.position.location=0;shader.attributes.normal.location=1;return new BackgroundCube(gl,buffer,vao,shader);}/***/},/***/6429:/***/function(module,__unused_webpack_exports,__nested_webpack_require_250249__){"use strict";module.exports=getCubeEdges;var bits=__nested_webpack_require_250249__(8828);var multiply=__nested_webpack_require_250249__(6760);var splitPoly=__nested_webpack_require_250249__(5202);var orient=__nested_webpack_require_250249__(3250);var mvp=new Array(16);var pCubeVerts=new Array(8);var cubeVerts=new Array(8);var x=new Array(3);var zero3=[0,0,0];(function(){for(var i=0;i<8;++i){pCubeVerts[i]=[1,1,1,1];cubeVerts[i]=[1,1,1];}})();function transformHg(result,x,mat){for(var i=0;i<4;++i){result[i]=mat[12+i];for(var j=0;j<3;++j){result[i]+=x[j]*mat[4*j+i];}}}var FRUSTUM_PLANES=[[0,0,1,0,0],[0,0,-1,1,0],[0,-1,0,1,0],[0,1,0,1,0],[-1,0,0,1,0],[1,0,0,1,0]];function polygonArea(p){for(var i=0;io0){closest|=1<o0){closest|=1<cubeVerts[i][1]){bottom=i;}}//Find left/right neighbors of bottom vertex
var left=-1;for(var i=0;i<3;++i){var idx=bottom^1<cubeVerts[right][0]){right=idx;}}//Determine edge axis coordinates
var cubeEdges=CUBE_EDGES;cubeEdges[0]=cubeEdges[1]=cubeEdges[2]=0;cubeEdges[bits.log2(left^bottom)]=bottom&left;cubeEdges[bits.log2(bottom^right)]=bottom&right;var top=right^7;if(top===closest||top===farthest){top=left^7;cubeEdges[bits.log2(right^top)]=top&right;}else{cubeEdges[bits.log2(left^top)]=top&left;}//Determine visible faces
var axis=CUBE_AXIS;var cutCorner=closest;for(var d=0;d<3;++d){if(cutCorner&1< HALF_PI) && (b <= ONE_AND_HALF_PI)) ?\n b - PI :\n b;\n}\n\nfloat look_horizontal_or_vertical(float a, float ratio) {\n // ratio controls the ratio between being horizontal to (vertical + horizontal)\n // if ratio is set to 0.5 then it is 50%, 50%.\n // when using a higher ratio e.g. 0.75 the result would\n // likely be more horizontal than vertical.\n\n float b = positive_angle(a);\n\n return\n (b < ( ratio) * HALF_PI) ? 0.0 :\n (b < (2.0 - ratio) * HALF_PI) ? -HALF_PI :\n (b < (2.0 + ratio) * HALF_PI) ? 0.0 :\n (b < (4.0 - ratio) * HALF_PI) ? HALF_PI :\n 0.0;\n}\n\nfloat roundTo(float a, float b) {\n return float(b * floor((a + 0.5 * b) / b));\n}\n\nfloat look_round_n_directions(float a, int n) {\n float b = positive_angle(a);\n float div = TWO_PI / float(n);\n float c = roundTo(b, div);\n return look_upwards(c);\n}\n\nfloat applyAlignOption(float rawAngle, float delta) {\n return\n (option > 2) ? look_round_n_directions(rawAngle + delta, option) : // option 3-n: round to n directions\n (option == 2) ? look_horizontal_or_vertical(rawAngle + delta, hv_ratio) : // horizontal or vertical\n (option == 1) ? rawAngle + delta : // use free angle, and flip to align with one direction of the axis\n (option == 0) ? look_upwards(rawAngle) : // use free angle, and stay upwards\n (option ==-1) ? 0.0 : // useful for backward compatibility, all texts remains horizontal\n rawAngle; // otherwise return back raw input angle\n}\n\nbool isAxisTitle = (axis.x == 0.0) &&\n (axis.y == 0.0) &&\n (axis.z == 0.0);\n\nvoid main() {\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n\n float beta = angle; // i.e. user defined attributes for each tick\n\n float axisAngle;\n float clipAngle;\n float flip;\n\n if (enableAlign) {\n axisAngle = (isAxisTitle) ? HALF_PI :\n computeViewAngle(dataPosition, dataPosition + axis);\n clipAngle = computeViewAngle(dataPosition, dataPosition + alignDir);\n\n axisAngle += (sin(axisAngle) < 0.0) ? PI : 0.0;\n clipAngle += (sin(clipAngle) < 0.0) ? PI : 0.0;\n\n flip = (dot(vec2(cos(axisAngle), sin(axisAngle)),\n vec2(sin(clipAngle),-cos(clipAngle))) > 0.0) ? 1.0 : 0.0;\n\n beta += applyAlignOption(clipAngle, flip * PI);\n }\n\n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n\n mat2 planeXform = scale * mat2(\n cos(beta), sin(beta),\n -sin(beta), cos(beta)\n );\n\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute clip position\n vec3 clipPosition = project(dataPosition);\n\n //Apply text offset in clip coordinates\n clipPosition += vec3(viewOffset, 0.0);\n\n //Done\n gl_Position = vec4(clipPosition, 1.0);\n}\n"]);var textFrag=glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]);exports.Q=function(gl){return createShader(gl,textVert,textFrag,null,[{name:'position',type:'vec3'}]);};var bgVert=glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n\n vec3 signAxis = sign(bounds[1] - bounds[0]);\n\n vec3 realNormal = signAxis * normal;\n\n if(dot(realNormal, enable) > 0.0) {\n vec3 minRange = min(bounds[0], bounds[1]);\n vec3 maxRange = max(bounds[0], bounds[1]);\n vec3 nPosition = mix(minRange, maxRange, 0.5 * (position + 1.0));\n gl_Position = projection * (view * (model * vec4(nPosition, 1.0)));\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n\n colorChannel = abs(realNormal);\n}\n"]);var bgFrag=glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] +\n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]);exports.bg=function(gl){return createShader(gl,bgVert,bgFrag,null,[{name:'position',type:'vec3'},{name:'normal',type:'vec3'}]);};/***/},/***/4935:/***/function(module,__unused_webpack_exports,__nested_webpack_require_264949__){"use strict";module.exports=createTextSprites;var createBuffer=__nested_webpack_require_264949__(2762);var createVAO=__nested_webpack_require_264949__(8116);var vectorizeText=__nested_webpack_require_264949__(4359);var createShader=__nested_webpack_require_264949__(1879)/* .text */.Q;var globals=window||process.global||{};var __TEXT_CACHE=globals.__TEXT_CACHE||{};globals.__TEXT_CACHE={};//Vertex buffer format for text is:
//
/// [x,y,z] = Spatial coordinate
//
var VERTEX_SIZE=3;function TextSprites(gl,shader,buffer,vao){this.gl=gl;this.shader=shader;this.buffer=buffer;this.vao=vao;this.tickOffset=this.tickCount=this.labelOffset=this.labelCount=null;}var proto=TextSprites.prototype;//Bind textures for rendering
var SHAPE=[0,0];proto.bind=function(model,view,projection,pixelScale){this.vao.bind();this.shader.bind();var uniforms=this.shader.uniforms;uniforms.model=model;uniforms.view=view;uniforms.projection=projection;uniforms.pixelScale=pixelScale;SHAPE[0]=this.gl.drawingBufferWidth;SHAPE[1]=this.gl.drawingBufferHeight;this.shader.uniforms.resolution=SHAPE;};proto.unbind=function(){this.vao.unbind();};proto.update=function(bounds,labels,labelFont,ticks,tickFont){var data=[];function addItem(t,text,font,size,lineSpacing,styletags){var fontKey=[font.style,font.weight,font.variant,font.family].join('_');var fontcache=__TEXT_CACHE[fontKey];if(!fontcache){fontcache=__TEXT_CACHE[fontKey]={};}var mesh=fontcache[text];if(!mesh){mesh=fontcache[text]=tryVectorizeText(text,{triangles:true,font:font.family,fontStyle:font.style,fontWeight:font.weight,fontVariant:font.variant,textAlign:'center',textBaseline:'middle',lineSpacing:lineSpacing,styletags:styletags});}var scale=(size||12)/12;var positions=mesh.positions;var cells=mesh.cells;for(var i=0,nc=cells.length;i=0;--j){var p=positions[c[j]];data.push(scale*p[0],-scale*p[1],t);}}}//Generate sprites for all 3 axes, store data in texture atlases
var tickOffset=[0,0,0];var tickCount=[0,0,0];var labelOffset=[0,0,0];var labelCount=[0,0,0];var lineSpacing=1.25;var styletags={breaklines:true,bolds:true,italics:true,subscripts:true,superscripts:true};for(var d=0;d<3;++d){//Generate label
labelOffset[d]=data.length/VERTEX_SIZE|0;addItem(0.5*(bounds[0][d]+bounds[1][d]),labels[d],labelFont[d],12,// labelFontSize
lineSpacing,styletags);labelCount[d]=(data.length/VERTEX_SIZE|0)-labelOffset[d];//Generate sprites for tick marks
tickOffset[d]=data.length/VERTEX_SIZE|0;for(var i=0;i=0){sigFigs=stepStr.length-u-1;}var shift=Math.pow(10,sigFigs);var x=Math.round(spacing*i*shift);var xstr=x+"";if(xstr.indexOf("e")>=0){return xstr;}var xi=x/shift,xf=x%shift;if(x<0){xi=-Math.ceil(xi)|0;xf=-xf|0;}else{xi=Math.floor(xi)|0;xf=xf|0;}var xis=""+xi;if(x<0){xis="-"+xis;}if(sigFigs){var xs=""+xf;while(xs.length=bounds[0][d];--t){ticks.push({x:t*tickSpacing[d],text:prettyPrint(tickSpacing[d],t)});}array.push(ticks);}return array;}function ticksEqual(ticksA,ticksB){for(var i=0;i<3;++i){if(ticksA[i].length!==ticksB[i].length){return false;}for(var j=0;jlen){throw new Error("gl-buffer: If resizing buffer, must not specify offset");}gl.bufferSubData(type,offset,data);return len;}function makeScratchTypeArray(array,dtype){var res=pool.malloc(array.length,dtype);var n=array.length;for(var i=0;i=0;--i){if(stride[i]!==n){return false;}n*=shape[i];}return true;}proto.update=function(array,offset){if(typeof offset!=="number"){offset=-1;}this.bind();if(typeof array==="object"&&typeof array.shape!=="undefined"){//ndarray
var dtype=array.dtype;if(SUPPORTED_TYPES.indexOf(dtype)<0){dtype="float32";}if(this.type===this.gl.ELEMENT_ARRAY_BUFFER){var ext=gl.getExtension('OES_element_index_uint');if(ext&&dtype!=="uint16"){dtype="uint32";}else{dtype="uint16";}}if(dtype===array.dtype&&isPacked(array.shape,array.stride)){if(array.offset===0&&array.data.length===array.shape[0]){this.length=updateTypeArray(this.gl,this.type,this.length,this.usage,array.data,offset);}else{this.length=updateTypeArray(this.gl,this.type,this.length,this.usage,array.data.subarray(array.offset,array.shape[0]),offset);}}else{var tmp=pool.malloc(array.size,dtype);var ndt=ndarray(tmp,array.shape);ops.assign(ndt,array);if(offset<0){this.length=updateTypeArray(this.gl,this.type,this.length,this.usage,tmp,offset);}else{this.length=updateTypeArray(this.gl,this.type,this.length,this.usage,tmp.subarray(0,array.size),offset);}pool.free(tmp);}}else if(Array.isArray(array)){//Vanilla array
var t;if(this.type===this.gl.ELEMENT_ARRAY_BUFFER){t=makeScratchTypeArray(array,"uint16");}else{t=makeScratchTypeArray(array,"float32");}if(offset<0){this.length=updateTypeArray(this.gl,this.type,this.length,this.usage,t,offset);}else{this.length=updateTypeArray(this.gl,this.type,this.length,this.usage,t.subarray(0,array.length),offset);}pool.free(t);}else if(typeof array==="object"&&typeof array.length==="number"){//Typed array
this.length=updateTypeArray(this.gl,this.type,this.length,this.usage,array,offset);}else if(typeof array==="number"||array===undefined){//Number/default
if(offset>=0){throw new Error("gl-buffer: Cannot specify offset when resizing buffer");}array=array|0;if(array<=0){array=1;}this.gl.bufferData(this.type,array|0,this.usage);this.length=array;}else{//Error, case should not happen
throw new Error("gl-buffer: Invalid data type");}};function createBuffer(gl,data,type,usage){type=type||gl.ARRAY_BUFFER;usage=usage||gl.DYNAMIC_DRAW;if(type!==gl.ARRAY_BUFFER&&type!==gl.ELEMENT_ARRAY_BUFFER){throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");}if(usage!==gl.DYNAMIC_DRAW&&usage!==gl.STATIC_DRAW&&usage!==gl.STREAM_DRAW){throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");}var handle=gl.createBuffer();var result=new GLBuffer(gl,type,handle,0,usage);result.update(data);return result;}module.exports=createBuffer;/***/},/***/6405:/***/function(module,__unused_webpack_exports,__nested_webpack_require_277635__){"use strict";var vec3=__nested_webpack_require_277635__(2931);module.exports=function(vectorfield,bounds){var positions=vectorfield.positions;var vectors=vectorfield.vectors;var geo={positions:[],vertexIntensity:[],vertexIntensityBounds:vectorfield.vertexIntensityBounds,vectors:[],cells:[],coneOffset:vectorfield.coneOffset,colormap:vectorfield.colormap};if(vectorfield.positions.length===0){if(bounds){bounds[0]=[0,0,0];bounds[1]=[0,0,0];}return geo;}// Compute bounding box for the dataset.
// Compute maximum velocity for the dataset to use for scaling the cones.
var maxNorm=0;var minX=Infinity,maxX=-Infinity;var minY=Infinity,maxY=-Infinity;var minZ=Infinity,maxZ=-Infinity;var p2=null;var u2=null;var positionVectors=[];var vectorScale=Infinity;var skipIt=false;var rawSizemodemode=vectorfield.coneSizemode==='raw';for(var i=0;imaxNorm){maxNorm=vec3.length(u);}if(i&&!rawSizemodemode){// Find vector scale [w/ units of time] using "successive" positions
// (not "adjacent" with would be O(n^2)),
//
// The vector scale corresponds to the minimum "time" to travel across two
// two adjacent positions at the average velocity of those two adjacent positions
var q=2*vec3.distance(p2,p)/(vec3.length(u2)+vec3.length(u));if(q){vectorScale=Math.min(vectorScale,q);skipIt=false;}else{skipIt=true;}}if(!skipIt){p2=p;u2=u;}positionVectors.push(u);}var minV=[minX,minY,minZ];var maxV=[maxX,maxY,maxZ];if(bounds){bounds[0]=minV;bounds[1]=maxV;}if(maxNorm===0){maxNorm=1;}// Inverted max norm would map vector with norm maxNorm to 1 coord space units in length
var invertedMaxNorm=1/maxNorm;if(!isFinite(vectorScale)){vectorScale=1.0;}geo.vectorScale=vectorScale;var coneScale=vectorfield.coneSize||(rawSizemodemode?1:0.5);if(vectorfield.absoluteConeSize){coneScale=vectorfield.absoluteConeSize*invertedMaxNorm;}geo.coneScale=coneScale;// Build the cone model.
for(var i=0,j=0;i=1;};proto.isTransparent=function(){return this.opacity<1;};proto.pickSlots=1;proto.setPickBase=function(id){this.pickId=id;};function genColormap(param){var colors=colormap({colormap:param,nshades:256,format:'rgba'});var result=new Uint8Array(256*4);for(var i=0;i<256;++i){var c=colors[i];for(var j=0;j<3;++j){result[4*i+j]=c[j];}result[4*i+3]=c[3]*255;}return ndarray(result,[256,256,4],[4,0,1]);}function takeZComponent(array){var n=array.length;var result=new Array(n);for(var i=0;i0){var shader=this.triShader;shader.bind();shader.uniforms=uniforms;this.triangleVAO.bind();gl.drawArrays(gl.TRIANGLES,0,this.triangleCount*3);this.triangleVAO.unbind();}};proto.drawPick=function(params){params=params||{};var gl=this.gl;var model=params.model||IDENTITY;var view=params.view||IDENTITY;var projection=params.projection||IDENTITY;var clipBounds=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]];for(var i=0;i<3;++i){clipBounds[0][i]=Math.max(clipBounds[0][i],this.clipBounds[0][i]);clipBounds[1][i]=Math.min(clipBounds[1][i],this.clipBounds[1][i]);}//Save camera parameters
this._model=[].slice.call(model);this._view=[].slice.call(view);this._projection=[].slice.call(projection);this._resolution=[gl.drawingBufferWidth,gl.drawingBufferHeight];var uniforms={model:model,view:view,projection:projection,clipBounds:clipBounds,tubeScale:this.tubeScale,vectorScale:this.vectorScale,coneScale:this.coneScale,coneOffset:this.coneOffset,pickId:this.pickId/255.0};var shader=this.pickShader;shader.bind();shader.uniforms=uniforms;if(this.triangleCount>0){this.triangleVAO.bind();gl.drawArrays(gl.TRIANGLES,0,this.triangleCount*3);this.triangleVAO.unbind();}};proto.pick=function(pickData){if(!pickData){return null;}if(pickData.id!==this.pickId){return null;}var cellId=pickData.value[0]+256*pickData.value[1]+65536*pickData.value[2];var cell=this.cells[cellId];var pos=this.positions[cell[1]].slice(0,3);var result={position:pos,dataCoordinate:pos,index:Math.floor(cell[1]/48)};if(this.traceType==='cone'){result.index=Math.floor(cell[1]/48);}else if(this.traceType==='streamtube'){result.intensity=this.intensity[cell[1]];result.velocity=this.vectors[cell[1]].slice(0,3);result.divergence=this.vectors[cell[1]][3];result.index=cellId;}return result;};proto.dispose=function(){this.texture.dispose();this.triShader.dispose();this.pickShader.dispose();this.triangleVAO.dispose();this.trianglePositions.dispose();this.triangleVectors.dispose();this.triangleColors.dispose();this.triangleUVs.dispose();this.triangleIds.dispose();};function createMeshShader(gl,shaders){var shader=createShader(gl,shaders.meshShader.vertex,shaders.meshShader.fragment,null,shaders.meshShader.attributes);shader.attributes.position.location=0;shader.attributes.color.location=2;shader.attributes.uv.location=3;shader.attributes.vector.location=4;return shader;}function createPickShader(gl,shaders){var shader=createShader(gl,shaders.pickShader.vertex,shaders.pickShader.fragment,null,shaders.pickShader.attributes);shader.attributes.position.location=0;shader.attributes.id.location=1;shader.attributes.vector.location=4;return shader;}function createVectorMesh(gl,params,opts){var shaders=opts.shaders;if(arguments.length===1){params=gl;gl=params.gl;}var triShader=createMeshShader(gl,shaders);var pickShader=createPickShader(gl,shaders);var meshTexture=createTexture(gl,ndarray(new Uint8Array([255,255,255,255]),[1,1,4]));meshTexture.generateMipmap();meshTexture.minFilter=gl.LINEAR_MIPMAP_LINEAR;meshTexture.magFilter=gl.LINEAR;var trianglePositions=createBuffer(gl);var triangleVectors=createBuffer(gl);var triangleColors=createBuffer(gl);var triangleUVs=createBuffer(gl);var triangleIds=createBuffer(gl);var triangleVAO=createVAO(gl,[{buffer:trianglePositions,type:gl.FLOAT,size:4},{buffer:triangleIds,type:gl.UNSIGNED_BYTE,size:4,normalized:true},{buffer:triangleColors,type:gl.FLOAT,size:4},{buffer:triangleUVs,type:gl.FLOAT,size:2},{buffer:triangleVectors,type:gl.FLOAT,size:4}]);var mesh=new VectorMesh(gl,meshTexture,triShader,pickShader,trianglePositions,triangleVectors,triangleIds,triangleColors,triangleUVs,triangleVAO,opts.traceType||'cone');mesh.update(params);return mesh;}module.exports=createVectorMesh;/***/},/***/614:/***/function(__unused_webpack_module,exports,__nested_webpack_require_291306__){var glslify=__nested_webpack_require_291306__(3236);var triVertSrc=glslify(["precision highp float;\n\nprecision highp float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n // Return up-vector for only-z vector.\n // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n // From the above if-statement we have ||a|| > 0 U ||b|| > 0.\n // Assign z = 0, x = -b, y = a:\n // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n return normalize(vec3(-v.y, v.x, 0.0));\n } else {\n return normalize(vec3(0.0, v.z, -v.y));\n }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n// segment + 0 top vertex\n// segment + 1 perimeter vertex a+1\n// segment + 2 perimeter vertex a\n// segment + 3 center base vertex\n// segment + 4 perimeter vertex a\n// segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n const float segmentCount = 8.0;\n\n float index = rawIndex - floor(rawIndex /\n (segmentCount * 6.0)) *\n (segmentCount * 6.0);\n\n float segment = floor(0.001 + index/6.0);\n float segmentIndex = index - (segment*6.0);\n\n normal = -normalize(d);\n\n if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n return mix(vec3(0.0), -d, coneOffset);\n }\n\n float nextAngle = (\n (segmentIndex > 0.99 && segmentIndex < 1.01) ||\n (segmentIndex > 4.99 && segmentIndex < 5.01)\n ) ? 1.0 : 0.0;\n float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n vec3 v1 = mix(d, vec3(0.0), coneOffset);\n vec3 v2 = v1 - d;\n\n vec3 u = getOrthogonalVector(d);\n vec3 v = normalize(cross(u, d));\n\n vec3 x = u * cos(angle) * length(d)*0.25;\n vec3 y = v * sin(angle) * length(d)*0.25;\n vec3 v3 = v2 + x + y;\n if (segmentIndex < 3.0) {\n vec3 tx = u * sin(angle);\n vec3 ty = v * -cos(angle);\n vec3 tangent = tx + ty;\n normal = normalize(cross(v3 - v1, tangent));\n }\n\n if (segmentIndex == 0.0) {\n return mix(d, vec3(0.0), coneOffset);\n }\n return v3;\n}\n\nattribute vec3 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\n\nuniform float vectorScale, coneScale, coneOffset;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 eyePosition, lightPosition;\n\nvarying vec3 f_normal, f_lightDirection, f_eyeDirection, f_data, f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n // Scale the vector magnitude to stay constant with\n // model & view changes.\n vec3 normal;\n vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal);\n vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * conePosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n f_lightDirection = lightPosition - cameraCoordinate.xyz;\n f_eyeDirection = eyePosition - cameraCoordinate.xyz;\n f_normal = normalize((vec4(normal, 0.0) * inverseModel).xyz);\n\n // vec4 m_position = model * vec4(conePosition, 1.0);\n vec4 t_position = view * conePosition;\n gl_Position = projection * t_position;\n\n f_color = color;\n f_data = conePosition.xyz;\n f_position = position.xyz;\n f_uv = uv;\n}\n"]);var triFragSrc=glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision highp float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal, f_lightDirection, f_eyeDirection, f_data, f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}\n"]);var pickVertSrc=glslify(["precision highp float;\n\nprecision highp float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n // Return up-vector for only-z vector.\n // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n // From the above if-statement we have ||a|| > 0 U ||b|| > 0.\n // Assign z = 0, x = -b, y = a:\n // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n return normalize(vec3(-v.y, v.x, 0.0));\n } else {\n return normalize(vec3(0.0, v.z, -v.y));\n }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n// segment + 0 top vertex\n// segment + 1 perimeter vertex a+1\n// segment + 2 perimeter vertex a\n// segment + 3 center base vertex\n// segment + 4 perimeter vertex a\n// segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n const float segmentCount = 8.0;\n\n float index = rawIndex - floor(rawIndex /\n (segmentCount * 6.0)) *\n (segmentCount * 6.0);\n\n float segment = floor(0.001 + index/6.0);\n float segmentIndex = index - (segment*6.0);\n\n normal = -normalize(d);\n\n if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n return mix(vec3(0.0), -d, coneOffset);\n }\n\n float nextAngle = (\n (segmentIndex > 0.99 && segmentIndex < 1.01) ||\n (segmentIndex > 4.99 && segmentIndex < 5.01)\n ) ? 1.0 : 0.0;\n float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n vec3 v1 = mix(d, vec3(0.0), coneOffset);\n vec3 v2 = v1 - d;\n\n vec3 u = getOrthogonalVector(d);\n vec3 v = normalize(cross(u, d));\n\n vec3 x = u * cos(angle) * length(d)*0.25;\n vec3 y = v * sin(angle) * length(d)*0.25;\n vec3 v3 = v2 + x + y;\n if (segmentIndex < 3.0) {\n vec3 tx = u * sin(angle);\n vec3 ty = v * -cos(angle);\n vec3 tangent = tx + ty;\n normal = normalize(cross(v3 - v1, tangent));\n }\n\n if (segmentIndex == 0.0) {\n return mix(d, vec3(0.0), coneOffset);\n }\n return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform float vectorScale, coneScale, coneOffset;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n vec3 normal;\n vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector.xyz), position.w, coneOffset, normal);\n vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n gl_Position = projection * (view * conePosition);\n f_id = id;\n f_position = position.xyz;\n}\n"]);var pickFragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);exports.meshShader={vertex:triVertSrc,fragment:triFragSrc,attributes:[{name:'position',type:'vec4'},{name:'color',type:'vec4'},{name:'uv',type:'vec2'},{name:'vector',type:'vec3'}]};exports.pickShader={vertex:pickVertSrc,fragment:pickFragSrc,attributes:[{name:'position',type:'vec4'},{name:'id',type:'vec4'},{name:'vector',type:'vec3'}]};/***/},/***/737:/***/function(module){module.exports={0:'NONE',1:'ONE',2:'LINE_LOOP',3:'LINE_STRIP',4:'TRIANGLES',5:'TRIANGLE_STRIP',6:'TRIANGLE_FAN',256:'DEPTH_BUFFER_BIT',512:'NEVER',513:'LESS',514:'EQUAL',515:'LEQUAL',516:'GREATER',517:'NOTEQUAL',518:'GEQUAL',519:'ALWAYS',768:'SRC_COLOR',769:'ONE_MINUS_SRC_COLOR',770:'SRC_ALPHA',771:'ONE_MINUS_SRC_ALPHA',772:'DST_ALPHA',773:'ONE_MINUS_DST_ALPHA',774:'DST_COLOR',775:'ONE_MINUS_DST_COLOR',776:'SRC_ALPHA_SATURATE',1024:'STENCIL_BUFFER_BIT',1028:'FRONT',1029:'BACK',1032:'FRONT_AND_BACK',1280:'INVALID_ENUM',1281:'INVALID_VALUE',1282:'INVALID_OPERATION',1285:'OUT_OF_MEMORY',1286:'INVALID_FRAMEBUFFER_OPERATION',2304:'CW',2305:'CCW',2849:'LINE_WIDTH',2884:'CULL_FACE',2885:'CULL_FACE_MODE',2886:'FRONT_FACE',2928:'DEPTH_RANGE',2929:'DEPTH_TEST',2930:'DEPTH_WRITEMASK',2931:'DEPTH_CLEAR_VALUE',2932:'DEPTH_FUNC',2960:'STENCIL_TEST',2961:'STENCIL_CLEAR_VALUE',2962:'STENCIL_FUNC',2963:'STENCIL_VALUE_MASK',2964:'STENCIL_FAIL',2965:'STENCIL_PASS_DEPTH_FAIL',2966:'STENCIL_PASS_DEPTH_PASS',2967:'STENCIL_REF',2968:'STENCIL_WRITEMASK',2978:'VIEWPORT',3024:'DITHER',3042:'BLEND',3088:'SCISSOR_BOX',3089:'SCISSOR_TEST',3106:'COLOR_CLEAR_VALUE',3107:'COLOR_WRITEMASK',3317:'UNPACK_ALIGNMENT',3333:'PACK_ALIGNMENT',3379:'MAX_TEXTURE_SIZE',3386:'MAX_VIEWPORT_DIMS',3408:'SUBPIXEL_BITS',3410:'RED_BITS',3411:'GREEN_BITS',3412:'BLUE_BITS',3413:'ALPHA_BITS',3414:'DEPTH_BITS',3415:'STENCIL_BITS',3553:'TEXTURE_2D',4352:'DONT_CARE',4353:'FASTEST',4354:'NICEST',5120:'BYTE',5121:'UNSIGNED_BYTE',5122:'SHORT',5123:'UNSIGNED_SHORT',5124:'INT',5125:'UNSIGNED_INT',5126:'FLOAT',5386:'INVERT',5890:'TEXTURE',6401:'STENCIL_INDEX',6402:'DEPTH_COMPONENT',6406:'ALPHA',6407:'RGB',6408:'RGBA',6409:'LUMINANCE',6410:'LUMINANCE_ALPHA',7680:'KEEP',7681:'REPLACE',7682:'INCR',7683:'DECR',7936:'VENDOR',7937:'RENDERER',7938:'VERSION',9728:'NEAREST',9729:'LINEAR',9984:'NEAREST_MIPMAP_NEAREST',9985:'LINEAR_MIPMAP_NEAREST',9986:'NEAREST_MIPMAP_LINEAR',9987:'LINEAR_MIPMAP_LINEAR',10240:'TEXTURE_MAG_FILTER',10241:'TEXTURE_MIN_FILTER',10242:'TEXTURE_WRAP_S',10243:'TEXTURE_WRAP_T',10497:'REPEAT',10752:'POLYGON_OFFSET_UNITS',16384:'COLOR_BUFFER_BIT',32769:'CONSTANT_COLOR',32770:'ONE_MINUS_CONSTANT_COLOR',32771:'CONSTANT_ALPHA',32772:'ONE_MINUS_CONSTANT_ALPHA',32773:'BLEND_COLOR',32774:'FUNC_ADD',32777:'BLEND_EQUATION_RGB',32778:'FUNC_SUBTRACT',32779:'FUNC_REVERSE_SUBTRACT',32819:'UNSIGNED_SHORT_4_4_4_4',32820:'UNSIGNED_SHORT_5_5_5_1',32823:'POLYGON_OFFSET_FILL',32824:'POLYGON_OFFSET_FACTOR',32854:'RGBA4',32855:'RGB5_A1',32873:'TEXTURE_BINDING_2D',32926:'SAMPLE_ALPHA_TO_COVERAGE',32928:'SAMPLE_COVERAGE',32936:'SAMPLE_BUFFERS',32937:'SAMPLES',32938:'SAMPLE_COVERAGE_VALUE',32939:'SAMPLE_COVERAGE_INVERT',32968:'BLEND_DST_RGB',32969:'BLEND_SRC_RGB',32970:'BLEND_DST_ALPHA',32971:'BLEND_SRC_ALPHA',33071:'CLAMP_TO_EDGE',33170:'GENERATE_MIPMAP_HINT',33189:'DEPTH_COMPONENT16',33306:'DEPTH_STENCIL_ATTACHMENT',33635:'UNSIGNED_SHORT_5_6_5',33648:'MIRRORED_REPEAT',33901:'ALIASED_POINT_SIZE_RANGE',33902:'ALIASED_LINE_WIDTH_RANGE',33984:'TEXTURE0',33985:'TEXTURE1',33986:'TEXTURE2',33987:'TEXTURE3',33988:'TEXTURE4',33989:'TEXTURE5',33990:'TEXTURE6',33991:'TEXTURE7',33992:'TEXTURE8',33993:'TEXTURE9',33994:'TEXTURE10',33995:'TEXTURE11',33996:'TEXTURE12',33997:'TEXTURE13',33998:'TEXTURE14',33999:'TEXTURE15',34000:'TEXTURE16',34001:'TEXTURE17',34002:'TEXTURE18',34003:'TEXTURE19',34004:'TEXTURE20',34005:'TEXTURE21',34006:'TEXTURE22',34007:'TEXTURE23',34008:'TEXTURE24',34009:'TEXTURE25',34010:'TEXTURE26',34011:'TEXTURE27',34012:'TEXTURE28',34013:'TEXTURE29',34014:'TEXTURE30',34015:'TEXTURE31',34016:'ACTIVE_TEXTURE',34024:'MAX_RENDERBUFFER_SIZE',34041:'DEPTH_STENCIL',34055:'INCR_WRAP',34056:'DECR_WRAP',34067:'TEXTURE_CUBE_MAP',34068:'TEXTURE_BINDING_CUBE_MAP',34069:'TEXTURE_CUBE_MAP_POSITIVE_X',34070:'TEXTURE_CUBE_MAP_NEGATIVE_X',34071:'TEXTURE_CUBE_MAP_POSITIVE_Y',34072:'TEXTURE_CUBE_MAP_NEGATIVE_Y',34073:'TEXTURE_CUBE_MAP_POSITIVE_Z',34074:'TEXTURE_CUBE_MAP_NEGATIVE_Z',34076:'MAX_CUBE_MAP_TEXTURE_SIZE',34338:'VERTEX_ATTRIB_ARRAY_ENABLED',34339:'VERTEX_ATTRIB_ARRAY_SIZE',34340:'VERTEX_ATTRIB_ARRAY_STRIDE',34341:'VERTEX_ATTRIB_ARRAY_TYPE',34342:'CURRENT_VERTEX_ATTRIB',34373:'VERTEX_ATTRIB_ARRAY_POINTER',34466:'NUM_COMPRESSED_TEXTURE_FORMATS',34467:'COMPRESSED_TEXTURE_FORMATS',34660:'BUFFER_SIZE',34661:'BUFFER_USAGE',34816:'STENCIL_BACK_FUNC',34817:'STENCIL_BACK_FAIL',34818:'STENCIL_BACK_PASS_DEPTH_FAIL',34819:'STENCIL_BACK_PASS_DEPTH_PASS',34877:'BLEND_EQUATION_ALPHA',34921:'MAX_VERTEX_ATTRIBS',34922:'VERTEX_ATTRIB_ARRAY_NORMALIZED',34930:'MAX_TEXTURE_IMAGE_UNITS',34962:'ARRAY_BUFFER',34963:'ELEMENT_ARRAY_BUFFER',34964:'ARRAY_BUFFER_BINDING',34965:'ELEMENT_ARRAY_BUFFER_BINDING',34975:'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',35040:'STREAM_DRAW',35044:'STATIC_DRAW',35048:'DYNAMIC_DRAW',35632:'FRAGMENT_SHADER',35633:'VERTEX_SHADER',35660:'MAX_VERTEX_TEXTURE_IMAGE_UNITS',35661:'MAX_COMBINED_TEXTURE_IMAGE_UNITS',35663:'SHADER_TYPE',35664:'FLOAT_VEC2',35665:'FLOAT_VEC3',35666:'FLOAT_VEC4',35667:'INT_VEC2',35668:'INT_VEC3',35669:'INT_VEC4',35670:'BOOL',35671:'BOOL_VEC2',35672:'BOOL_VEC3',35673:'BOOL_VEC4',35674:'FLOAT_MAT2',35675:'FLOAT_MAT3',35676:'FLOAT_MAT4',35678:'SAMPLER_2D',35680:'SAMPLER_CUBE',35712:'DELETE_STATUS',35713:'COMPILE_STATUS',35714:'LINK_STATUS',35715:'VALIDATE_STATUS',35716:'INFO_LOG_LENGTH',35717:'ATTACHED_SHADERS',35718:'ACTIVE_UNIFORMS',35719:'ACTIVE_UNIFORM_MAX_LENGTH',35720:'SHADER_SOURCE_LENGTH',35721:'ACTIVE_ATTRIBUTES',35722:'ACTIVE_ATTRIBUTE_MAX_LENGTH',35724:'SHADING_LANGUAGE_VERSION',35725:'CURRENT_PROGRAM',36003:'STENCIL_BACK_REF',36004:'STENCIL_BACK_VALUE_MASK',36005:'STENCIL_BACK_WRITEMASK',36006:'FRAMEBUFFER_BINDING',36007:'RENDERBUFFER_BINDING',36048:'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',36049:'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',36050:'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',36051:'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',36053:'FRAMEBUFFER_COMPLETE',36054:'FRAMEBUFFER_INCOMPLETE_ATTACHMENT',36055:'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT',36057:'FRAMEBUFFER_INCOMPLETE_DIMENSIONS',36061:'FRAMEBUFFER_UNSUPPORTED',36064:'COLOR_ATTACHMENT0',36096:'DEPTH_ATTACHMENT',36128:'STENCIL_ATTACHMENT',36160:'FRAMEBUFFER',36161:'RENDERBUFFER',36162:'RENDERBUFFER_WIDTH',36163:'RENDERBUFFER_HEIGHT',36164:'RENDERBUFFER_INTERNAL_FORMAT',36168:'STENCIL_INDEX8',36176:'RENDERBUFFER_RED_SIZE',36177:'RENDERBUFFER_GREEN_SIZE',36178:'RENDERBUFFER_BLUE_SIZE',36179:'RENDERBUFFER_ALPHA_SIZE',36180:'RENDERBUFFER_DEPTH_SIZE',36181:'RENDERBUFFER_STENCIL_SIZE',36194:'RGB565',36336:'LOW_FLOAT',36337:'MEDIUM_FLOAT',36338:'HIGH_FLOAT',36339:'LOW_INT',36340:'MEDIUM_INT',36341:'HIGH_INT',36346:'SHADER_COMPILER',36347:'MAX_VERTEX_UNIFORM_VECTORS',36348:'MAX_VARYING_VECTORS',36349:'MAX_FRAGMENT_UNIFORM_VECTORS',37440:'UNPACK_FLIP_Y_WEBGL',37441:'UNPACK_PREMULTIPLY_ALPHA_WEBGL',37442:'CONTEXT_LOST_WEBGL',37443:'UNPACK_COLORSPACE_CONVERSION_WEBGL',37444:'BROWSER_DEFAULT_WEBGL'};/***/},/***/5171:/***/function(module,__unused_webpack_exports,__nested_webpack_require_309403__){var gl10=__nested_webpack_require_309403__(737);module.exports=function lookupConstant(number){return gl10[number];};/***/},/***/9165:/***/function(module,__unused_webpack_exports,__nested_webpack_require_309590__){"use strict";module.exports=createErrorBars;var createBuffer=__nested_webpack_require_309590__(2762);var createVAO=__nested_webpack_require_309590__(8116);var createShader=__nested_webpack_require_309590__(3436);var IDENTITY=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function ErrorBars(gl,buffer,vao,shader){this.gl=gl;this.shader=shader;this.buffer=buffer;this.vao=vao;this.pixelRatio=1;this.bounds=[[Infinity,Infinity,Infinity],[-Infinity,-Infinity,-Infinity]];this.clipBounds=[[-Infinity,-Infinity,-Infinity],[Infinity,Infinity,Infinity]];this.lineWidth=[1,1,1];this.capSize=[10,10,10];this.lineCount=[0,0,0];this.lineOffset=[0,0,0];this.opacity=1;this.hasAlpha=false;}var proto=ErrorBars.prototype;proto.isOpaque=function(){return!this.hasAlpha;};proto.isTransparent=function(){return this.hasAlpha;};proto.drawTransparent=proto.draw=function(cameraParams){var gl=this.gl;var uniforms=this.shader.uniforms;this.shader.bind();var view=uniforms.view=cameraParams.view||IDENTITY;var projection=uniforms.projection=cameraParams.projection||IDENTITY;uniforms.model=cameraParams.model||IDENTITY;uniforms.clipBounds=this.clipBounds;uniforms.opacity=this.opacity;var cx=view[12];var cy=view[13];var cz=view[14];var cw=view[15];var isOrtho=cameraParams._ortho||false;var orthoFix=isOrtho?2:1;// double up padding for orthographic ticks & labels
var pixelScaleF=orthoFix*this.pixelRatio*(projection[3]*cx+projection[7]*cy+projection[11]*cz+projection[15]*cw)/gl.drawingBufferHeight;this.vao.bind();for(var i=0;i<3;++i){gl.lineWidth(this.lineWidth[i]*this.pixelRatio);uniforms.capSize=this.capSize[i]*pixelScaleF;if(this.lineCount[i]){gl.drawArrays(gl.LINES,this.lineOffset[i],this.lineCount[i]);}}this.vao.unbind();};function updateBounds(bounds,point){for(var i=0;i<3;++i){bounds[0][i]=Math.min(bounds[0][i],point[i]);bounds[1][i]=Math.max(bounds[1][i],point[i]);}}var FACE_TABLE=function(){var table=new Array(3);for(var d=0;d<3;++d){var row=[];for(var j=1;j<=2;++j){for(var s=-1;s<=1;s+=2){var u=(j+d)%3;var y=[0,0,0];y[u]=s;row.push(y);}}table[d]=row;}return table;}();function emitFace(verts,x,c,d){var offsets=FACE_TABLE[d];for(var i=0;i0){var x=p.slice();x[j]+=e[1][j];verts.push(p[0],p[1],p[2],c[0],c[1],c[2],c[3],0,0,0,x[0],x[1],x[2],c[0],c[1],c[2],c[3],0,0,0);updateBounds(this.bounds,x);vertexCount+=2+emitFace(verts,x,c,j);}}this.lineCount[j]=vertexCount-this.lineOffset[j];}this.buffer.update(verts);}};proto.dispose=function(){this.shader.dispose();this.buffer.dispose();this.vao.dispose();};function createErrorBars(options){var gl=options.gl;var buffer=createBuffer(gl);var vao=createVAO(gl,[{buffer:buffer,type:gl.FLOAT,size:3,offset:0,stride:40},{buffer:buffer,type:gl.FLOAT,size:4,offset:12,stride:40},{buffer:buffer,type:gl.FLOAT,size:3,offset:28,stride:40}]);var shader=createShader(gl);shader.attributes.position.location=0;shader.attributes.color.location=1;shader.attributes.offset.location=2;var result=new ErrorBars(gl,buffer,vao,shader);result.update(options);return result;}/***/},/***/3436:/***/function(module,__unused_webpack_exports,__nested_webpack_require_314229__){"use strict";var glslify=__nested_webpack_require_314229__(3236);var createShader=__nested_webpack_require_314229__(9405);var vertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n vec4 worldPosition = model * vec4(position, 1.0);\n worldPosition = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n gl_Position = projection * (view * worldPosition);\n fragColor = color;\n fragPosition = position;\n}"]);var fragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if (\n outOfRange(clipBounds[0], clipBounds[1], fragPosition) ||\n fragColor.a * opacity == 0.\n ) discard;\n\n gl_FragColor = opacity * fragColor;\n}"]);module.exports=function(gl){return createShader(gl,vertSrc,fragSrc,null,[{name:'position',type:'vec3'},{name:'color',type:'vec4'},{name:'offset',type:'vec3'}]);};/***/},/***/2260:/***/function(module,__unused_webpack_exports,__nested_webpack_require_315954__){"use strict";var createTexture=__nested_webpack_require_315954__(7766);module.exports=createFBO;var colorAttachmentArrays=null;var FRAMEBUFFER_UNSUPPORTED;var FRAMEBUFFER_INCOMPLETE_ATTACHMENT;var FRAMEBUFFER_INCOMPLETE_DIMENSIONS;var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;function saveFBOState(gl){var fbo=gl.getParameter(gl.FRAMEBUFFER_BINDING);var rbo=gl.getParameter(gl.RENDERBUFFER_BINDING);var tex=gl.getParameter(gl.TEXTURE_BINDING_2D);return[fbo,rbo,tex];}function restoreFBOState(gl,data){gl.bindFramebuffer(gl.FRAMEBUFFER,data[0]);gl.bindRenderbuffer(gl.RENDERBUFFER,data[1]);gl.bindTexture(gl.TEXTURE_2D,data[2]);}function lazyInitColorAttachments(gl,ext){var maxColorAttachments=gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL);colorAttachmentArrays=new Array(maxColorAttachments+1);for(var i=0;i<=maxColorAttachments;++i){var x=new Array(maxColorAttachments);for(var j=0;j1){ext.drawBuffersWEBGL(colorAttachmentArrays[numColors]);}//Allocate depth/stencil buffers
var WEBGL_depth_texture=gl.getExtension('WEBGL_depth_texture');if(WEBGL_depth_texture){if(useStencil){fbo.depth=initTexture(gl,width,height,WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL,gl.DEPTH_STENCIL,gl.DEPTH_STENCIL_ATTACHMENT);}else if(useDepth){fbo.depth=initTexture(gl,width,height,gl.UNSIGNED_SHORT,gl.DEPTH_COMPONENT,gl.DEPTH_ATTACHMENT);}}else{if(useDepth&&useStencil){fbo._depth_rb=initRenderBuffer(gl,width,height,gl.DEPTH_STENCIL,gl.DEPTH_STENCIL_ATTACHMENT);}else if(useDepth){fbo._depth_rb=initRenderBuffer(gl,width,height,gl.DEPTH_COMPONENT16,gl.DEPTH_ATTACHMENT);}else if(useStencil){fbo._depth_rb=initRenderBuffer(gl,width,height,gl.STENCIL_INDEX,gl.STENCIL_ATTACHMENT);}}//Check frame buffer state
var status=gl.checkFramebufferStatus(gl.FRAMEBUFFER);if(status!==gl.FRAMEBUFFER_COMPLETE){//Release all partially allocated resources
fbo._destroyed=true;//Release all resources
gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.deleteFramebuffer(fbo.handle);fbo.handle=null;if(fbo.depth){fbo.depth.dispose();fbo.depth=null;}if(fbo._depth_rb){gl.deleteRenderbuffer(fbo._depth_rb);fbo._depth_rb=null;}for(var i=0;imaxFBOSize||h<0||h>maxFBOSize){throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions');}//Update shape
fbo._shape[0]=w;fbo._shape[1]=h;//Save framebuffer state
var state=saveFBOState(gl);//Resize framebuffer attachments
for(var i=0;imaxFBOSize||height<0||height>maxFBOSize){throw new Error('gl-fbo: Parameters are too large for FBO');}//Handle each option type
options=options||{};//Figure out number of color buffers to use
var numColors=1;if('color'in options){numColors=Math.max(options.color|0,0);if(numColors<0){throw new Error('gl-fbo: Must specify a nonnegative number of colors');}if(numColors>1){//Check if multiple render targets supported
if(!WEBGL_draw_buffers){throw new Error('gl-fbo: Multiple draw buffer extension not supported');}else if(numColors>gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)){throw new Error('gl-fbo: Context does not support '+numColors+' draw buffers');}}}//Determine whether to use floating point textures
var colorType=gl.UNSIGNED_BYTE;var OES_texture_float=gl.getExtension('OES_texture_float');if(options.float&&numColors>0){if(!OES_texture_float){throw new Error('gl-fbo: Context does not support floating point textures');}colorType=gl.FLOAT;}else if(options.preferFloat&&numColors>0){if(OES_texture_float){colorType=gl.FLOAT;}}//Check if we should use depth buffer
var useDepth=true;if('depth'in options){useDepth=!!options.depth;}//Check if we should use a stencil buffer
var useStencil=false;if('stencil'in options){useStencil=!!options.stencil;}return new Framebuffer(gl,width,height,colorType,numColors,useDepth,useStencil,WEBGL_draw_buffers);}/***/},/***/2992:/***/function(module,__unused_webpack_exports,__nested_webpack_require_326414__){var sprintf=__nested_webpack_require_326414__(3387).sprintf;var glConstants=__nested_webpack_require_326414__(5171);var shaderName=__nested_webpack_require_326414__(1848);var addLineNumbers=__nested_webpack_require_326414__(1085);module.exports=formatCompilerError;function formatCompilerError(errLog,src,type){"use strict";var name=shaderName(src)||'of unknown name (see npm glsl-shader-name)';var typeName='unknown type';if(type!==undefined){typeName=type===glConstants.FRAGMENT_SHADER?'fragment':'vertex';}var longForm=sprintf('Error compiling %s shader %s:\n',typeName,name);var shortForm=sprintf("%s%s",longForm,errLog);var errorStrings=errLog.split('\n');var errors={};for(var i=0;i>i*8&0xff;}this.pickOffset=pickOffset;shader.bind();var uniforms=shader.uniforms;uniforms.viewTransform=MATRIX;uniforms.pickOffset=PICK_VECTOR;uniforms.shape=this.shape;var attributes=shader.attributes;this.positionBuffer.bind();attributes.position.pointer();this.weightBuffer.bind();attributes.weight.pointer(gl.UNSIGNED_BYTE,false);this.idBuffer.bind();attributes.pickId.pointer(gl.UNSIGNED_BYTE,false);gl.drawArrays(gl.TRIANGLES,0,numVertices);return pickOffset+this.shape[0]*this.shape[1];};}();proto.pick=function(x,y,value){var pickOffset=this.pickOffset;var pointCount=this.shape[0]*this.shape[1];if(value=pickOffset+pointCount){return null;}var pointId=value-pickOffset;var xData=this.xData;var yData=this.yData;return{object:this,pointId:pointId,dataCoord:[xData[pointId%this.shape[0]],yData[pointId/this.shape[0]|0]]};};proto.update=function(options){options=options||{};var shape=options.shape||[0,0];var x=options.x||iota(shape[0]);var y=options.y||iota(shape[1]);var z=options.z||new Float32Array(shape[0]*shape[1]);var isSmooth=options.zsmooth!==false;this.xData=x;this.yData=y;var colorLevels=options.colorLevels||[0];var colorValues=options.colorValues||[0,0,0,1];var colorCount=colorLevels.length;var bounds=this.bounds;var lox,loy,hix,hiy;if(isSmooth){lox=bounds[0]=x[0];loy=bounds[1]=y[0];hix=bounds[2]=x[x.length-1];hiy=bounds[3]=y[y.length-1];}else{// To get squares to centre on data values
lox=bounds[0]=x[0]+(x[1]-x[0])/2;// starting x value
loy=bounds[1]=y[0]+(y[1]-y[0])/2;// starting y value
// Bounds needs to add half a square on each end
hix=bounds[2]=x[x.length-1]+(x[x.length-1]-x[x.length-2])/2;hiy=bounds[3]=y[y.length-1]+(y[y.length-1]-y[y.length-2])/2;// N.B. Resolution = 1 / range
}var xs=1.0/(hix-lox);var ys=1.0/(hiy-loy);var numX=shape[0];var numY=shape[1];this.shape=[numX,numY];var numVerts=(isSmooth?(numX-1)*(numY-1):numX*numY)*(WEIGHTS.length>>>1);this.numVertices=numVerts;var colors=pool.mallocUint8(numVerts*4);var positions=pool.mallocFloat32(numVerts*2);var weights=pool.mallocUint8(numVerts*2);var ids=pool.mallocUint32(numVerts);var ptr=0;var ni=isSmooth?numX-1:numX;var nj=isSmooth?numY-1:numY;for(var j=0;j max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if (\n outOfRange(clipBounds[0], clipBounds[1], worldPosition) ||\n fragColor.a * opacity == 0.\n ) discard;\n\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]);var pickFrag=glslify(["precision highp float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\n// https://github.com/mikolalysenko/glsl-read-float/blob/master/index.glsl\nvec4 packFloat(float v) {\n float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n float e = floor(log2(av));\n float m = av * pow(2.0, -e) - 1.0;\n\n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n\n //Unpack exponent\n float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0;\n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], worldPosition)) discard;\n\n gl_FragColor = vec4(pickId/255.0, packFloat(pixelArcLength).xyz);\n}"]);var ATTRIBUTES=[{name:'position',type:'vec3'},{name:'nextPosition',type:'vec3'},{name:'arcLength',type:'float'},{name:'lineWidth',type:'float'},{name:'color',type:'vec4'}];exports.createShader=function(gl){return createShader(gl,vertSrc,forwardFrag,null,ATTRIBUTES);};exports.createPickShader=function(gl){return createShader(gl,vertSrc,pickFrag,null,ATTRIBUTES);};/***/},/***/5714:/***/function(module,__unused_webpack_exports,__nested_webpack_require_340765__){"use strict";module.exports=createLinePlot;var createBuffer=__nested_webpack_require_340765__(2762);var createVAO=__nested_webpack_require_340765__(8116);var createTexture=__nested_webpack_require_340765__(7766);var UINT8_VIEW=new Uint8Array(4);var FLOAT_VIEW=new Float32Array(UINT8_VIEW.buffer);// https://github.com/mikolalysenko/glsl-read-float/blob/master/index.js
function unpackFloat(x,y,z,w){UINT8_VIEW[0]=w;UINT8_VIEW[1]=z;UINT8_VIEW[2]=y;UINT8_VIEW[3]=x;return FLOAT_VIEW[0];}var bsearch=__nested_webpack_require_340765__(2478);var ndarray=__nested_webpack_require_340765__(9618);var shaders=__nested_webpack_require_340765__(7319);var createShader=shaders.createShader;var createPickShader=shaders.createPickShader;var identity=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function distance(a,b){var s=0.0;for(var i=0;i<3;++i){var d=a[i]-b[i];s+=d*d;}return Math.sqrt(s);}function filterClipBounds(bounds){var result=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]];for(var i=0;i<3;++i){result[0][i]=Math.max(bounds[0][i],result[0][i]);result[1][i]=Math.min(bounds[1][i],result[1][i]);}return result;}function PickResult(tau,position,index,dataCoordinate){this.arcLength=tau;this.position=position;this.index=index;this.dataCoordinate=dataCoordinate;}function LinePlot(gl,shader,pickShader,buffer,vao,texture){this.gl=gl;this.shader=shader;this.pickShader=pickShader;this.buffer=buffer;this.vao=vao;this.clipBounds=[[-Infinity,-Infinity,-Infinity],[Infinity,Infinity,Infinity]];this.points=[];this.arcLength=[];this.vertexCount=0;this.bounds=[[0,0,0],[0,0,0]];this.pickId=0;this.lineWidth=1;this.texture=texture;this.dashScale=1;this.opacity=1;this.hasAlpha=false;this.dirty=true;this.pixelRatio=1;}var proto=LinePlot.prototype;proto.isTransparent=function(){return this.hasAlpha;};proto.isOpaque=function(){return!this.hasAlpha;};proto.pickSlots=1;proto.setPickBase=function(id){this.pickId=id;};proto.drawTransparent=proto.draw=function(camera){if(!this.vertexCount)return;var gl=this.gl;var shader=this.shader;var vao=this.vao;shader.bind();shader.uniforms={model:camera.model||identity,view:camera.view||identity,projection:camera.projection||identity,clipBounds:filterClipBounds(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[gl.drawingBufferWidth,gl.drawingBufferHeight],pixelRatio:this.pixelRatio};vao.bind();vao.draw(gl.TRIANGLE_STRIP,this.vertexCount);vao.unbind();};proto.drawPick=function(camera){if(!this.vertexCount)return;var gl=this.gl;var shader=this.pickShader;var vao=this.vao;shader.bind();shader.uniforms={model:camera.model||identity,view:camera.view||identity,projection:camera.projection||identity,pickId:this.pickId,clipBounds:filterClipBounds(this.clipBounds),screenShape:[gl.drawingBufferWidth,gl.drawingBufferHeight],pixelRatio:this.pixelRatio};vao.bind();vao.draw(gl.TRIANGLE_STRIP,this.vertexCount);vao.unbind();};proto.update=function(options){var i,j;this.dirty=true;var connectGaps=!!options.connectGaps;if('dashScale'in options){this.dashScale=options.dashScale;}this.hasAlpha=false;// default to no transparent draw
if('opacity'in options){this.opacity=+options.opacity;if(this.opacity<1){this.hasAlpha=true;}}// Recalculate buffer data
var buffer=[];var arcLengthArray=[];var pointArray=[];var arcLength=0.0;var vertexCount=0;var bounds=[[Infinity,Infinity,Infinity],[-Infinity,-Infinity,-Infinity]];var positions=options.position||options.positions;if(positions){// Default color
var colors=options.color||options.colors||[0,0,0,1];var lineWidth=options.lineWidth||1;var hadGap=false;fill_loop:for(i=1;i0){for(var k=0;k<24;++k){buffer.push(buffer[buffer.length-12]);}vertexCount+=2;hadGap=true;}continue fill_loop;}bounds[0][j]=Math.min(bounds[0][j],a[j],b[j]);bounds[1][j]=Math.max(bounds[1][j],a[j],b[j]);}var acolor,bcolor;if(Array.isArray(colors[0])){acolor=colors.length>i-1?colors[i-1]:// using index value
colors.length>0?colors[colors.length-1]:// using last item
[0,0,0,1];// using black
bcolor=colors.length>i?colors[i]:// using index value
colors.length>0?colors[colors.length-1]:// using last item
[0,0,0,1];// using black
}else{acolor=bcolor=colors;}if(acolor.length===3){acolor=[acolor[0],acolor[1],acolor[2],1];}if(bcolor.length===3){bcolor=[bcolor[0],bcolor[1],bcolor[2],1];}if(!this.hasAlpha&&acolor[3]<1)this.hasAlpha=true;var w0;if(Array.isArray(lineWidth)){w0=lineWidth.length>i-1?lineWidth[i-1]:// using index value
lineWidth.length>0?lineWidth[lineWidth.length-1]:// using last item
[0,0,0,1];// using black
}else{w0=lineWidth;}var t0=arcLength;arcLength+=distance(a,b);if(hadGap){for(j=0;j<2;++j){buffer.push(a[0],a[1],a[2],b[0],b[1],b[2],t0,w0,acolor[0],acolor[1],acolor[2],acolor[3]);}vertexCount+=2;hadGap=false;}buffer.push(a[0],a[1],a[2],b[0],b[1],b[2],t0,w0,acolor[0],acolor[1],acolor[2],acolor[3],a[0],a[1],a[2],b[0],b[1],b[2],t0,-w0,acolor[0],acolor[1],acolor[2],acolor[3],b[0],b[1],b[2],a[0],a[1],a[2],arcLength,-w0,bcolor[0],bcolor[1],bcolor[2],bcolor[3],b[0],b[1],b[2],a[0],a[1],a[2],arcLength,w0,bcolor[0],bcolor[1],bcolor[2],bcolor[3]);vertexCount+=4;}}this.buffer.update(buffer);arcLengthArray.push(arcLength);pointArray.push(positions[positions.length-1].slice());this.bounds=bounds;this.vertexCount=vertexCount;this.points=pointArray;this.arcLength=arcLengthArray;if('dashes'in options){var dashArray=options.dashes;// Calculate prefix sum
var prefixSum=dashArray.slice();prefixSum.unshift(0);for(i=1;i1.0001){return null;}s+=weights[i];}if(Math.abs(s-1.0)>0.001){return null;}return[closestIndex,interpolate(simplex,weights),weights];}/***/},/***/840:/***/function(__unused_webpack_module,exports,__nested_webpack_require_365949__){var glslify=__nested_webpack_require_365949__(3236);var triVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection\n , inverseModel;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvec4 project(vec3 p) {\n return projection * (view * (model * vec4(p, 1.0)));\n}\n\nvoid main() {\n gl_Position = project(position);\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * vec4(position , 1.0);\n cameraCoordinate.xyz /= cameraCoordinate.w;\n f_lightDirection = lightPosition - cameraCoordinate.xyz;\n f_eyeDirection = eyePosition - cameraCoordinate.xyz;\n f_normal = normalize((vec4(normal, 0.0) * inverseModel).xyz);\n\n f_color = color;\n f_data = position;\n f_uv = uv;\n}\n"]);var triFragSrc=glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision highp float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n//#pragma glslify: beckmann = require(glsl-specular-beckmann) // used in gl-surface3d\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if (f_color.a == 0.0 ||\n outOfRange(clipBounds[0], clipBounds[1], f_data)\n ) discard;\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n //float specular = max(0.0, beckmann(L, V, N, roughness)); // used in gl-surface3d\n\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = vec4(f_color.rgb, 1.0) * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * f_color.a;\n}\n"]);var edgeVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * (view * (model * vec4(position, 1.0)));\n f_color = color;\n f_data = position;\n f_uv = uv;\n}"]);var edgeFragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], f_data)) discard;\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]);var pointVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n gl_Position = vec4(0.0, 0.0 ,0.0 ,0.0);\n } else {\n gl_Position = projection * (view * (model * vec4(position, 1.0)));\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}"]);var pointFragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5, 0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]);var pickVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * (view * (model * vec4(position, 1.0)));\n f_id = id;\n f_position = position;\n}"]);var pickFragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);var pickPointVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n gl_Position = vec4(0.0, 0.0, 0.0, 0.0);\n } else {\n gl_Position = projection * (view * (model * vec4(position, 1.0)));\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}"]);var contourVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * (view * (model * vec4(position, 1.0)));\n}"]);var contourFragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor, 1.0);\n}\n"]);exports.meshShader={vertex:triVertSrc,fragment:triFragSrc,attributes:[{name:'position',type:'vec3'},{name:'normal',type:'vec3'},{name:'color',type:'vec4'},{name:'uv',type:'vec2'}]};exports.wireShader={vertex:edgeVertSrc,fragment:edgeFragSrc,attributes:[{name:'position',type:'vec3'},{name:'color',type:'vec4'},{name:'uv',type:'vec2'}]};exports.pointShader={vertex:pointVertSrc,fragment:pointFragSrc,attributes:[{name:'position',type:'vec3'},{name:'color',type:'vec4'},{name:'uv',type:'vec2'},{name:'pointSize',type:'float'}]};exports.pickShader={vertex:pickVertSrc,fragment:pickFragSrc,attributes:[{name:'position',type:'vec3'},{name:'id',type:'vec4'}]};exports.pointPickShader={vertex:pickPointVertSrc,fragment:pickFragSrc,attributes:[{name:'position',type:'vec3'},{name:'pointSize',type:'float'},{name:'id',type:'vec4'}]};exports.contourShader={vertex:contourVertSrc,fragment:contourFragSrc,attributes:[{name:'position',type:'vec3'}]};/***/},/***/7201:/***/function(module,__unused_webpack_exports,__nested_webpack_require_376362__){"use strict";var DEFAULT_VERTEX_NORMALS_EPSILON=1e-6;// may be too large if triangles are very small
var DEFAULT_FACE_NORMALS_EPSILON=1e-6;var createShader=__nested_webpack_require_376362__(9405);var createBuffer=__nested_webpack_require_376362__(2762);var createVAO=__nested_webpack_require_376362__(8116);var createTexture=__nested_webpack_require_376362__(7766);var normals=__nested_webpack_require_376362__(8406);var multiply=__nested_webpack_require_376362__(6760);var invert=__nested_webpack_require_376362__(7608);var ndarray=__nested_webpack_require_376362__(9618);var colormap=__nested_webpack_require_376362__(6729);var getContour=__nested_webpack_require_376362__(7765);var pool=__nested_webpack_require_376362__(1888);var shaders=__nested_webpack_require_376362__(840);var closestPoint=__nested_webpack_require_376362__(7626);var meshShader=shaders.meshShader;var wireShader=shaders.wireShader;var pointShader=shaders.pointShader;var pickShader=shaders.pickShader;var pointPickShader=shaders.pointPickShader;var contourShader=shaders.contourShader;var IDENTITY=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function SimplicialMesh(gl,texture,triShader,lineShader,pointShader,pickShader,pointPickShader,contourShader,trianglePositions,triangleIds,triangleColors,triangleUVs,triangleNormals,triangleVAO,edgePositions,edgeIds,edgeColors,edgeUVs,edgeVAO,pointPositions,pointIds,pointColors,pointUVs,pointSizes,pointVAO,contourPositions,contourVAO){this.gl=gl;this.pixelRatio=1;this.cells=[];this.positions=[];this.intensity=[];this.texture=texture;this.dirty=true;this.triShader=triShader;this.lineShader=lineShader;this.pointShader=pointShader;this.pickShader=pickShader;this.pointPickShader=pointPickShader;this.contourShader=contourShader;this.trianglePositions=trianglePositions;this.triangleColors=triangleColors;this.triangleNormals=triangleNormals;this.triangleUVs=triangleUVs;this.triangleIds=triangleIds;this.triangleVAO=triangleVAO;this.triangleCount=0;this.lineWidth=1;this.edgePositions=edgePositions;this.edgeColors=edgeColors;this.edgeUVs=edgeUVs;this.edgeIds=edgeIds;this.edgeVAO=edgeVAO;this.edgeCount=0;this.pointPositions=pointPositions;this.pointColors=pointColors;this.pointUVs=pointUVs;this.pointSizes=pointSizes;this.pointIds=pointIds;this.pointVAO=pointVAO;this.pointCount=0;this.contourLineWidth=1;this.contourPositions=contourPositions;this.contourVAO=contourVAO;this.contourCount=0;this.contourColor=[0,0,0];this.contourEnable=true;this.pickVertex=true;this.pickId=1;this.bounds=[[Infinity,Infinity,Infinity],[-Infinity,-Infinity,-Infinity]];this.clipBounds=[[-Infinity,-Infinity,-Infinity],[Infinity,Infinity,Infinity]];this.lightPosition=[1e5,1e5,0];this.ambientLight=0.8;this.diffuseLight=0.8;this.specularLight=2.0;this.roughness=0.5;this.fresnel=1.5;this.opacity=1.0;this.hasAlpha=false;this.opacityscale=false;this._model=IDENTITY;this._view=IDENTITY;this._projection=IDENTITY;this._resolution=[1,1];}var proto=SimplicialMesh.prototype;proto.isOpaque=function(){return!this.hasAlpha;};proto.isTransparent=function(){return this.hasAlpha;};proto.pickSlots=1;proto.setPickBase=function(id){this.pickId=id;};function getOpacityFromScale(ratio,opacityscale){if(!opacityscale)return 1;if(!opacityscale.length)return 1;for(var i=0;iratio&&i>0){var d=(opacityscale[i][0]-ratio)/(opacityscale[i][0]-opacityscale[i-1][0]);return opacityscale[i][1]*(1-d)+d*opacityscale[i-1][1];}}return 1;}function genColormap(param,opacityscale){var colors=colormap({colormap:param,nshades:256,format:'rgba'});var result=new Uint8Array(256*4);for(var i=0;i<256;++i){var c=colors[i];for(var j=0;j<3;++j){result[4*i+j]=c[j];}if(!opacityscale){result[4*i+3]=255*c[3];}else{result[4*i+3]=255*getOpacityFromScale(i/255.0,opacityscale);}}return ndarray(result,[256,256,4],[4,0,1]);}function takeZComponent(array){var n=array.length;var result=new Array(n);for(var i=0;i0){var shader=this.triShader;shader.bind();shader.uniforms=uniforms;this.triangleVAO.bind();gl.drawArrays(gl.TRIANGLES,0,this.triangleCount*3);this.triangleVAO.unbind();}if(this.edgeCount>0&&this.lineWidth>0){var shader=this.lineShader;shader.bind();shader.uniforms=uniforms;this.edgeVAO.bind();gl.lineWidth(this.lineWidth*this.pixelRatio);gl.drawArrays(gl.LINES,0,this.edgeCount*2);this.edgeVAO.unbind();}if(this.pointCount>0){var shader=this.pointShader;shader.bind();shader.uniforms=uniforms;this.pointVAO.bind();gl.drawArrays(gl.POINTS,0,this.pointCount);this.pointVAO.unbind();}if(this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0){var shader=this.contourShader;shader.bind();shader.uniforms=uniforms;this.contourVAO.bind();gl.drawArrays(gl.LINES,0,this.contourCount);this.contourVAO.unbind();}};proto.drawPick=function(params){params=params||{};var gl=this.gl;var model=params.model||IDENTITY;var view=params.view||IDENTITY;var projection=params.projection||IDENTITY;var clipBounds=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]];for(var i=0;i<3;++i){clipBounds[0][i]=Math.max(clipBounds[0][i],this.clipBounds[0][i]);clipBounds[1][i]=Math.min(clipBounds[1][i],this.clipBounds[1][i]);}//Save camera parameters
this._model=[].slice.call(model);this._view=[].slice.call(view);this._projection=[].slice.call(projection);this._resolution=[gl.drawingBufferWidth,gl.drawingBufferHeight];var uniforms={model:model,view:view,projection:projection,clipBounds:clipBounds,pickId:this.pickId/255.0};var shader=this.pickShader;shader.bind();shader.uniforms=uniforms;if(this.triangleCount>0){this.triangleVAO.bind();gl.drawArrays(gl.TRIANGLES,0,this.triangleCount*3);this.triangleVAO.unbind();}if(this.edgeCount>0){this.edgeVAO.bind();gl.lineWidth(this.lineWidth*this.pixelRatio);gl.drawArrays(gl.LINES,0,this.edgeCount*2);this.edgeVAO.unbind();}if(this.pointCount>0){var shader=this.pointPickShader;shader.bind();shader.uniforms=uniforms;this.pointVAO.bind();gl.drawArrays(gl.POINTS,0,this.pointCount);this.pointVAO.unbind();}};proto.pick=function(pickData){if(!pickData){return null;}if(pickData.id!==this.pickId){return null;}var cellId=pickData.value[0]+256*pickData.value[1]+65536*pickData.value[2];var cell=this.cells[cellId];var positions=this.positions;var simplex=new Array(cell.length);for(var i=0;itickOffset[start]){shader.uniforms.dataAxis=DATA_AXIS;shader.uniforms.screenOffset=SCREEN_OFFSET;shader.uniforms.color=textColor[axis];shader.uniforms.angle=textAngle[axis];gl.drawArrays(gl.TRIANGLES,tickOffset[start],tickOffset[end]-tickOffset[start]);}}if(labelEnable[axis]&&labelCount){SCREEN_OFFSET[axis^1]-=screenScale*pixelRatio*labelPad[axis];shader.uniforms.dataAxis=ZERO_2;shader.uniforms.screenOffset=SCREEN_OFFSET;shader.uniforms.color=labelColor[axis];shader.uniforms.angle=labelAngle[axis];gl.drawArrays(gl.TRIANGLES,labelOffset,labelCount);}SCREEN_OFFSET[axis^1]=screenScale*viewBox[2+(axis^1)]-1.0;if(tickEnable[axis+2]){SCREEN_OFFSET[axis^1]+=screenScale*pixelRatio*tickPad[axis+2];if(starttickOffset[start]){shader.uniforms.dataAxis=DATA_AXIS;shader.uniforms.screenOffset=SCREEN_OFFSET;shader.uniforms.color=textColor[axis+2];shader.uniforms.angle=textAngle[axis+2];gl.drawArrays(gl.TRIANGLES,tickOffset[start],tickOffset[end]-tickOffset[start]);}}if(labelEnable[axis+2]&&labelCount){SCREEN_OFFSET[axis^1]+=screenScale*pixelRatio*labelPad[axis+2];shader.uniforms.dataAxis=ZERO_2;shader.uniforms.screenOffset=SCREEN_OFFSET;shader.uniforms.color=labelColor[axis+2];shader.uniforms.angle=labelAngle[axis+2];gl.drawArrays(gl.TRIANGLES,labelOffset,labelCount);}};}();proto.drawTitle=function(){var DATA_AXIS=[0,0];var SCREEN_OFFSET=[0,0];return function(){var plot=this.plot;var shader=this.shader;var gl=plot.gl;var screenBox=plot.screenBox;var titleCenter=plot.titleCenter;var titleAngle=plot.titleAngle;var titleColor=plot.titleColor;var pixelRatio=plot.pixelRatio;if(!this.titleCount){return;}for(var i=0;i<2;++i){SCREEN_OFFSET[i]=2.0*(titleCenter[i]*pixelRatio-screenBox[i])/(screenBox[2+i]-screenBox[i])-1;}shader.bind();shader.uniforms.dataAxis=DATA_AXIS;shader.uniforms.screenOffset=SCREEN_OFFSET;shader.uniforms.angle=titleAngle;shader.uniforms.color=titleColor;gl.drawArrays(gl.TRIANGLES,this.titleOffset,this.titleCount);};}();proto.bind=function(){var DATA_SHIFT=[0,0];var DATA_SCALE=[0,0];var TEXT_SCALE=[0,0];return function(){var plot=this.plot;var shader=this.shader;var bounds=plot._tickBounds;var dataBox=plot.dataBox;var screenBox=plot.screenBox;var viewBox=plot.viewBox;shader.bind();//Set up coordinate scaling uniforms
for(var i=0;i<2;++i){var lo=bounds[i];var hi=bounds[i+2];var boundScale=hi-lo;var dataCenter=0.5*(dataBox[i+2]+dataBox[i]);var dataWidth=dataBox[i+2]-dataBox[i];var viewLo=viewBox[i];var viewHi=viewBox[i+2];var viewScale=viewHi-viewLo;var screenLo=screenBox[i];var screenHi=screenBox[i+2];var screenScale=screenHi-screenLo;DATA_SCALE[i]=2.0*boundScale/dataWidth*viewScale/screenScale;DATA_SHIFT[i]=2.0*(lo-dataCenter)/dataWidth*viewScale/screenScale;}TEXT_SCALE[1]=2.0*plot.pixelRatio/(screenBox[3]-screenBox[1]);TEXT_SCALE[0]=TEXT_SCALE[1]*(screenBox[3]-screenBox[1])/(screenBox[2]-screenBox[0]);shader.uniforms.dataScale=DATA_SCALE;shader.uniforms.dataShift=DATA_SHIFT;shader.uniforms.textScale=TEXT_SCALE;//Set attributes
this.vbo.bind();shader.attributes.textCoordinate.pointer();};}();proto.update=function(options){var vertices=[];var axesTicks=options.ticks;var bounds=options.bounds;var i,j,k,data,scale,dimension;for(dimension=0;dimension<2;++dimension){var offsets=[Math.floor(vertices.length/3)],tickX=[-Infinity];//Copy vertices over to buffer
var ticks=axesTicks[dimension];for(i=0;i=0)){continue;}var zeroIntercept=screenBox[i]-dataBox[i]*(screenBox[i+2]-screenBox[i])/(dataBox[i+2]-dataBox[i]);if(i===0){line.drawLine(zeroIntercept,screenBox[1],zeroIntercept,screenBox[3],zeroLineWidth[i],zeroLineColor[i]);}else{line.drawLine(screenBox[0],zeroIntercept,screenBox[2],zeroIntercept,zeroLineWidth[i],zeroLineColor[i]);}}}//Draw traces
for(var i=0;i=0;--i){this.objects[i].dispose();}this.objects.length=0;for(var i=this.overlays.length-1;i>=0;--i){this.overlays[i].dispose();}this.overlays.length=0;this.gl=null;};proto.addObject=function(object){if(this.objects.indexOf(object)<0){this.objects.push(object);this.setDirty();}};proto.removeObject=function(object){var objects=this.objects;for(var i=0;iMath.abs(dy)){view.rotate(t,0,0,-dx*flipX*Math.PI*camera.rotateSpeed/window.innerWidth);}else{if(!camera._ortho){var kzoom=-camera.zoomSpeed*flipY*dy/window.innerHeight*(t-view.lastT())/20.0;view.pan(t,0,0,distance*(Math.exp(kzoom)-1));}}},true);};camera.enableMouseListeners();return camera;}/***/},/***/799:/***/function(module,__unused_webpack_exports,__nested_webpack_require_434616__){var glslify=__nested_webpack_require_434616__(3236);var createShader=__nested_webpack_require_434616__(9405);var vertSrc=glslify(["precision mediump float;\n#define GLSLIFY 1\nattribute vec2 position;\nvarying vec2 uv;\nvoid main() {\n uv = position;\n gl_Position = vec4(position, 0, 1);\n}"]);var fragSrc=glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D accumBuffer;\nvarying vec2 uv;\n\nvoid main() {\n vec4 accum = texture2D(accumBuffer, 0.5 * (uv + 1.0));\n gl_FragColor = min(vec4(1,1,1,1), accum);\n}"]);module.exports=function(gl){return createShader(gl,vertSrc,fragSrc,null,[{name:'position',type:'vec2'}]);};/***/},/***/4100:/***/function(module,__unused_webpack_exports,__nested_webpack_require_435320__){"use strict";var createCamera=__nested_webpack_require_435320__(4437);var createAxes=__nested_webpack_require_435320__(3837);var axesRanges=__nested_webpack_require_435320__(5445);var createSpikes=__nested_webpack_require_435320__(4449);var createSelect=__nested_webpack_require_435320__(3589);var createFBO=__nested_webpack_require_435320__(2260);var drawTriangle=__nested_webpack_require_435320__(7169);var mouseChange=__nested_webpack_require_435320__(351);var perspective=__nested_webpack_require_435320__(4772);var ortho=__nested_webpack_require_435320__(4040);var createShader=__nested_webpack_require_435320__(799);var isMobile=__nested_webpack_require_435320__(9216)({tablet:true,featureDetect:true});module.exports={createScene:createScene,createCamera:createCamera};function MouseSelect(){this.mouse=[-1,-1];this.screen=null;this.distance=Infinity;this.index=null;this.dataCoordinate=null;this.dataPosition=null;this.object=null;this.data=null;}function getContext(canvas,options){var gl=null;try{gl=canvas.getContext('webgl',options);if(!gl){gl=canvas.getContext('experimental-webgl',options);}}catch(e){return null;}return gl;}function roundUpPow10(x){var y=Math.round(Math.log(Math.abs(x))/Math.log(10));if(y<0){var base=Math.round(Math.pow(10,-y));return Math.ceil(x*base)/base;}else if(y>0){var base=Math.round(Math.pow(10,y));return Math.ceil(x/base)*base;}return Math.ceil(x);}function defaultBool(x){if(typeof x==='boolean'){return x;}return true;}function createScene(options){options=options||{};options.camera=options.camera||{};var canvas=options.canvas;if(!canvas){canvas=document.createElement('canvas');if(options.container){var container=options.container;container.appendChild(canvas);}else{document.body.appendChild(canvas);}}var gl=options.gl;if(!gl){if(options.glOptions){isMobile=!!options.glOptions.preserveDrawingBuffer;}gl=getContext(canvas,options.glOptions||{premultipliedAlpha:true,antialias:true,preserveDrawingBuffer:isMobile});}if(!gl){throw new Error('webgl not supported');}//Initial bounds
var bounds=options.bounds||[[-10,-10,-10],[10,10,10]];//Create selection
var selection=new MouseSelect();//Accumulation buffer
var accumBuffer=createFBO(gl,gl.drawingBufferWidth,gl.drawingBufferHeight,{preferFloat:!isMobile});var accumShader=createShader(gl);var isOrtho=options.cameraObject&&options.cameraObject._ortho===true||options.camera.projection&&options.camera.projection.type==='orthographic'||false;//Create a camera
var cameraOptions={eye:options.camera.eye||[2,0,0],center:options.camera.center||[0,0,0],up:options.camera.up||[0,1,0],zoomMin:options.camera.zoomMax||0.1,zoomMax:options.camera.zoomMin||100,mode:options.camera.mode||'turntable',_ortho:isOrtho};//Create axes
var axesOptions=options.axes||{};var axes=createAxes(gl,axesOptions);axes.enable=!axesOptions.disable;//Create spikes
var spikeOptions=options.spikes||{};var spikes=createSpikes(gl,spikeOptions);//Object list is empty initially
var objects=[];var pickBufferIds=[];var pickBufferCount=[];var pickBuffers=[];//Dirty flag, skip redraw if scene static
var dirty=true;var pickDirty=true;var projection=new Array(16);var model=new Array(16);var cameraParams={view:null,projection:projection,model:model,_ortho:false};var pickDirty=true;var viewShape=[gl.drawingBufferWidth,gl.drawingBufferHeight];var camera=options.cameraObject||createCamera(canvas,cameraOptions);//Create scene object
var scene={gl:gl,contextLost:false,pixelRatio:options.pixelRatio||1,canvas:canvas,selection:selection,camera:camera,axes:axes,axesPixels:null,spikes:spikes,bounds:bounds,objects:objects,shape:viewShape,aspect:options.aspectRatio||[1,1,1],pickRadius:options.pickRadius||10,zNear:options.zNear||0.01,zFar:options.zFar||1000,fovy:options.fovy||Math.PI/4,clearColor:options.clearColor||[0,0,0,0],autoResize:defaultBool(options.autoResize),autoBounds:defaultBool(options.autoBounds),autoScale:!!options.autoScale,autoCenter:defaultBool(options.autoCenter),clipToBounds:defaultBool(options.clipToBounds),snapToData:!!options.snapToData,onselect:options.onselect||null,onrender:options.onrender||null,onclick:options.onclick||null,cameraParams:cameraParams,oncontextloss:null,mouseListener:null,_stopped:false,getAspectratio:function(){return{x:this.aspect[0],y:this.aspect[1],z:this.aspect[2]};},setAspectratio:function(aspectratio){this.aspect[0]=aspectratio.x;this.aspect[1]=aspectratio.y;this.aspect[2]=aspectratio.z;pickDirty=true;},setBounds:function(axisIndex,range){this.bounds[0][axisIndex]=range.min;this.bounds[1][axisIndex]=range.max;},setClearColor:function(clearColor){this.clearColor=clearColor;},clearRGBA:function(){this.gl.clearColor(this.clearColor[0],this.clearColor[1],this.clearColor[2],this.clearColor[3]);this.gl.clear(this.gl.COLOR_BUFFER_BIT|this.gl.DEPTH_BUFFER_BIT);}};var pickShape=[gl.drawingBufferWidth/scene.pixelRatio|0,gl.drawingBufferHeight/scene.pixelRatio|0];function resizeListener(){if(scene._stopped){return;}if(!scene.autoResize){return;}var parent=canvas.parentNode;var width=1;var height=1;if(parent&&parent!==document.body){width=parent.clientWidth;height=parent.clientHeight;}else{width=window.innerWidth;height=window.innerHeight;}var nextWidth=Math.ceil(width*scene.pixelRatio)|0;var nextHeight=Math.ceil(height*scene.pixelRatio)|0;if(nextWidth!==canvas.width||nextHeight!==canvas.height){canvas.width=nextWidth;canvas.height=nextHeight;var style=canvas.style;style.position=style.position||'absolute';style.left='0px';style.top='0px';style.width=width+'px';style.height=height+'px';dirty=true;}}if(scene.autoResize){resizeListener();}window.addEventListener('resize',resizeListener);function reallocPickIds(){var numObjs=objects.length;var numPick=pickBuffers.length;for(var i=0;i0&&pickBufferCount[numPick-1]===0){pickBufferCount.pop();pickBuffers.pop().dispose();}}scene.update=function(options){if(scene._stopped){return;}options=options||{};dirty=true;pickDirty=true;};scene.add=function(obj){if(scene._stopped){return;}obj.axes=axes;objects.push(obj);pickBufferIds.push(-1);dirty=true;pickDirty=true;reallocPickIds();};scene.remove=function(obj){if(scene._stopped){return;}var idx=objects.indexOf(obj);if(idx<0){return;}objects.splice(idx,1);pickBufferIds.pop();dirty=true;pickDirty=true;reallocPickIds();};scene.dispose=function(){if(scene._stopped){return;}scene._stopped=true;window.removeEventListener('resize',resizeListener);canvas.removeEventListener('webglcontextlost',checkContextLoss);scene.mouseListener.enabled=false;if(scene.contextLost){return;}//Destroy objects
axes.dispose();spikes.dispose();for(var i=0;iselection.distance){continue;}for(var j=0;j 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]);exports.pickVertex=glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]);exports.pickFragment=glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]);/***/},/***/4696:/***/function(module,__unused_webpack_exports,__nested_webpack_require_453471__){"use strict";var createShader=__nested_webpack_require_453471__(9405);var createBuffer=__nested_webpack_require_453471__(2762);var pool=__nested_webpack_require_453471__(1888);var SHADERS=__nested_webpack_require_453471__(6640);module.exports=createPointcloud2D;function Pointcloud2D(plot,offsetBuffer,pickBuffer,shader,pickShader){this.plot=plot;this.offsetBuffer=offsetBuffer;this.pickBuffer=pickBuffer;this.shader=shader;this.pickShader=pickShader;this.sizeMin=0.5;this.sizeMinCap=2;this.sizeMax=20;this.areaRatio=1.0;this.pointCount=0;this.color=[1,0,0,1];this.borderColor=[0,0,0,1];this.blend=false;this.pickOffset=0;this.points=null;}var proto=Pointcloud2D.prototype;proto.dispose=function(){this.shader.dispose();this.pickShader.dispose();this.offsetBuffer.dispose();this.pickBuffer.dispose();this.plot.removeObject(this);};proto.update=function(options){var i;options=options||{};function dflt(opt,value){if(opt in options){return options[opt];}return value;}this.sizeMin=dflt('sizeMin',0.5);// this.sizeMinCap = dflt('sizeMinCap', 2)
this.sizeMax=dflt('sizeMax',20);this.color=dflt('color',[1,0,0,1]).slice();this.areaRatio=dflt('areaRatio',1);this.borderColor=dflt('borderColor',[0,0,0,1]).slice();this.blend=dflt('blend',false);//Update point data
// Attempt straight-through processing (STP) to avoid allocation and copy
// TODO eventually abstract out STP logic, maybe into `pool` or a layer above
var pointCount=options.positions.length>>>1;var dataStraightThrough=options.positions instanceof Float32Array;var idStraightThrough=options.idToIndex instanceof Int32Array&&options.idToIndex.length>=pointCount;// permit larger to help reuse
var data=options.positions;var packed=dataStraightThrough?data:pool.mallocFloat32(data.length);var packedId=idStraightThrough?options.idToIndex:pool.mallocInt32(pointCount);if(!dataStraightThrough){packed.set(data);}if(!idStraightThrough){packed.set(data);for(i=0;i>>1;var i;for(i=0;i=dataBox[0]&&x<=dataBox[2]&&y>=dataBox[1]&&y<=dataBox[3])visiblePointCountEstimate++;}return visiblePointCountEstimate;}proto.unifiedDraw=function(){var MATRIX=[1,0,0,0,1,0,0,0,1];var PICK_VEC4=[0,0,0,0];return function(pickOffset){var pick=pickOffset!==void 0;var shader=pick?this.pickShader:this.shader;var gl=this.plot.gl;var dataBox=this.plot.dataBox;if(this.pointCount===0){return pickOffset;}var dataX=dataBox[2]-dataBox[0];var dataY=dataBox[3]-dataBox[1];var visiblePointCountEstimate=count(this.points,dataBox);var basicPointSize=this.plot.pickPixelRatio*Math.max(Math.min(this.sizeMinCap,this.sizeMin),Math.min(this.sizeMax,this.sizeMax/Math.pow(visiblePointCountEstimate,0.33333)));MATRIX[0]=2.0/dataX;MATRIX[4]=2.0/dataY;MATRIX[6]=-2.0*dataBox[0]/dataX-1.0;MATRIX[7]=-2.0*dataBox[1]/dataY-1.0;this.offsetBuffer.bind();shader.bind();shader.attributes.position.pointer();shader.uniforms.matrix=MATRIX;shader.uniforms.color=this.color;shader.uniforms.borderColor=this.borderColor;shader.uniforms.pointCloud=basicPointSize<5;shader.uniforms.pointSize=basicPointSize;shader.uniforms.centerFraction=Math.min(1,Math.max(0,Math.sqrt(1-this.areaRatio)));if(pick){PICK_VEC4[0]=pickOffset&0xff;PICK_VEC4[1]=pickOffset>>8&0xff;PICK_VEC4[2]=pickOffset>>16&0xff;PICK_VEC4[3]=pickOffset>>24&0xff;this.pickBuffer.bind();shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE);shader.uniforms.pickOffset=PICK_VEC4;this.pickOffset=pickOffset;}// Worth switching these off, but we can't make assumptions about other
// renderers, so let's restore it after each draw
var blend=gl.getParameter(gl.BLEND);var dither=gl.getParameter(gl.DITHER);if(blend&&!this.blend)gl.disable(gl.BLEND);if(dither)gl.disable(gl.DITHER);gl.drawArrays(gl.POINTS,0,this.pointCount);if(blend&&!this.blend)gl.enable(gl.BLEND);if(dither)gl.enable(gl.DITHER);return pickOffset+this.pointCount;};}();proto.draw=proto.unifiedDraw;proto.drawPick=proto.unifiedDraw;proto.pick=function(x,y,value){var pickOffset=this.pickOffset;var pointCount=this.pointCount;if(value=pickOffset+pointCount){return null;}var pointId=value-pickOffset;var points=this.points;return{object:this,pointId:pointId,dataCoord:[points[2*pointId],points[2*pointId+1]]};};function createPointcloud2D(plot,options){var gl=plot.gl;var buffer=createBuffer(gl);var pickBuffer=createBuffer(gl);var shader=createShader(gl,SHADERS.pointVertex,SHADERS.pointFragment);var pickShader=createShader(gl,SHADERS.pickVertex,SHADERS.pickFragment);var result=new Pointcloud2D(plot,buffer,pickBuffer,shader,pickShader);result.update(options);//Register with plot
plot.addObject(result);return result;}/***/},/***/783:/***/function(module){module.exports=slerp;/**
* Performs a spherical linear interpolation between two quat
*
* @param {quat} out the receiving quaternion
* @param {quat} a the first operand
* @param {quat} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {quat} out
*/function slerp(out,a,b,t){// benchmarks:
// http://jsperf.com/quaternion-slerp-implementations
var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3];var omega,cosom,sinom,scale0,scale1;// calc cosine
cosom=ax*bx+ay*by+az*bz+aw*bw;// adjust signs (if necessary)
if(cosom<0.0){cosom=-cosom;bx=-bx;by=-by;bz=-bz;bw=-bw;}// calculate coefficients
if(1.0-cosom>0.000001){// standard case (slerp)
omega=Math.acos(cosom);sinom=Math.sin(omega);scale0=Math.sin((1.0-t)*omega)/sinom;scale1=Math.sin(t*omega)/sinom;}else{// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0=1.0-t;scale1=t;}// calculate final values
out[0]=scale0*ax+scale1*bx;out[1]=scale0*ay+scale1*by;out[2]=scale0*az+scale1*bz;out[3]=scale0*aw+scale1*bw;return out;}/***/},/***/5964:/***/function(module){"use strict";module.exports=function(a){return!a&&a!==0?'':a.toString();};/***/},/***/9366:/***/function(module,__unused_webpack_exports,__nested_webpack_require_459702__){"use strict";var vectorizeText=__nested_webpack_require_459702__(4359);module.exports=getGlyph;var GLYPH_CACHE={};function getGlyph(symbol,font,pixelRatio){var fontKey=[font.style,font.weight,font.variant,font.family].join('_');var fontCache=GLYPH_CACHE[fontKey];if(!fontCache){fontCache=GLYPH_CACHE[fontKey]={};}if(symbol in fontCache){return fontCache[symbol];}var config={textAlign:"center",textBaseline:"middle",lineHeight:1.0,font:font.family,fontStyle:font.style,fontWeight:font.weight,fontVariant:font.variant,lineSpacing:1.25,styletags:{breaklines:true,bolds:true,italics:true,subscripts:true,superscripts:true}};//Get line and triangle meshes for glyph
config.triangles=true;var triSymbol=vectorizeText(symbol,config);config.triangles=false;var lineSymbol=vectorizeText(symbol,config);var i,j;if(pixelRatio&&pixelRatio!==1){for(i=0;i max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = 1.0;\n if(distance(highlightId, id) < 0.0001) {\n scale = highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1);\n vec4 viewPosition = view * worldPosition;\n viewPosition = viewPosition / viewPosition.w;\n vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n\n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}"]);var orthographicVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = pixelRatio;\n if(distance(highlightId.bgr, id.bgr) < 0.001) {\n scale *= highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1.0);\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}"]);var projectionVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n gl_Position = vec4(0,0,0,0);\n } else {\n float lscale = pixelRatio * scale;\n if(distance(highlightId, id) < 0.0001) {\n lscale *= highlightScale;\n }\n\n vec4 clipCenter = projection * (view * (model * vec4(position, 1)));\n vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n vec4 clipPosition = projection * (view * (model * vec4(dataPosition, 1)));\n\n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = dataPosition;\n }\n}\n"]);var drawFragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if (\n outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) ||\n interpColor.a * opacity == 0.\n ) discard;\n gl_FragColor = interpColor * opacity;\n}\n"]);var pickFragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate)) discard;\n\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n}"]);var ATTRIBUTES=[{name:'position',type:'vec3'},{name:'color',type:'vec4'},{name:'glyph',type:'vec2'},{name:'id',type:'vec4'}];var perspective={vertex:perspectiveVertSrc,fragment:drawFragSrc,attributes:ATTRIBUTES},ortho={vertex:orthographicVertSrc,fragment:drawFragSrc,attributes:ATTRIBUTES},project={vertex:projectionVertSrc,fragment:drawFragSrc,attributes:ATTRIBUTES},pickPerspective={vertex:perspectiveVertSrc,fragment:pickFragSrc,attributes:ATTRIBUTES},pickOrtho={vertex:orthographicVertSrc,fragment:pickFragSrc,attributes:ATTRIBUTES},pickProject={vertex:projectionVertSrc,fragment:pickFragSrc,attributes:ATTRIBUTES};function createShader(gl,src){var shader=createShaderWrapper(gl,src);var attr=shader.attributes;attr.position.location=0;attr.color.location=1;attr.glyph.location=2;attr.id.location=3;return shader;}exports.createPerspective=function(gl){return createShader(gl,perspective);};exports.createOrtho=function(gl){return createShader(gl,ortho);};exports.createProject=function(gl){return createShader(gl,project);};exports.createPickPerspective=function(gl){return createShader(gl,pickPerspective);};exports.createPickOrtho=function(gl){return createShader(gl,pickOrtho);};exports.createPickProject=function(gl){return createShader(gl,pickProject);};/***/},/***/8418:/***/function(module,__unused_webpack_exports,__nested_webpack_require_468978__){"use strict";var isAllBlank=__nested_webpack_require_468978__(5219);var createBuffer=__nested_webpack_require_468978__(2762);var createVAO=__nested_webpack_require_468978__(8116);var pool=__nested_webpack_require_468978__(1888);var mat4mult=__nested_webpack_require_468978__(6760);var shaders=__nested_webpack_require_468978__(1283);var getGlyph=__nested_webpack_require_468978__(9366);var getSimpleString=__nested_webpack_require_468978__(5964);var IDENTITY=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];var ab=ArrayBuffer;var dv=DataView;function isTypedArray(a){return ab.isView(a)&&!(a instanceof dv);}function isArrayOrTypedArray(a){return Array.isArray(a)||isTypedArray(a);}module.exports=createPointCloud;function transformMat4(x,m){var x0=x[0];var x1=x[1];var x2=x[2];var x3=x[3];x[0]=m[0]*x0+m[4]*x1+m[8]*x2+m[12]*x3;x[1]=m[1]*x0+m[5]*x1+m[9]*x2+m[13]*x3;x[2]=m[2]*x0+m[6]*x1+m[10]*x2+m[14]*x3;x[3]=m[3]*x0+m[7]*x1+m[11]*x2+m[15]*x3;return x;}function project(p,v,m,x){transformMat4(x,x,m);transformMat4(x,x,v);return transformMat4(x,x,p);}function ScatterPlotPickResult(index,position){this.index=index;this.dataCoordinate=this.position=position;}function fixOpacity(a){if(a===true)return 1;if(a>1)return 1;return a;}function PointCloud(gl,shader,orthoShader,projectShader,pointBuffer,colorBuffer,glyphBuffer,idBuffer,vao,pickPerspectiveShader,pickOrthoShader,pickProjectShader){this.gl=gl;this.pixelRatio=1;this.shader=shader;this.orthoShader=orthoShader;this.projectShader=projectShader;this.pointBuffer=pointBuffer;this.colorBuffer=colorBuffer;this.glyphBuffer=glyphBuffer;this.idBuffer=idBuffer;this.vao=vao;this.vertexCount=0;this.lineVertexCount=0;this.opacity=1;this.hasAlpha=false;this.lineWidth=0;this.projectScale=[2.0/3.0,2.0/3.0,2.0/3.0];this.projectOpacity=[1,1,1];this.projectHasAlpha=false;this.pickId=0;this.pickPerspectiveShader=pickPerspectiveShader;this.pickOrthoShader=pickOrthoShader;this.pickProjectShader=pickProjectShader;this.points=[];this._selectResult=new ScatterPlotPickResult(0,[0,0,0]);this.useOrtho=true;this.bounds=[[Infinity,Infinity,Infinity],[-Infinity,-Infinity,-Infinity]];//Axes projections
this.axesProject=[true,true,true];this.axesBounds=[[-Infinity,-Infinity,-Infinity],[Infinity,Infinity,Infinity]];this.highlightId=[1,1,1,1];this.highlightScale=2;this.clipBounds=[[-Infinity,-Infinity,-Infinity],[Infinity,Infinity,Infinity]];this.dirty=true;}var proto=PointCloud.prototype;proto.pickSlots=1;proto.setPickBase=function(pickBase){this.pickId=pickBase;};proto.isTransparent=function(){if(this.hasAlpha){return true;}for(var i=0;i<3;++i){if(this.axesProject[i]&&this.projectHasAlpha){return true;}}return false;};proto.isOpaque=function(){if(!this.hasAlpha){return true;}for(var i=0;i<3;++i){if(this.axesProject[i]&&!this.projectHasAlpha){return true;}}return false;};var VIEW_SHAPE=[0,0];var U_VEC=[0,0,0];var V_VEC=[0,0,0];var MU_VEC=[0,0,0,1];var MV_VEC=[0,0,0,1];var SCRATCH_MATRIX=IDENTITY.slice();var SCRATCH_VEC=[0,0,0];var CLIP_BOUNDS=[[0,0,0],[0,0,0]];function zeroVec(a){a[0]=a[1]=a[2]=0;return a;}function augment(hg,af){hg[0]=af[0];hg[1]=af[1];hg[2]=af[2];hg[3]=1;return hg;}function setComponent(out,v,i,x){out[0]=v[0];out[1]=v[1];out[2]=v[2];out[i]=x;return out;}function getClipBounds(bounds){var result=CLIP_BOUNDS;for(var i=0;i<2;++i){for(var j=0;j<3;++j){result[i][j]=Math.max(Math.min(bounds[i][j],1e8),-1e8);}}return result;}function drawProject(shader,points,camera,pixelRatio){var axesProject=points.axesProject;var gl=points.gl;var uniforms=shader.uniforms;var model=camera.model||IDENTITY;var view=camera.view||IDENTITY;var projection=camera.projection||IDENTITY;var bounds=points.axesBounds;var clipBounds=getClipBounds(points.clipBounds);var cubeAxis;if(points.axes&&points.axes.lastCubeProps){cubeAxis=points.axes.lastCubeProps.axis;}else{cubeAxis=[1,1,1];}VIEW_SHAPE[0]=2.0/gl.drawingBufferWidth;VIEW_SHAPE[1]=2.0/gl.drawingBufferHeight;shader.bind();uniforms.view=view;uniforms.projection=projection;uniforms.screenSize=VIEW_SHAPE;uniforms.highlightId=points.highlightId;uniforms.highlightScale=points.highlightScale;uniforms.clipBounds=clipBounds;uniforms.pickGroup=points.pickId/255.0;uniforms.pixelRatio=pixelRatio;for(var i=0;i<3;++i){if(!axesProject[i]){continue;}uniforms.scale=points.projectScale[i];uniforms.opacity=points.projectOpacity[i];//Project model matrix
var pmodel=SCRATCH_MATRIX;for(var j=0;j<16;++j){pmodel[j]=0;}for(var j=0;j<4;++j){pmodel[5*j]=1;}pmodel[5*i]=0;if(cubeAxis[i]<0){pmodel[12+i]=bounds[0][i];}else{pmodel[12+i]=bounds[1][i];}mat4mult(pmodel,model,pmodel);uniforms.model=pmodel;//Compute initial axes
var u=(i+1)%3;var v=(i+2)%3;var du=zeroVec(U_VEC);var dv=zeroVec(V_VEC);du[u]=1;dv[v]=1;//Align orientation relative to viewer
var mdu=project(projection,view,model,augment(MU_VEC,du));var mdv=project(projection,view,model,augment(MV_VEC,dv));if(Math.abs(mdu[1])>Math.abs(mdv[1])){var tmp=mdu;mdu=mdv;mdv=tmp;tmp=du;du=dv;dv=tmp;var t=u;u=v;v=t;}if(mdu[0]<0){du[u]=-1;}if(mdv[1]>0){dv[v]=-1;}var su=0.0;var sv=0.0;for(var j=0;j<4;++j){su+=Math.pow(model[4*u+j],2);sv+=Math.pow(model[4*v+j],2);}du[u]/=Math.sqrt(su);dv[v]/=Math.sqrt(sv);uniforms.axes[0]=du;uniforms.axes[1]=dv;//Update fragment clip bounds
uniforms.fragClipBounds[0]=setComponent(SCRATCH_VEC,clipBounds[0],i,-1e8);uniforms.fragClipBounds[1]=setComponent(SCRATCH_VEC,clipBounds[1],i,1e8);points.vao.bind();//Draw interior
points.vao.draw(gl.TRIANGLES,points.vertexCount);//Draw edges
if(points.lineWidth>0){gl.lineWidth(points.lineWidth*pixelRatio);points.vao.draw(gl.LINES,points.lineVertexCount,points.vertexCount);}points.vao.unbind();}}var NEG_INFINITY3=[-1e8,-1e8,-1e8];var POS_INFINITY3=[1e8,1e8,1e8];var CLIP_GROUP=[NEG_INFINITY3,POS_INFINITY3];function drawFull(shader,pshader,points,camera,pixelRatio,transparent,forceDraw){var gl=points.gl;if(transparent===points.projectHasAlpha||forceDraw){drawProject(pshader,points,camera,pixelRatio);}if(transparent===points.hasAlpha||forceDraw){shader.bind();var uniforms=shader.uniforms;uniforms.model=camera.model||IDENTITY;uniforms.view=camera.view||IDENTITY;uniforms.projection=camera.projection||IDENTITY;VIEW_SHAPE[0]=2.0/gl.drawingBufferWidth;VIEW_SHAPE[1]=2.0/gl.drawingBufferHeight;uniforms.screenSize=VIEW_SHAPE;uniforms.highlightId=points.highlightId;uniforms.highlightScale=points.highlightScale;uniforms.fragClipBounds=CLIP_GROUP;uniforms.clipBounds=points.axes.bounds;uniforms.opacity=points.opacity;uniforms.pickGroup=points.pickId/255.0;uniforms.pixelRatio=pixelRatio;points.vao.bind();//Draw interior
points.vao.draw(gl.TRIANGLES,points.vertexCount);//Draw edges
if(points.lineWidth>0){gl.lineWidth(points.lineWidth*pixelRatio);points.vao.draw(gl.LINES,points.lineVertexCount,points.vertexCount);}points.vao.unbind();}}proto.draw=function(camera){var shader=this.useOrtho?this.orthoShader:this.shader;drawFull(shader,this.projectShader,this,camera,this.pixelRatio,false,false);};proto.drawTransparent=function(camera){var shader=this.useOrtho?this.orthoShader:this.shader;drawFull(shader,this.projectShader,this,camera,this.pixelRatio,true,false);};proto.drawPick=function(camera){var shader=this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader;drawFull(shader,this.pickProjectShader,this,camera,1,true,true);};proto.pick=function(selected){if(!selected){return null;}if(selected.id!==this.pickId){return null;}var x=selected.value[2]+(selected.value[1]<<8)+(selected.value[0]<<16);if(x>=this.pointCount||x<0){return null;}//Unpack result
var coord=this.points[x];var result=this._selectResult;result.index=x;for(var i=0;i<3;++i){result.position[i]=result.dataCoordinate[i]=coord[i];}return result;};proto.highlight=function(selection){if(!selection){this.highlightId=[1,1,1,1];}else{var pointId=selection.index;var a0=pointId&0xff;var a1=pointId>>8&0xff;var a2=pointId>>16&0xff;this.highlightId=[a0/255.0,a1/255.0,a2/255.0,0];}};function get_glyphData(glyphs,index,font,pixelRatio){var str;// use the data if presented in an array
if(isArrayOrTypedArray(glyphs)){if(index0){var triOffset=0;var lineOffset=triVertexCount;var color=[0,0,0,1];var lineColor=[0,0,0,1];var isColorArray=isArrayOrTypedArray(colors)&&isArrayOrTypedArray(colors[0]);var isLineColorArray=isArrayOrTypedArray(lineColors)&&isArrayOrTypedArray(lineColors[0]);fill_loop:for(var i=0;i0?1-glyphBounds[0][0]:textOffsetX<0?1+glyphBounds[1][0]:1;textOffsetY*=textOffsetY>0?1-glyphBounds[0][1]:textOffsetY<0?1+glyphBounds[1][1]:1;var textOffset=[textOffsetX,textOffsetY];//Write out inner marker
var cells=glyphMesh.cells||[];var verts=glyphMesh.positions||[];for(var j=0;j0){//Draw border
var w=lineWidth*pixelRatio;boxes.drawBox(loX-w,loY-w,hiX+w,loY+w,borderColor);boxes.drawBox(loX-w,hiY-w,hiX+w,hiY+w,borderColor);boxes.drawBox(loX-w,loY-w,loX+w,hiY+w,borderColor);boxes.drawBox(hiX-w,loY-w,hiX+w,hiY+w,borderColor);}};proto.update=function(options){options=options||{};this.innerFill=!!options.innerFill;this.outerFill=!!options.outerFill;this.innerColor=(options.innerColor||[0,0,0,0.5]).slice();this.outerColor=(options.outerColor||[0,0,0,0.5]).slice();this.borderColor=(options.borderColor||[0,0,0,1]).slice();this.borderWidth=options.borderWidth||0;this.selectBox=(options.selectBox||this.selectBox).slice();};proto.dispose=function(){this.boxBuffer.dispose();this.boxShader.dispose();this.plot.removeOverlay(this);};function createSelectBox(plot,options){var gl=plot.gl;var buffer=createBuffer(gl,[0,0,0,1,1,0,1,1]);var shader=createShader(gl,SHADERS.boxVertex,SHADERS.boxFragment);var selectBox=new SelectBox(plot,buffer,shader);selectBox.update(options);plot.addOverlay(selectBox);return selectBox;}/***/},/***/3589:/***/function(module,__unused_webpack_exports,__nested_webpack_require_489456__){"use strict";module.exports=createSelectBuffer;var createFBO=__nested_webpack_require_489456__(2260);var pool=__nested_webpack_require_489456__(1888);var ndarray=__nested_webpack_require_489456__(9618);var nextPow2=__nested_webpack_require_489456__(8828).nextPow2;var selectRange=function(arr,x,y){var closestD2=1e8;var closestX=-1;var closestY=-1;var ni=arr.shape[0];var nj=arr.shape[1];for(var i=0;ithis.buffer.length){pool.free(this.buffer);var buffer=this.buffer=pool.mallocUint8(nextPow2(r*c*4));for(var i=0;ioldAttribCount){for(i=oldAttribCount;inewAttribCount){for(i=newAttribCount;i=0){var size=attr.type.charAt(attr.type.length-1)|0;var locVector=new Array(size);for(var j=0;j=0){curLocation+=1;}attributeLocations[i]=curLocation;}}//Rebuild program and recompute all uniform locations
var uniformLocations=new Array(uniforms.length);function relink(){wrapper.program=shaderCache.program(gl,wrapper._vref,wrapper._fref,attributeNames,attributeLocations);for(var i=0;i=0){var d=type.charCodeAt(type.length-1)-48;if(d<2||d>4){throw new GLError('','Invalid data type for attribute '+name+': '+type);}addVectorAttribute(gl,wrapper,locs[0],locations,d,obj,name);}else if(type.indexOf('mat')>=0){var d=type.charCodeAt(type.length-1)-48;if(d<2||d>4){throw new GLError('','Invalid data type for attribute '+name+': '+type);}addMatrixAttribute(gl,wrapper,locs,locations,d,obj,name);}else{throw new GLError('','Unknown data type for attribute '+name+': '+type);}break;}}return obj;}/***/},/***/3327:/***/function(module,__unused_webpack_exports,__nested_webpack_require_503031__){"use strict";var coallesceUniforms=__nested_webpack_require_503031__(216);var GLError=__nested_webpack_require_503031__(8866);module.exports=createUniformWrapper;//Binds a function and returns a value
function identity(x){return function(){return x;};}function makeVector(length,fill){var result=new Array(length);for(var i=0;i4){throw new GLError('','Invalid data type');}switch(t.charAt(0)){case'b':case'i':gl['uniform'+d+'iv'](locations[idx],objPath);break;case'v':gl['uniform'+d+'fv'](locations[idx],objPath);break;default:throw new GLError('','Unrecognized data type for vector '+name+': '+t);}}else if(t.indexOf('mat')===0&&t.length===4){d=t.charCodeAt(t.length-1)-48;if(d<2||d>4){throw new GLError('','Invalid uniform dimension type for matrix '+name+': '+t);}gl['uniformMatrix'+d+'fv'](locations[idx],false,objPath);break;}else{throw new GLError('','Unknown uniform data type for '+name+': '+t);}}}}};}function enumerateIndices(prefix,type){if(typeof type!=='object'){return[[prefix,type]];}var indices=[];for(var id in type){var prop=type[id];var tprefix=prefix;if(parseInt(id)+''===id){tprefix+='['+id+']';}else{tprefix+='.'+id;}if(typeof prop==='object'){indices.push.apply(indices,enumerateIndices(tprefix,prop));}else{indices.push([tprefix,prop]);}}return indices;}function defaultValue(type){switch(type){case'bool':return false;case'int':case'sampler2D':case'samplerCube':return 0;case'float':return 0.0;default:var vidx=type.indexOf('vec');if(0<=vidx&&vidx<=1&&type.length===4+vidx){var d=type.charCodeAt(type.length-1)-48;if(d<2||d>4){throw new GLError('','Invalid data type');}if(type.charAt(0)==='b'){return makeVector(d,false);}return makeVector(d,0);}else if(type.indexOf('mat')===0&&type.length===4){var d=type.charCodeAt(type.length-1)-48;if(d<2||d>4){throw new GLError('','Invalid uniform dimension type for matrix '+name+': '+type);}return makeVector(d*d,0);}else{throw new GLError('','Unknown uniform data type for '+name+': '+type);}}}function storeProperty(obj,prop,type){if(typeof type==='object'){var child=processObject(type);Object.defineProperty(obj,prop,{get:identity(child),set:makeSetter(type),enumerable:true,configurable:false});}else{if(locations[type]){Object.defineProperty(obj,prop,{get:makeGetter(type),set:makeSetter(type),enumerable:true,configurable:false});}else{obj[prop]=defaultValue(uniforms[type].type);}}}function processObject(obj){var result;if(Array.isArray(obj)){result=new Array(obj.length);for(var i=0;i1){if(!(x[0]in o)){o[x[0]]=[];}o=o[x[0]];for(var k=1;k1){for(var j=0;j 0 U ||b|| > 0.\n // Assign z = 0, x = -b, y = a:\n // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n return normalize(vec3(-v.y, v.x, 0.0));\n } else {\n return normalize(vec3(0.0, v.z, -v.y));\n }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n float segmentCount = 8.0;\n\n float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n vec3 u = getOrthogonalVector(d);\n vec3 v = normalize(cross(u, d));\n\n vec3 x = u * cos(angle) * length(d);\n vec3 y = v * sin(angle) * length(d);\n vec3 v3 = x + y;\n\n normal = normalize(v3);\n\n return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\n\nuniform float vectorScale, tubeScale;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 eyePosition, lightPosition;\n\nvarying vec3 f_normal, f_lightDirection, f_eyeDirection, f_data, f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n // Scale the vector magnitude to stay constant with\n // model & view changes.\n vec3 normal;\n vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * tubePosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n f_lightDirection = lightPosition - cameraCoordinate.xyz;\n f_eyeDirection = eyePosition - cameraCoordinate.xyz;\n f_normal = normalize((vec4(normal, 0.0) * inverseModel).xyz);\n\n // vec4 m_position = model * vec4(tubePosition, 1.0);\n vec4 t_position = view * tubePosition;\n gl_Position = projection * t_position;\n\n f_color = color;\n f_data = tubePosition.xyz;\n f_position = position.xyz;\n f_uv = uv;\n}\n"]);var triFragSrc=glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision highp float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal, f_lightDirection, f_eyeDirection, f_data, f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}\n"]);var pickVertSrc=glslify(["precision highp float;\n\nprecision highp float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n // Return up-vector for only-z vector.\n // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n // From the above if-statement we have ||a|| > 0 U ||b|| > 0.\n // Assign z = 0, x = -b, y = a:\n // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n return normalize(vec3(-v.y, v.x, 0.0));\n } else {\n return normalize(vec3(0.0, v.z, -v.y));\n }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n float segmentCount = 8.0;\n\n float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n vec3 u = getOrthogonalVector(d);\n vec3 v = normalize(cross(u, d));\n\n vec3 x = u * cos(angle) * length(d);\n vec3 y = v * sin(angle) * length(d);\n vec3 v3 = x + y;\n\n normal = normalize(v3);\n\n return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform float tubeScale;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n vec3 normal;\n vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n gl_Position = projection * (view * tubePosition);\n f_id = id;\n f_position = position.xyz;\n}\n"]);var pickFragSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n return ((p > max(a, b)) || \n (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n return (outOfRange(a.x, b.x, p.x) ||\n outOfRange(a.y, b.y, p.y) ||\n outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);exports.meshShader={vertex:triVertSrc,fragment:triFragSrc,attributes:[{name:'position',type:'vec4'},{name:'color',type:'vec4'},{name:'uv',type:'vec2'},{name:'vector',type:'vec4'}]};exports.pickShader={vertex:pickVertSrc,fragment:pickFragSrc,attributes:[{name:'position',type:'vec4'},{name:'id',type:'vec4'},{name:'vector',type:'vec4'}]};/***/},/***/7815:/***/function(module,__unused_webpack_exports,__nested_webpack_require_527334__){"use strict";var vec3=__nested_webpack_require_527334__(2931);var vec4=__nested_webpack_require_527334__(9970);var GRID_TYPES=['xyz','xzy','yxz','yzx','zxy','zyx'];var streamToTube=function(stream,maxDivergence,minDistance,maxNorm){var points=stream.points;var velocities=stream.velocities;var divergences=stream.divergences;var verts=[];var faces=[];var vectors=[];var previousVerts=[];var currentVerts=[];var intensities=[];var previousIntensity=0;var currentIntensity=0;var currentVector=vec4.create();var previousVector=vec4.create();var facets=8;for(var i=0;i0){for(var a=0;av)return i-1;}return i;};var clamp=function(v,min,max){return v