module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "fae3"); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports) { /* (ignored) */ /***/ }), /***/ "0000": /***/ (function(module, exports, __webpack_require__) { "use strict"; //High level idea: // 1. Use Clarkson's incremental construction to find convex hull // 2. Point location in triangulation by jump and walk module.exports = incrementalConvexHull var orient = __webpack_require__("92ba") var compareCell = __webpack_require__("24ad").compareCells function compareInt(a, b) { return a - b } function Simplex(vertices, adjacent, boundary) { this.vertices = vertices this.adjacent = adjacent this.boundary = boundary this.lastVisited = -1 } Simplex.prototype.flip = function() { var t = this.vertices[0] this.vertices[0] = this.vertices[1] this.vertices[1] = t var u = this.adjacent[0] this.adjacent[0] = this.adjacent[1] this.adjacent[1] = u } function GlueFacet(vertices, cell, index) { this.vertices = vertices this.cell = cell this.index = index } function compareGlue(a, b) { return compareCell(a.vertices, b.vertices) } function bakeOrient(d) { var code = ["function orient(){var tuple=this.tuple;return test("] for(var i=0; i<=d; ++i) { if(i > 0) { code.push(",") } code.push("tuple[", i, "]") } code.push(")}return orient") var proc = new Function("test", code.join("")) var test = orient[d+1] if(!test) { test = orient } return proc(test) } var BAKED = [] function Triangulation(dimension, vertices, simplices) { this.dimension = dimension this.vertices = vertices this.simplices = simplices this.interior = simplices.filter(function(c) { return !c.boundary }) this.tuple = new Array(dimension+1) for(var i=0; i<=dimension; ++i) { this.tuple[i] = this.vertices[i] } var o = BAKED[dimension] if(!o) { o = BAKED[dimension] = bakeOrient(dimension) } this.orient = o } var proto = Triangulation.prototype //Degenerate situation where we are on boundary, but coplanar to face proto.handleBoundaryDegeneracy = function(cell, point) { var d = this.dimension var n = this.vertices.length - 1 var tuple = this.tuple var verts = this.vertices //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate var toVisit = [ cell ] cell.lastVisited = -n while(toVisit.length > 0) { cell = toVisit.pop() var cellVerts = cell.vertices var cellAdj = cell.adjacent for(var i=0; i<=d; ++i) { var neighbor = cellAdj[i] if(!neighbor.boundary || neighbor.lastVisited <= -n) { continue } var nv = neighbor.vertices for(var j=0; j<=d; ++j) { var vv = nv[j] if(vv < 0) { tuple[j] = point } else { tuple[j] = verts[vv] } } var o = this.orient() if(o > 0) { return neighbor } neighbor.lastVisited = -n if(o === 0) { toVisit.push(neighbor) } } } return null } proto.walk = function(point, random) { //Alias local properties var n = this.vertices.length - 1 var d = this.dimension var verts = this.vertices var tuple = this.tuple //Compute initial jump cell var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1) var cell = this.interior[ initIndex ] //Start walking outerLoop: while(!cell.boundary) { var cellVerts = cell.vertices var cellAdj = cell.adjacent for(var i=0; i<=d; ++i) { tuple[i] = verts[cellVerts[i]] } cell.lastVisited = n //Find farthest adjacent cell for(var i=0; i<=d; ++i) { var neighbor = cellAdj[i] if(neighbor.lastVisited >= n) { continue } var prev = tuple[i] tuple[i] = point var o = this.orient() tuple[i] = prev if(o < 0) { cell = neighbor continue outerLoop } else { if(!neighbor.boundary) { neighbor.lastVisited = n } else { neighbor.lastVisited = -n } } } return } return cell } proto.addPeaks = function(point, cell) { var n = this.vertices.length - 1 var d = this.dimension var verts = this.vertices var tuple = this.tuple var interior = this.interior var simplices = this.simplices //Walking finished at boundary, time to add peaks var tovisit = [ cell ] //Stretch initial boundary cell into a peak cell.lastVisited = n cell.vertices[cell.vertices.indexOf(-1)] = n cell.boundary = false interior.push(cell) //Record a list of all new boundaries created by added peaks so we can glue them together when we are all done var glueFacets = [] //Do a traversal of the boundary walking outward from starting peak while(tovisit.length > 0) { //Pop off peak and walk over adjacent cells var cell = tovisit.pop() var cellVerts = cell.vertices var cellAdj = cell.adjacent var indexOfN = cellVerts.indexOf(n) if(indexOfN < 0) { continue } for(var i=0; i<=d; ++i) { if(i === indexOfN) { continue } //For each boundary neighbor of the cell var neighbor = cellAdj[i] if(!neighbor.boundary || neighbor.lastVisited >= n) { continue } var nv = neighbor.vertices //Test if neighbor is a peak if(neighbor.lastVisited !== -n) { //Compute orientation of p relative to each boundary peak var indexOfNeg1 = 0 for(var j=0; j<=d; ++j) { if(nv[j] < 0) { indexOfNeg1 = j tuple[j] = point } else { tuple[j] = verts[nv[j]] } } var o = this.orient() //Test if neighbor cell is also a peak if(o > 0) { nv[indexOfNeg1] = n neighbor.boundary = false interior.push(neighbor) tovisit.push(neighbor) neighbor.lastVisited = n continue } else { neighbor.lastVisited = -n } } var na = neighbor.adjacent //Otherwise, replace neighbor with new face var vverts = cellVerts.slice() var vadj = cellAdj.slice() var ncell = new Simplex(vverts, vadj, true) simplices.push(ncell) //Connect to neighbor var opposite = na.indexOf(cell) if(opposite < 0) { continue } na[opposite] = ncell vadj[indexOfN] = neighbor //Connect to cell vverts[i] = -1 vadj[i] = cell cellAdj[i] = ncell //Flip facet ncell.flip() //Add to glue list for(var j=0; j<=d; ++j) { var uu = vverts[j] if(uu < 0 || uu === n) { continue } var nface = new Array(d-1) var nptr = 0 for(var k=0; k<=d; ++k) { var vv = vverts[k] if(vv < 0 || k === j) { continue } nface[nptr++] = vv } glueFacets.push(new GlueFacet(nface, ncell, j)) } } } //Glue boundary facets together glueFacets.sort(compareGlue) for(var i=0; i+1= 0) { bcell[ptr++] = cv[j] } else { parity = j&1 } } if(parity === (d&1)) { var t = bcell[0] bcell[0] = bcell[1] bcell[1] = t } boundary.push(bcell) } } return boundary } function incrementalConvexHull(points, randomSearch) { var n = points.length if(n === 0) { throw new Error("Must have at least d+1 points") } var d = points[0].length if(n <= d) { throw new Error("Must input at least d+1 points") } //FIXME: This could be degenerate, but need to select d+1 non-coplanar points to bootstrap process var initialSimplex = points.slice(0, d+1) //Make sure initial simplex is positively oriented var o = orient.apply(void 0, initialSimplex) if(o === 0) { throw new Error("Input not in general position") } var initialCoords = new Array(d+1) for(var i=0; i<=d; ++i) { initialCoords[i] = i } if(o < 0) { initialCoords[0] = 1 initialCoords[1] = 0 } //Create initial topological index, glue pointers together (kind of messy) var initialCell = new Simplex(initialCoords, new Array(d+1), false) var boundary = initialCell.adjacent var list = new Array(d+2) for(var i=0; i<=d; ++i) { var verts = initialCoords.slice() for(var j=0; j<=d; ++j) { if(j === i) { verts[j] = -1 } } var t = verts[0] verts[0] = verts[1] verts[1] = t var cell = new Simplex(verts, new Array(d+1), true) boundary[i] = cell list[i] = cell } list[d+1] = initialCell for(var i=0; i<=d; ++i) { var verts = boundary[i].vertices var adj = boundary[i].adjacent for(var j=0; j<=d; ++j) { var v = verts[j] if(v < 0) { adj[j] = initialCell continue } for(var k=0; k<=d; ++k) { if(boundary[k].vertices.indexOf(v) < 0) { adj[j] = boundary[k] } } } } //Initialize triangles var triangles = new Triangulation(d, initialSimplex, list) //Insert remaining points var useRandom = !!randomSearch for(var i=d+1; i 0) { 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; i < prefixSum.length; ++i) { prefixSum[i] = prefixSum[i - 1] + prefixSum[i] } var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4]) for (i = 0; i < 256; ++i) { for (j = 0; j < 4; ++j) { dashTexture.set(i, 0, j, 0) } if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { dashTexture.set(i, 0, 0, 0) } else { dashTexture.set(i, 0, 0, 255) } } this.texture.setPixels(dashTexture) } } proto.dispose = function () { this.shader.dispose() this.vao.dispose() this.buffer.dispose() } proto.pick = function (selection) { if (!selection) { return null } if (selection.id !== this.pickId) { return null } var tau = unpackFloat( selection.value[0], selection.value[1], selection.value[2], 0) var index = bsearch.le(this.arcLength, tau) if (index < 0) { return null } if (index === this.arcLength.length - 1) { return new PickResult( this.arcLength[this.arcLength.length - 1], this.points[this.points.length - 1].slice(), index) } var a = this.points[index] var b = this.points[Math.min(index + 1, this.points.length - 1)] var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index]) var ti = 1.0 - t var x = [0, 0, 0] for (var i = 0; i < 3; ++i) { x[i] = ti * a[i] + t * b[i] } var dataIndex = Math.min((t < 0.5) ? index : (index + 1), this.points.length - 1) return new PickResult( tau, x, dataIndex, this.points[dataIndex]) } function createLinePlot (options) { var gl = options.gl || (options.scene && options.scene.gl) var shader = createShader(gl) shader.attributes.position.location = 0 shader.attributes.nextPosition.location = 1 shader.attributes.arcLength.location = 2 shader.attributes.lineWidth.location = 3 shader.attributes.color.location = 4 var pickShader = createPickShader(gl) pickShader.attributes.position.location = 0 pickShader.attributes.nextPosition.location = 1 pickShader.attributes.arcLength.location = 2 pickShader.attributes.lineWidth.location = 3 pickShader.attributes.color.location = 4 var buffer = createBuffer(gl) var vao = createVAO(gl, [ { 'buffer': buffer, 'size': 3, 'offset': 0, 'stride': 48 }, { 'buffer': buffer, 'size': 3, 'offset': 12, 'stride': 48 }, { 'buffer': buffer, 'size': 1, 'offset': 24, 'stride': 48 }, { 'buffer': buffer, 'size': 1, 'offset': 28, 'stride': 48 }, { 'buffer': buffer, 'size': 4, 'offset': 32, 'stride': 48 } ]) // Create texture for dash pattern var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4]) for (var i = 0; i < 256 * 4; ++i) { defaultTexture.data[i] = 255 } var texture = createTexture(gl, defaultTexture) texture.wrap = gl.REPEAT var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) linePlot.update(options) return linePlot } /***/ }), /***/ "0054": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorscaleCalc = __webpack_require__("3aa8"); // 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' }); } }; /***/ }), /***/ "0082": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var isNumeric = __webpack_require__("19b2"); 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); } }); }; /***/ }), /***/ "00bd": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "00fe": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { moduleType: 'trace', name: 'ohlc', basePlotModule: __webpack_require__("91cd"), categories: ['cartesian', 'svg', 'showLegend'], meta: { }, attributes: __webpack_require__("6657"), supplyDefaults: __webpack_require__("9143"), calc: __webpack_require__("bb14").calc, plot: __webpack_require__("a56d"), style: __webpack_require__("b0f1"), hoverPoints: __webpack_require__("d945").hoverPoints, selectPoints: __webpack_require__("ab9c") }; /***/ }), /***/ "0103": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** @module color-normalize */ var rgba = __webpack_require__("7f20") var clamp = __webpack_require__("53a5") var dtype = __webpack_require__("7831") module.exports = function normalize (color, type) { if (type === 'float' || !type) type = 'array' if (type === 'uint') type = 'uint8' if (type === 'uint_clamped') type = 'uint8_clamped' var Ctor = dtype(type) var output = new Ctor(4) var normalize = type !== 'uint8' && type !== 'uint8_clamped' // attempt to parse non-array arguments if (!color.length || typeof color === 'string') { color = rgba(color) color[0] /= 255 color[1] /= 255 color[2] /= 255 } // 0, 1 are possible contradictory values for Arrays: // [1,1,1] input gives [1,1,1] output instead of [1/255,1/255,1/255], which may be collision if input is meant to be uint. // converting [1,1,1] to [1/255,1/255,1/255] in case of float input gives larger mistake since [1,1,1] float is frequent edge value, whereas [0,1,1], [1,1,1] etc. uint inputs are relatively rare if (isInt(color)) { output[0] = color[0] output[1] = color[1] output[2] = color[2] output[3] = color[3] != null ? color[3] : 255 if (normalize) { output[0] /= 255 output[1] /= 255 output[2] /= 255 output[3] /= 255 } return output } if (!normalize) { output[0] = clamp(Math.floor(color[0] * 255), 0, 255) output[1] = clamp(Math.floor(color[1] * 255), 0, 255) output[2] = clamp(Math.floor(color[2] * 255), 0, 255) output[3] = color[3] == null ? 255 : clamp(Math.floor(color[3] * 255), 0, 255) } else { output[0] = color[0] output[1] = color[1] output[2] = color[2] output[3] = color[3] != null ? color[3] : 1 } return output } function isInt(color) { if (color instanceof Uint8Array || color instanceof Uint8ClampedArray) return true if (Array.isArray(color) && (color[0] > 1 || color[0] === 0) && (color[1] > 1 || color[1] === 0) && (color[2] > 1 || color[2] === 0) && (!color[3] || color[3] > 1) ) return true return false } /***/ }), /***/ "0119": /***/ (function(module, exports, __webpack_require__) { "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(x < a) { break } else if(x === a && y < b) { break } data[jptr] = x data[jptr+1] = y jptr -= 2 } data[jptr] = a data[jptr+1] = b } } function swap(i, j, data) { i *= 2 j *= 2 var x = data[i] var y = data[i+1] data[i] = data[j] data[i+1] = data[j+1] data[j] = x data[j+1] = y } function move(i, j, data) { i *= 2 j *= 2 data[i] = data[j] data[i+1] = data[j+1] } function rotate(i, j, k, data) { i *= 2 j *= 2 k *= 2 var x = data[i] var y = data[i+1] data[i] = data[j] data[i+1] = data[j+1] data[j] = data[k] data[j+1] = data[k+1] data[k] = x data[k+1] = y } function shufflePivot(i, j, px, py, data) { i *= 2 j *= 2 data[i] = data[j] data[j] = px data[i+1] = data[j+1] data[j+1] = py } function compare(i, j, data) { i *= 2 j *= 2 var x = data[i], y = data[j] if(x < y) { return false } else if(x === y) { return data[i+1] > data[j+1] } return true } function comparePivot(i, y, b, data) { i *= 2 var x = data[i] if(x < y) { return true } else if(x === y) { return data[i+1] < b } return false } function quickSort(left, right, data) { var sixth = (right - left + 1) / 6 | 0, index1 = left + sixth, index5 = right - sixth, index3 = left + right >> 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 (--great < k) { break; } continue; } else { if (comparePivot(great, pivot1X, pivot1Y, data)) { rotate(k, less, great, data) ++less; --great; } else { swap(k, great, data) --great; } break; } } } } } shufflePivot(left, less-1, pivot1X, pivot1Y, data) shufflePivot(right, great+1, pivot2X, pivot2Y, data) if (less - 2 - left <= INSERT_SORT_CUTOFF) { insertionSort(left, less - 2, data); } else { quickSort(left, less - 2, data); } if (right - (great + 2) <= INSERT_SORT_CUTOFF) { insertionSort(great + 2, right, data); } else { quickSort(great + 2, right, data); } if (great - less <= INSERT_SORT_CUTOFF) { insertionSort(less, great, data); } else { quickSort(less, great, data); } } /***/ }), /***/ "014c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { circle: '●', 'circle-open': '○', square: '■', 'square-open': '□', diamond: '◆', 'diamond-open': '◇', cross: '+', x: '❌' }; /***/ }), /***/ "019a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint block-scoped-var: 0*/ /* eslint no-redeclare: 0*/ module.exports = computeTickMarks; var Axes = __webpack_require__("0642"); var Lib = __webpack_require__("fc26"); 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); 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); } /***/ }), /***/ "01db": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("b964"); /***/ }), /***/ "0230": /***/ (function(module, exports, __webpack_require__) { /* * World Calendars * https://github.com/alexcjohnson/world-calendars * * Batch-converted from kbwood/calendars * Many thanks to Keith Wood and all of the contributors to the original project! * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* http://keith-wood.name/calendars.html Calendars for jQuery v2.0.2. Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009. Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ var assign = __webpack_require__("320c"); function Calendars() { this.regionalOptions = []; this.regionalOptions[''] = { invalidCalendar: 'Calendar {0} not found', invalidDate: 'Invalid {0} date', invalidMonth: 'Invalid {0} month', invalidYear: 'Invalid {0} year', differentCalendars: 'Cannot mix {0} and {1} dates' }; this.local = this.regionalOptions['']; this.calendars = {}; this._localCals = {}; } /** Create the calendars plugin.

Provides support for various world calendars in a consistent manner.

@class Calendars @example _exports.instance('julian').newDate(2014, 12, 25) */ assign(Calendars.prototype, { /** Obtain a calendar implementation and localisation. @memberof Calendars @param [name='gregorian'] {string} The name of the calendar, e.g. 'gregorian', 'persian', 'islamic'. @param [language=''] {string} The language code to use for localisation (default is English). @return {Calendar} The calendar and localisation. @throws Error if calendar not found. */ instance: function(name, language) { name = (name || 'gregorian').toLowerCase(); language = language || ''; var cal = this._localCals[name + '-' + language]; if (!cal && this.calendars[name]) { cal = new this.calendars[name](language); this._localCals[name + '-' + language] = cal; } if (!cal) { throw (this.local.invalidCalendar || this.regionalOptions[''].invalidCalendar). replace(/\{0\}/, name); } return cal; }, /** Create a new date - for today if no other parameters given. @memberof Calendars @param year {CDate|number} The date to copy or the year for the date. @param [month] {number} The month for the date. @param [day] {number} The day for the date. @param [calendar='gregorian'] {BaseCalendar|string} The underlying calendar or the name of the calendar. @param [language=''] {string} The language to use for localisation (default English). @return {CDate} The new date. @throws Error if an invalid date. */ newDate: function(year, month, day, calendar, language) { calendar = (year != null && year.year ? year.calendar() : (typeof calendar === 'string' ? this.instance(calendar, language) : calendar)) || this.instance(); return calendar.newDate(year, month, day); }, /** A simple digit substitution function for localising numbers via the Calendar digits option. @member Calendars @param digits {string[]} The substitute digits, for 0 through 9. @return {function} The substitution function. */ substituteDigits: function(digits) { return function(value) { return (value + '').replace(/[0-9]/g, function(digit) { return digits[digit]; }); } }, /** Digit substitution function for localising Chinese style numbers via the Calendar digits option. @member Calendars @param digits {string[]} The substitute digits, for 0 through 9. @param powers {string[]} The characters denoting powers of 10, i.e. 1, 10, 100, 1000. @return {function} The substitution function. */ substituteChineseDigits: function(digits, powers) { return function(value) { var localNumber = ''; var power = 0; while (value > 0) { var units = value % 10; localNumber = (units === 0 ? '' : digits[units] + powers[power]) + localNumber; power++; value = Math.floor(value / 10); } if (localNumber.indexOf(digits[1] + powers[1]) === 0) { localNumber = localNumber.substr(1); } return localNumber || digits[0]; } } }); /** Generic date, based on a particular calendar. @class CDate @param calendar {BaseCalendar} The underlying calendar implementation. @param year {number} The year for this date. @param month {number} The month for this date. @param day {number} The day for this date. @return {CDate} The date object. @throws Error if an invalid date. */ function CDate(calendar, year, month, day) { this._calendar = calendar; this._year = year; this._month = month; this._day = day; if (this._calendar._validateLevel === 0 && !this._calendar.isValid(this._year, this._month, this._day)) { throw (_exports.local.invalidDate || _exports.regionalOptions[''].invalidDate). replace(/\{0\}/, this._calendar.local.name); } } /** Pad a numeric value with leading zeroes. @private @param value {number} The number to format. @param length {number} The minimum length. @return {string} The formatted number. */ function pad(value, length) { value = '' + value; return '000000'.substring(0, length - value.length) + value; } assign(CDate.prototype, { /** Create a new date. @memberof CDate @param [year] {CDate|number} The date to copy or the year for the date (default this date). @param [month] {number} The month for the date. @param [day] {number} The day for the date. @return {CDate} The new date. @throws Error if an invalid date. */ newDate: function(year, month, day) { return this._calendar.newDate((year == null ? this : year), month, day); }, /** Set or retrieve the year for this date. @memberof CDate @param [year] {number} The year for the date. @return {number|CDate} The date's year (if no parameter) or the updated date. @throws Error if an invalid date. */ year: function(year) { return (arguments.length === 0 ? this._year : this.set(year, 'y')); }, /** Set or retrieve the month for this date. @memberof CDate @param [month] {number} The month for the date. @return {number|CDate} The date's month (if no parameter) or the updated date. @throws Error if an invalid date. */ month: function(month) { return (arguments.length === 0 ? this._month : this.set(month, 'm')); }, /** Set or retrieve the day for this date. @memberof CDate @param [day] {number} The day for the date. @return {number|CData} The date's day (if no parameter) or the updated date. @throws Error if an invalid date. */ day: function(day) { return (arguments.length === 0 ? this._day : this.set(day, 'd')); }, /** Set new values for this date. @memberof CDate @param year {number} The year for the date. @param month {number} The month for the date. @param day {number} The day for the date. @return {CDate} The updated date. @throws Error if an invalid date. */ date: function(year, month, day) { if (!this._calendar.isValid(year, month, day)) { throw (_exports.local.invalidDate || _exports.regionalOptions[''].invalidDate). replace(/\{0\}/, this._calendar.local.name); } this._year = year; this._month = month; this._day = day; return this; }, /** Determine whether this date is in a leap year. @memberof CDate @return {boolean} true if this is a leap year, false if not. */ leapYear: function() { return this._calendar.leapYear(this); }, /** Retrieve the epoch designator for this date, e.g. BCE or CE. @memberof CDate @return {string} The current epoch. */ epoch: function() { return this._calendar.epoch(this); }, /** Format the year, if not a simple sequential number. @memberof CDate @return {string} The formatted year. */ formatYear: function() { return this._calendar.formatYear(this); }, /** Retrieve the month of the year for this date, i.e. the month's position within a numbered year. @memberof CDate @return {number} The month of the year: minMonth to months per year. */ monthOfYear: function() { return this._calendar.monthOfYear(this); }, /** Retrieve the week of the year for this date. @memberof CDate @return {number} The week of the year: 1 to weeks per year. */ weekOfYear: function() { return this._calendar.weekOfYear(this); }, /** Retrieve the number of days in the year for this date. @memberof CDate @return {number} The number of days in this year. */ daysInYear: function() { return this._calendar.daysInYear(this); }, /** Retrieve the day of the year for this date. @memberof CDate @return {number} The day of the year: 1 to days per year. */ dayOfYear: function() { return this._calendar.dayOfYear(this); }, /** Retrieve the number of days in the month for this date. @memberof CDate @return {number} The number of days. */ daysInMonth: function() { return this._calendar.daysInMonth(this); }, /** Retrieve the day of the week for this date. @memberof CDate @return {number} The day of the week: 0 to number of days - 1. */ dayOfWeek: function() { return this._calendar.dayOfWeek(this); }, /** Determine whether this date is a week day. @memberof CDate @return {boolean} true if a week day, false if not. */ weekDay: function() { return this._calendar.weekDay(this); }, /** Retrieve additional information about this date. @memberof CDate @return {object} Additional information - contents depends on calendar. */ extraInfo: function() { return this._calendar.extraInfo(this); }, /** Add period(s) to a date. @memberof CDate @param offset {number} The number of periods to adjust by. @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day. @return {CDate} The updated date. */ add: function(offset, period) { return this._calendar.add(this, offset, period); }, /** Set a portion of the date. @memberof CDate @param value {number} The new value for the period. @param period {string} One of 'y' for year, 'm' for month, 'd' for day. @return {CDate} The updated date. @throws Error if not a valid date. */ set: function(value, period) { return this._calendar.set(this, value, period); }, /** Compare this date to another date. @memberof CDate @param date {CDate} The other date. @return {number} -1 if this date is before the other date, 0 if they are equal, or +1 if this date is after the other date. */ compareTo: function(date) { if (this._calendar.name !== date._calendar.name) { throw (_exports.local.differentCalendars || _exports.regionalOptions[''].differentCalendars). replace(/\{0\}/, this._calendar.local.name).replace(/\{1\}/, date._calendar.local.name); } var c = (this._year !== date._year ? this._year - date._year : this._month !== date._month ? this.monthOfYear() - date.monthOfYear() : this._day - date._day); return (c === 0 ? 0 : (c < 0 ? -1 : +1)); }, /** Retrieve the calendar backing this date. @memberof CDate @return {BaseCalendar} The calendar implementation. */ calendar: function() { return this._calendar; }, /** Retrieve the Julian date equivalent for this date, i.e. days since January 1, 4713 BCE Greenwich noon. @memberof CDate @return {number} The equivalent Julian date. */ toJD: function() { return this._calendar.toJD(this); }, /** Create a new date from a Julian date. @memberof CDate @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { return this._calendar.fromJD(jd); }, /** Convert this date to a standard (Gregorian) JavaScript Date. @memberof CDate @return {Date} The equivalent JavaScript date. */ toJSDate: function() { return this._calendar.toJSDate(this); }, /** Create a new date from a standard (Gregorian) JavaScript Date. @memberof CDate @param jsd {Date} The JavaScript date to convert. @return {CDate} The equivalent date. */ fromJSDate: function(jsd) { return this._calendar.fromJSDate(jsd); }, /** Convert to a string for display. @memberof CDate @return {string} This date as a string. */ toString: function() { return (this.year() < 0 ? '-' : '') + pad(Math.abs(this.year()), 4) + '-' + pad(this.month(), 2) + '-' + pad(this.day(), 2); } }); /** Basic functionality for all calendars. Other calendars should extend this:
OtherCalendar.prototype = new BaseCalendar;
@class BaseCalendar */ function BaseCalendar() { this.shortYearCutoff = '+10'; } assign(BaseCalendar.prototype, { _validateLevel: 0, // "Stack" to turn validation on/off /** Create a new date within this calendar - today if no parameters given. @memberof BaseCalendar @param year {CDate|number} The date to duplicate or the year for the date. @param [month] {number} The month for the date. @param [day] {number} The day for the date. @return {CDate} The new date. @throws Error if not a valid date or a different calendar used. */ newDate: function(year, month, day) { if (year == null) { return this.today(); } if (year.year) { this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); day = year.day(); month = year.month(); year = year.year(); } return new CDate(this, year, month, day); }, /** Create a new date for today. @memberof BaseCalendar @return {CDate} Today's date. */ today: function() { return this.fromJSDate(new Date()); }, /** Retrieve the epoch designator for this date. @memberof BaseCalendar @param year {CDate|number} The date to examine or the year to examine. @return {string} The current epoch. @throws Error if an invalid year or a different calendar used. */ epoch: function(year) { var date = this._validate(year, this.minMonth, this.minDay, _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear); return (date.year() < 0 ? this.local.epochs[0] : this.local.epochs[1]); }, /** Format the year, if not a simple sequential number @memberof BaseCalendar @param year {CDate|number} The date to format or the year to format. @return {string} The formatted year. @throws Error if an invalid year or a different calendar used. */ formatYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear); return (date.year() < 0 ? '-' : '') + pad(Math.abs(date.year()), 4) }, /** Retrieve the number of months in a year. @memberof BaseCalendar @param year {CDate|number} The date to examine or the year to examine. @return {number} The number of months. @throws Error if an invalid year or a different calendar used. */ monthsInYear: function(year) { this._validate(year, this.minMonth, this.minDay, _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear); return 12; }, /** Calculate the month's ordinal position within the year - for those calendars that don't start at month 1! @memberof BaseCalendar @param year {CDate|number} The date to examine or the year to examine. @param month {number} The month to examine. @return {number} The ordinal position, starting from minMonth. @throws Error if an invalid year/month or a different calendar used. */ monthOfYear: function(year, month) { var date = this._validate(year, month, this.minDay, _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth); return (date.month() + this.monthsInYear(date) - this.firstMonth) % this.monthsInYear(date) + this.minMonth; }, /** Calculate actual month from ordinal position, starting from minMonth. @memberof BaseCalendar @param year {number} The year to examine. @param ord {number} The month's ordinal position. @return {number} The month's number. @throws Error if an invalid year/month. */ fromMonthOfYear: function(year, ord) { var m = (ord + this.firstMonth - 2 * this.minMonth) % this.monthsInYear(year) + this.minMonth; this._validate(year, m, this.minDay, _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth); return m; }, /** Retrieve the number of days in a year. @memberof BaseCalendar @param year {CDate|number} The date to examine or the year to examine. @return {number} The number of days. @throws Error if an invalid year or a different calendar used. */ daysInYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear); return (this.leapYear(date) ? 366 : 365); }, /** Retrieve the day of the year for a date. @memberof BaseCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {number} The day of the year. @throws Error if an invalid date or a different calendar used. */ dayOfYear: function(year, month, day) { var date = this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); return date.toJD() - this.newDate(date.year(), this.fromMonthOfYear(date.year(), this.minMonth), this.minDay).toJD() + 1; }, /** Retrieve the number of days in a week. @memberof BaseCalendar @return {number} The number of days. */ daysInWeek: function() { return 7; }, /** Retrieve the day of the week for a date. @memberof BaseCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {number} The day of the week: 0 to number of days - 1. @throws Error if an invalid date or a different calendar used. */ dayOfWeek: function(year, month, day) { var date = this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); return (Math.floor(this.toJD(date)) + 2) % this.daysInWeek(); }, /** Retrieve additional information about a date. @memberof BaseCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used. */ extraInfo: function(year, month, day) { this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); return {}; }, /** Add period(s) to a date. Cater for no year zero. @memberof BaseCalendar @param date {CDate} The starting date. @param offset {number} The number of periods to adjust by. @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day. @return {CDate} The updated date. @throws Error if a different calendar used. */ add: function(date, offset, period) { this._validate(date, this.minMonth, this.minDay, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); return this._correctAdd(date, this._add(date, offset, period), offset, period); }, /** Add period(s) to a date. @memberof BaseCalendar @private @param date {CDate} The starting date. @param offset {number} The number of periods to adjust by. @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day. @return {CDate} The updated date. */ _add: function(date, offset, period) { this._validateLevel++; if (period === 'd' || period === 'w') { var jd = date.toJD() + offset * (period === 'w' ? this.daysInWeek() : 1); var d = date.calendar().fromJD(jd); this._validateLevel--; return [d.year(), d.month(), d.day()]; } try { var y = date.year() + (period === 'y' ? offset : 0); var m = date.monthOfYear() + (period === 'm' ? offset : 0); var d = date.day();// + (period === 'd' ? offset : 0) + //(period === 'w' ? offset * this.daysInWeek() : 0); var resyncYearMonth = function(calendar) { while (m < calendar.minMonth) { y--; m += calendar.monthsInYear(y); } var yearMonths = calendar.monthsInYear(y); while (m > yearMonths - 1 + calendar.minMonth) { y++; m -= yearMonths; yearMonths = calendar.monthsInYear(y); } }; if (period === 'y') { if (date.month() !== this.fromMonthOfYear(y, m)) { // Hebrew m = this.newDate(y, date.month(), this.minDay).monthOfYear(); } m = Math.min(m, this.monthsInYear(y)); d = Math.min(d, this.daysInMonth(y, this.fromMonthOfYear(y, m))); } else if (period === 'm') { resyncYearMonth(this); d = Math.min(d, this.daysInMonth(y, this.fromMonthOfYear(y, m))); } var ymd = [y, this.fromMonthOfYear(y, m), d]; this._validateLevel--; return ymd; } catch (e) { this._validateLevel--; throw e; } }, /** Correct a candidate date after adding period(s) to a date. Handle no year zero if necessary. @memberof BaseCalendar @private @param date {CDate} The starting date. @param ymd {number[]} The added date. @param offset {number} The number of periods to adjust by. @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day. @return {CDate} The updated date. */ _correctAdd: function(date, ymd, offset, period) { if (!this.hasYearZero && (period === 'y' || period === 'm')) { if (ymd[0] === 0 || // In year zero (date.year() > 0) !== (ymd[0] > 0)) { // Crossed year zero var adj = {y: [1, 1, 'y'], m: [1, this.monthsInYear(-1), 'm'], w: [this.daysInWeek(), this.daysInYear(-1), 'd'], d: [1, this.daysInYear(-1), 'd']}[period]; var dir = (offset < 0 ? -1 : +1); ymd = this._add(date, offset * adj[0] + dir * adj[1], adj[2]); } } return date.date(ymd[0], ymd[1], ymd[2]); }, /** Set a portion of the date. @memberof BaseCalendar @param date {CDate} The starting date. @param value {number} The new value for the period. @param period {string} One of 'y' for year, 'm' for month, 'd' for day. @return {CDate} The updated date. @throws Error if an invalid date or a different calendar used. */ set: function(date, value, period) { this._validate(date, this.minMonth, this.minDay, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); var y = (period === 'y' ? value : date.year()); var m = (period === 'm' ? value : date.month()); var d = (period === 'd' ? value : date.day()); if (period === 'y' || period === 'm') { d = Math.min(d, this.daysInMonth(y, m)); } return date.date(y, m, d); }, /** Determine whether a date is valid for this calendar. @memberof BaseCalendar @param year {number} The year to examine. @param month {number} The month to examine. @param day {number} The day to examine. @return {boolean} true if a valid date, false if not. */ isValid: function(year, month, day) { this._validateLevel++; var valid = (this.hasYearZero || year !== 0); if (valid) { var date = this.newDate(year, month, this.minDay); valid = (month >= this.minMonth && month - this.minMonth < this.monthsInYear(date)) && (day >= this.minDay && day - this.minDay < this.daysInMonth(date)); } this._validateLevel--; return valid; }, /** Convert the date to a standard (Gregorian) JavaScript Date. @memberof BaseCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {Date} The equivalent JavaScript date. @throws Error if an invalid date or a different calendar used. */ toJSDate: function(year, month, day) { var date = this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); return _exports.instance().fromJD(this.toJD(date)).toJSDate(); }, /** Convert the date from a standard (Gregorian) JavaScript Date. @memberof BaseCalendar @param jsd {Date} The JavaScript date. @return {CDate} The equivalent calendar date. */ fromJSDate: function(jsd) { return this.fromJD(_exports.instance().fromJSDate(jsd).toJD()); }, /** Check that a candidate date is from the same calendar and is valid. @memberof BaseCalendar @private @param year {CDate|number} The date to validate or the year to validate. @param [month] {number} The month to validate. @param [day] {number} The day to validate. @param error {string} Rrror message if invalid. @throws Error if different calendars used or invalid date. */ _validate: function(year, month, day, error) { if (year.year) { if (this._validateLevel === 0 && this.name !== year.calendar().name) { throw (_exports.local.differentCalendars || _exports.regionalOptions[''].differentCalendars). replace(/\{0\}/, this.local.name).replace(/\{1\}/, year.calendar().local.name); } return year; } try { this._validateLevel++; if (this._validateLevel === 1 && !this.isValid(year, month, day)) { throw error.replace(/\{0\}/, this.local.name); } var date = this.newDate(year, month, day); this._validateLevel--; return date; } catch (e) { this._validateLevel--; throw e; } } }); /** Implementation of the Proleptic Gregorian Calendar. See http://en.wikipedia.org/wiki/Gregorian_calendar and http://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar. @class GregorianCalendar @augments BaseCalendar @param [language=''] {string} The language code (default English) for localisation. */ function GregorianCalendar(language) { this.local = this.regionalOptions[language] || this.regionalOptions['']; } GregorianCalendar.prototype = new BaseCalendar; assign(GregorianCalendar.prototype, { /** The calendar name. @memberof GregorianCalendar */ name: 'Gregorian', /** Julian date of start of Gregorian epoch: 1 January 0001 CE. @memberof GregorianCalendar */ jdEpoch: 1721425.5, /** Days per month in a common year. @memberof GregorianCalendar */ daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], /** true if has a year zero, false if not. @memberof GregorianCalendar */ hasYearZero: false, /** The minimum month number. @memberof GregorianCalendar */ minMonth: 1, /** The first month in the year. @memberof GregorianCalendar */ firstMonth: 1, /** The minimum day number. @memberof GregorianCalendar */ minDay: 1, /** Localisations for the plugin. Entries are objects indexed by the language code ('' being the default US/English). Each object has the following attributes. @memberof GregorianCalendar @property name {string} The calendar name. @property epochs {string[]} The epoch names. @property monthNames {string[]} The long names of the months of the year. @property monthNamesShort {string[]} The short names of the months of the year. @property dayNames {string[]} The long names of the days of the week. @property dayNamesShort {string[]} The short names of the days of the week. @property dayNamesMin {string[]} The minimal names of the days of the week. @property dateFormat {string} The date format for this calendar. See the options on formatDate for details. @property firstDay {number} The number of the first day of the week, starting at 0. @property isRTL {number} true if this localisation reads right-to-left. */ regionalOptions: { // Localisations '': { name: 'Gregorian', epochs: ['BCE', 'CE'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], digits: null, dateFormat: 'mm/dd/yyyy', firstDay: 0, isRTL: false } }, /** Determine whether this date is in a leap year. @memberof GregorianCalendar @param year {CDate|number} The date to examine or the year to examine. @return {boolean} true if this is a leap year, false if not. @throws Error if an invalid year or a different calendar used. */ leapYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, _exports.local.invalidYear || _exports.regionalOptions[''].invalidYear); var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }, /** Determine the week of the year for a date - ISO 8601. @memberof GregorianCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {number} The week of the year, starting from 1. @throws Error if an invalid date or a different calendar used. */ weekOfYear: function(year, month, day) { // Find Thursday of this week starting on Monday var checkDate = this.newDate(year, month, day); checkDate.add(4 - (checkDate.dayOfWeek() || 7), 'd'); return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1; }, /** Retrieve the number of days in a month. @memberof GregorianCalendar @param year {CDate|number} The date to examine or the year of the month. @param [month] {number} The month. @return {number} The number of days in this month. @throws Error if an invalid month/year or a different calendar used. */ daysInMonth: function(year, month) { var date = this._validate(year, month, this.minDay, _exports.local.invalidMonth || _exports.regionalOptions[''].invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, /** Determine whether this date is a week day. @memberof GregorianCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {boolean} true if a week day, false if not. @throws Error if an invalid date or a different calendar used. */ weekDay: function(year, month, day) { return (this.dayOfWeek(year, month, day) || 7) < 6; }, /** Retrieve the Julian date equivalent for this date, i.e. days since January 1, 4713 BCE Greenwich noon. @memberof GregorianCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(year, month, day) { var date = this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); year = date.year(); month = date.month(); day = date.day(); if (year < 0) { year++; } // No year zero // Jean Meeus algorithm, "Astronomical Algorithms", 1991 if (month < 3) { month += 12; year--; } var a = Math.floor(year / 100); var b = 2 - a + Math.floor(a / 4); return Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + day + b - 1524.5; }, /** Create a new date from a Julian date. @memberof GregorianCalendar @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { // Jean Meeus algorithm, "Astronomical Algorithms", 1991 var z = Math.floor(jd + 0.5); var a = Math.floor((z - 1867216.25) / 36524.25); a = z + 1 + a - Math.floor(a / 4); var b = a + 1524; var c = Math.floor((b - 122.1) / 365.25); var d = Math.floor(365.25 * c); var e = Math.floor((b - d) / 30.6001); var day = b - d - Math.floor(e * 30.6001); var month = e - (e > 13.5 ? 13 : 1); var year = c - (month > 2.5 ? 4716 : 4715); if (year <= 0) { year--; } // No year zero return this.newDate(year, month, day); }, /** Convert this date to a standard (Gregorian) JavaScript Date. @memberof GregorianCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {Date} The equivalent JavaScript date. @throws Error if an invalid date or a different calendar used. */ toJSDate: function(year, month, day) { var date = this._validate(year, month, day, _exports.local.invalidDate || _exports.regionalOptions[''].invalidDate); var jsd = new Date(date.year(), date.month() - 1, date.day()); jsd.setHours(0); jsd.setMinutes(0); jsd.setSeconds(0); jsd.setMilliseconds(0); // Hours may be non-zero on daylight saving cut-over: // > 12 when midnight changeover, but then cannot generate // midnight datetime, so jump to 1AM, otherwise reset. jsd.setHours(jsd.getHours() > 12 ? jsd.getHours() + 2 : 0); return jsd; }, /** Create a new date from a standard (Gregorian) JavaScript Date. @memberof GregorianCalendar @param jsd {Date} The JavaScript date to convert. @return {CDate} The equivalent date. */ fromJSDate: function(jsd) { return this.newDate(jsd.getFullYear(), jsd.getMonth() + 1, jsd.getDate()); } }); // Singleton manager var _exports = module.exports = new Calendars(); // Date template _exports.cdate = CDate; // Base calendar template _exports.baseCalendar = BaseCalendar; // Gregorian calendar implementation _exports.calendars.gregorian = GregorianCalendar; /***/ }), /***/ "0248": /***/ (function(module, exports, __webpack_require__) { "use strict"; var warp = __webpack_require__("86d9") var invert = __webpack_require__("ba76") module.exports = applyHomography function applyHomography(dest, src, Xi) { var n = src.dimension var X = invert([], Xi) warp(dest, src, function(out_c, inp_c) { for(var i=0; i fs * threshold) { var emWidth = (kerningWidth - width) / fs table[pair] = emWidth * 1000 } } return table } function createPairs (range) { var pairs = [] for (var i = range[0]; i <= range[1]; i++) { var leftChar = String.fromCharCode(i) for (var j = range[0]; j < range[1]; j++) { var rightChar = String.fromCharCode(j) var pair = leftChar + rightChar pairs.push(pair) } } return pairs } /***/ }), /***/ "02e4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hover = __webpack_require__("98e7"); var makeHoverPointText = __webpack_require__("efcd").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 }; /***/ }), /***/ "02ea": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Color = __webpack_require__("d115"); var colorScaleAttrs = __webpack_require__("f4e9"); var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var baseAttrs = __webpack_require__("a876"); var extendFlat = __webpack_require__("9092").extendFlat; var overrideAll = __webpack_require__("cb34").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(), 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, }, _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; /***/ }), /***/ "030a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Plotly = __webpack_require__("c17d"); // traces Plotly.register([ __webpack_require__("f725"), __webpack_require__("b7e7"), __webpack_require__("3eab"), __webpack_require__("4fc7"), __webpack_require__("90a6"), __webpack_require__("b905"), __webpack_require__("5cc5"), __webpack_require__("664d"), __webpack_require__("6578"), __webpack_require__("3efe"), __webpack_require__("6ca5"), __webpack_require__("831f"), __webpack_require__("4746"), __webpack_require__("21dd"), __webpack_require__("6d0a"), __webpack_require__("f36e"), __webpack_require__("a8b9"), __webpack_require__("372f"), __webpack_require__("f17e"), __webpack_require__("6626"), __webpack_require__("0eb8"), __webpack_require__("f522"), __webpack_require__("2781"), __webpack_require__("388d"), __webpack_require__("c80f"), __webpack_require__("46c1"), __webpack_require__("2f68"), __webpack_require__("b7bb"), __webpack_require__("f3ca"), __webpack_require__("44d4"), __webpack_require__("f366"), __webpack_require__("01db"), __webpack_require__("7016"), __webpack_require__("d47b"), __webpack_require__("f846"), __webpack_require__("aa2c"), __webpack_require__("82e4"), __webpack_require__("f2a9"), __webpack_require__("bd75"), __webpack_require__("e2f4"), __webpack_require__("dff2"), __webpack_require__("75ac"), __webpack_require__("1cfc"), __webpack_require__("ff5b"), __webpack_require__("2d12") ]); // transforms // // Please note that all *transform* methods are executed before // all *calcTransform* methods - which could possibly lead to // unexpected results when applying multiple transforms of different types // to a given trace. // // For more info, see: // https://github.com/plotly/plotly.js/pull/978#pullrequestreview-2403353 // Plotly.register([ __webpack_require__("2594"), __webpack_require__("4b14"), __webpack_require__("9633"), __webpack_require__("d2d4") ]); // components Plotly.register([ __webpack_require__("e1f5") ]); module.exports = Plotly; /***/ }), /***/ "0316": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Axes = __webpack_require__("0642"); 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; }; /***/ }), /***/ "0324": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // remove opacity for any trace that has a fill or is filled to module.exports = function crossTraceDefaults(fullData) { for(var 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; } } } } }; /***/ }), /***/ "0365": /***/ (function(module, exports) { module.exports = clone; /** * Creates a new vec3 initialized with values from an existing vector * * @param {vec3} a vector to clone * @returns {vec3} a new 3D vector */ function clone(a) { var out = new Float32Array(3) out[0] = a[0] out[1] = a[1] out[2] = a[2] return out } /***/ }), /***/ "0366": /***/ (function(module, exports, __webpack_require__) { var aFunction = __webpack_require__("1c0b"); // optional / simple context binding module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 0: return function () { return fn.call(that); }; case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /***/ "0379": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* global MathJax:false */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var xmlnsNamespaces = __webpack_require__("73c9"); var LINE_SPACING = __webpack_require__("63dc").LINE_SPACING; // text converter function getSize(_selection, _dimension) { return _selection.node().getBoundingClientRect()[_dimension]; } 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')) && (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); } newSvg.attr({ 'class': svgClass, height: _svgBBox.height, 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 newSvgW = getSize(g, 'width'); var newSvgH = getSize(g, 'height'); var newX = +_context.attr('x') - newSvgW * {start: 0, middle: 0.5, end: 1}[_context.attr('text-anchor') || 'start']; // font baseline is about 1/4 fontSize below centerline var textHeight = fontSize || getSize(_context, 'height'); var dy = -textHeight / 4; if(svgClass[0] === 'y') { mathjaxGroup.attr({ transform: 'rotate(' + [-90, +_context.attr('x'), +_context.attr('y')] + ') translate(' + [-newSvgW / 2, dy - newSvgH / 2] + ')' }); newSvg.attr({x: +_context.attr('x'), y: +_context.attr('y')}); } else if(svgClass[0] === 'l') { newSvg.attr({x: _context.attr('x'), y: dy - (newSvgH / 2)}); } else if(svgClass[0] === 'a' && svgClass.indexOf('atitle') !== 0) { newSvg.attr({x: 0, y: dy}); } else { newSvg.attr({x: newX, y: (+_context.attr('y') + dy - newSvgH / 2)}); } 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 '); } function texToSVG(_texString, _config, _callback) { var originalRenderer, originalConfig, originalProcessSectionDelay, tmpDiv; MathJax.Hub.Queue( function() { originalConfig = Lib.extendDeepAll({}, MathJax.Hub.config); originalProcessSectionDelay = MathJax.Hub.processSectionDelay; if(MathJax.Hub.processSectionDelay !== undefined) { // MathJax 2.5+ MathJax.Hub.processSectionDelay = 0; } return MathJax.Hub.Config({ messageStyle: 'none', tex2jax: { inlineMath: [['$', '$'], ['\\(', '\\)']] }, displayAlign: 'left', }); }, function() { // Get original renderer originalRenderer = MathJax.Hub.config.menuSettings.renderer; if(originalRenderer !== 'SVG') { return MathJax.Hub.setRenderer('SVG'); } }, function() { var randomID = 'math-output-' + Lib.randstr({}, 64); tmpDiv = d3.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) .style({'font-size': _config.fontSize + 'px'}) .text(cleanEscapesForTex(_texString)); return MathJax.Hub.Typeset(tmpDiv.node()); }, function() { var glyphDefs = d3.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { Lib.log('There was an error in the tex syntax.', _texString); _callback(); } else { var svgBBox = tmpDiv.select('svg').node().getBoundingClientRect(); _callback(tmpDiv.select('.MathJax_SVG'), glyphDefs, svgBBox); } tmpDiv.remove(); if(originalRenderer !== 'SVG') { return MathJax.Hub.setRenderer(originalRenderer); } }, function() { if(originalProcessSectionDelay !== undefined) { MathJax.Hub.processSectionDelay = originalProcessSectionDelay; } return MathJax.Hub.Config(originalConfig); }); } 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%', 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 .', 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) { // check safe protocols var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { // Decode href to allow both already encoded and not encoded // URIs. Without decoding prior encoding, an already encoded // URI would be encoded twice producing a semantically different URI. nodeSpec.href = encodeURI(decodeURI(href)); nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || '_blank'; nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH); } } } enterNode(nodeSpec); } } } return hasLink; } 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(); this.style({ top: (getTop() - cRect.top) + 'px', left: (getLeft() - cRect.left) + 'px', 'z-index': 1000 }); return this; }; } /* * 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'); }; /***/ }), /***/ "037d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); 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}; 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; }; /***/ }), /***/ "0382": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("86d2"), supplyDefaults: __webpack_require__("447e"), calc: __webpack_require__("de229"), plot: __webpack_require__("0cc1"), style: __webpack_require__("464d"), hoverPoints: __webpack_require__("cbb8"), eventData: __webpack_require__("3e97"), moduleType: 'trace', name: 'image', basePlotModule: __webpack_require__("91cd"), categories: ['cartesian', 'svg', '2dMap', 'noSortingByValue'], animatable: false, meta: { } }; /***/ }), /***/ "038d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Axes = __webpack_require__("0642"); var attributes = __webpack_require__("8bd8"); var fillText = __webpack_require__("fc26").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; 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([xval, yval])) { isInside = !isInside; } // for polygons that cross antimeridian as xval is in [-180, 180] if(pt._polygons[j].contains([xval + 360, yval])) { 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, geo.mockAxis); 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('
'); } /***/ }), /***/ "03d7": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Drawing = __webpack_require__("83d1"); var Color = __webpack_require__("d115"); var DESELECTDIM = __webpack_require__("72a4").DESELECTDIM; var barStyle = __webpack_require__("2df3"); var resizeText = __webpack_require__("93a6").resizeText; var styleTextPoints = barStyle.styleTextPoints; function style(gd, cd, sel) { var s = sel ? sel : d3.select(gd).selectAll('g.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 }; /***/ }), /***/ "0435": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var scatterAttrs = __webpack_require__("107c"); var baseAttrs = __webpack_require__("a876"); var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var colorScaleAttrs = __webpack_require__("f4e9"); var FORMAT_LINK = __webpack_require__("78df").FORMAT_LINK; var extendFlat = __webpack_require__("9092").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'}}), 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', }, zhoverformat: { valType: 'string', dflt: '', editType: 'none', }, hovertemplate: hovertemplateAttrs(), showlegend: extendFlat({}, baseAttrs.showlegend, {dflt: false}) }, { transforms: undefined }, colorScaleAttrs('', {cLetter: 'z', autoColorDflt: false}) ); /***/ }), /***/ "0446": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var Drawing = __webpack_require__("83d1"); var Axes = __webpack_require__("0642"); /** * 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(); }; /***/ }), /***/ "044b": /***/ (function(module, exports) { /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } /***/ }), /***/ "046b": /***/ (function(module, exports, __webpack_require__) { "use strict"; var Lib = __webpack_require__("fc26"); 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 0.3s ease 0s;-moz-transition:background-color 0.3s ease 0s;-ms-transition:background-color 0.3s ease 0s;-o-transition:background-color 0.3s ease 0s;transition:background-color 0.3s ease 0s;", "X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.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:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;", "X [data-title]:after": "content:attr(data-title);background:#69738a;color:white;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 transparent;border-left-color:#69738a;margin-top:8px;margin-right:-30px;", "X .select-outline": "fill:none;stroke-width:1;shape-rendering:crispEdges;", "X .select-outline-1": "stroke:white;", "X .select-outline-2": "stroke:black;stroke-dasharray:2px 2px;", Y: "font-family:'Open Sans';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,0.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:0.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]); } /***/ }), /***/ "04a4": /***/ (function(module, exports, __webpack_require__) { "use strict"; var createCamera = __webpack_require__("9351") var createAxes = __webpack_require__("dbd1") var axesRanges = __webpack_require__("15dd") var createSpikes = __webpack_require__("794e") var createSelect = __webpack_require__("578f") var createFBO = __webpack_require__("44c3") var drawTriangle = __webpack_require__("a92a") var mouseChange = __webpack_require__("91b8") var perspective = __webpack_require__("7ad0") var ortho = __webpack_require__("f889") var createShader = __webpack_require__("5ccc") var isMobile = __webpack_require__("8df8")({ tablet: 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) { 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 }, 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; i 0 && 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; i selection.distance) { continue } for(var j=0; j 0) { stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) ) } vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0") } } //Create index variables for(var i=0; i=0; --i) { sizeVariable.push(shape(order[i])) } //Previous phases and vertex_ids vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0", PHASES + "=mallocUint32(" + POOL_SIZE + ")", VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")", POINTER + "=0") //Create cube variables for phases vars.push(pcube(0) + "=0") for(var j=1; j<(1<=0; --i) { forLoopBegin(i, 0) } var phaseFuncArgs = [] for(var i=0; i0; k=(k-1)&subset) { faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]") } faceArgs.push(vert(0)) for(var k=0; k0){", index(order[i]), "=1;") createLoop(i-1, mask|(1< 0") } if(typeof args.vertex !== "function") { error("Must specify vertex creation function") } if(typeof args.cell !== "function") { error("Must specify cell creation function") } if(typeof args.phase !== "function") { error("Must specify phase function") } var getters = args.getters || [] var typesig = new Array(arrays) for(var i=0; i= 0) { typesig[i] = true } else { typesig[i] = false } } return compileSurfaceProcedure( args.vertex, args.cell, args.phase, scalars, order, typesig) } /***/ }), /***/ "05d6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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', nodeCapture: 'node-capture', nodeCentered: 'node-entered', nodeLabelGuide: 'node-label-guide', nodeLabel: 'node-label', nodeLabelTextPath: 'node-label-text-path' } }; /***/ }), /***/ "0625": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var Axes = __webpack_require__("0642"); var histogram2dCalc = __webpack_require__("7f9e"); var colorscaleCalc = __webpack_require__("3aa8"); var convertColumnData = __webpack_require__("d064"); var clean2dArray = __webpack_require__("1b6a"); var interp2d = __webpack_require__("2d0e"); var findEmpties = __webpack_require__("0c3a"); var makeBoundArray = __webpack_require__("d706"); 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; var x0; var dx; var y; var y0; var dy; var z; var i; var binned; // cancel minimum tick spacings (only applies to bars and boxes) xa._minDtick = 0; ya._minDtick = 0; if(isHist) { binned = histogram2dCalc(gd, trace); x = binned.x; x0 = binned.x0; dx = binned.dx; 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 { x = trace._x = trace.x ? xa.makeCalcdata(trace, 'x') : []; y = trace._y = trace.y ? ya.makeCalcdata(trace, 'y') : []; } x0 = trace.x0; dx = trace.dx; y0 = trace.y0; dy = trace.dy; z = clean2dArray(zIn, trace, xa, ya); if(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); } // check whether we really can smooth (ie all boxes are about the same size) if(zsmooth === 'fast') { if(xa.type === 'log' || ya.type === 'log') { noZsmooth('log axis found'); } else if(!isHist) { if(x.length) { var avgdx = (x[x.length - 1] - x[0]) / (x.length - 1); var maxErrX = Math.abs(avgdx / 100); for(i = 0; i < x.length - 1; i++) { if(Math.abs(x[i + 1] - x[i] - avgdx) > maxErrX) { noZsmooth('x scale is not linear'); break; } } } if(y.length && zsmooth === 'fast') { var avgdy = (y[y.length - 1] - y[0]) / (y.length - 1); var maxErrY = Math.abs(avgdy / 100); for(i = 0; i < y.length - 1; i++) { if(Math.abs(y[i + 1] - y[i] - avgdy) > maxErrY) { noZsmooth('y scale is not linear'); break; } } } } } // 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(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]; }; /***/ }), /***/ "0642": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var isNumeric = __webpack_require__("19b2"); var Plots = __webpack_require__("bb71"); var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var svgTextUtils = __webpack_require__("0379"); var Titles = __webpack_require__("1999"); var Color = __webpack_require__("d115"); var Drawing = __webpack_require__("83d1"); var axAttrs = __webpack_require__("d798"); var cleanTicks = __webpack_require__("da6a"); var constants = __webpack_require__("e806"); var ONEAVGYEAR = constants.ONEAVGYEAR; var ONEAVGMONTH = constants.ONEAVGMONTH; var ONEDAY = constants.ONEDAY; var ONEHOUR = constants.ONEHOUR; var ONEMIN = constants.ONEMIN; var ONESEC = constants.ONESEC; var MINUS_SIGN = constants.MINUS_SIGN; var BADNUM = constants.BADNUM; var alignmentConstants = __webpack_require__("63dc"); 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 axes = module.exports = {}; axes.setConvert = __webpack_require__("1a40"); var autoType = __webpack_require__("0b77"); var axisIds = __webpack_require__("3c1c"); 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__("ce56"); axes.getAutoRange = autorange.getAutoRange; axes.findExtremes = autorange.findExtremes; /* * 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] || extraOption; if(!extraOption) extraOption = dflt; // data-ref annotations are not supported in gl2d yet attrDef[refAttr] = { valType: 'enumerated', values: axlist.concat(extraOption ? [extraOption] : []), dflt: dflt }; // xref, yref return Lib.coerce(containerIn, containerOut, attrDef, refAttr); }; /* * 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; if(axRef === 'paper' || axRef === 'pixel') { 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); }; 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(Array.isArray(d2cTarget)) { ax = { type: autoType(targetArray), _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._rangeInitial === undefined); var hasChanged = isNew || !( ax.range[0] === ax._rangeInitial[0] && ax.range[1] === ax._rangeInitial[1] ); if((isNew && ax.autorange === false) || (overwrite && hasChanged)) { ax._rangeInitial = ax.range.slice(); 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 -= ONEDAY / 2; } var nextBinStart = axes.tickIncrement(binStart, dtick); if(nextBinStart <= dataMin) return nextBinStart; } return binStart; } // ---------------------------------------------------- // Ticks and grids // ---------------------------------------------------- // ensure we have tick0, dtick, and tick rounding calculated axes.prepTicks = function(ax) { var rng = Lib.simpleMap(ax.range, ax.r2l); // 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 ? (ax.tickfont.size || 12) * 1.2 : 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; } // add a couple of extra digits for filling in ticks when we // have explicit tickvals without tick text if(ax.tickmode === 'array') nt *= 100; axes.autoTicks(ax, Math.abs(rng[1] - rng[0]) / nt); // 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); } } // 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); }; // 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) { axes.prepTicks(ax); var rng = Lib.simpleMap(ax.range, ax.r2l); // 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(ax.tickmode === 'array') return arrayTicks(ax); // find the first tick ax._tmin = axes.tickFirst(ax); // add a tiny bit so we get ticks which may have rounded out var startTick = rng[0] * 1.0001 - rng[1] * 0.0001; var endTick = rng[1] * 1.0001 - rng[0] * 0.0001; // check for reversed axis var axrev = (rng[1] < rng[0]); // No visible ticks? Quit. // I've only seen this on category axes with all categories off the edge. if((ax._tmin < startTick) !== axrev) return []; // return the full set of tick vals var tickVals = []; if(ax.type === 'category' || ax.type === 'multicategory') { endTick = (axrev) ? Math.max(-0.5, endTick) : Math.min(ax._categories.length - 0.5, endTick); } var isDLog = (ax.type === 'log') && !(isNumeric(ax.dtick) || ax.dtick.charAt(0) === 'L'); var xPrevious = null; var maxTicks = Math.max(1000, ax._length || 0); for(var x = ax._tmin; (axrev) ? (x >= endTick) : (x <= endTick); x = axes.tickIncrement(x, ax.dtick, axrev, ax.calendar)) { // 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 === xPrevious) break; xPrevious = x; var minor = false; if(isDLog && (x !== (x | 0))) { minor = true; } tickVals.push({ minor: minor, value: x }); } // 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 ticksOut = new Array(tickVals.length); for(var i = 0; i < tickVals.length; i++) { ticksOut[i] = axes.tickText( ax, tickVals[i].value, false, // hover tickVals[i].minor // noSuffixPrefix ); } ax._inCalcTicks = false; return ticksOut; }; function arrayTicks(ax) { var vals = ax.tickvals; var text = ax.ticktext; var ticksOut = new Array(vals.length); var rng = Lib.simpleMap(ax.range, ax.r2l); var r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001; var r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001; var tickMin = Math.min(r0expanded, r1expanded); var tickMax = Math.max(r0expanded, r1expanded); var j = 0; // without a text array, just format the given values as any other ticks // except with more precision to the numbers if(!Array.isArray(text)) text = []; // 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); } for(var i = 0; i < vals.length; i++) { var vali = tickVal2l(vals[i]); if(vali > tickMin && vali < tickMax) { if(text[i] === undefined) ticksOut[j] = axes.tickText(ax, vali); else ticksOut[j] = tickTextObj(ax, vali, String(text[i])); j++; } } if(j < vals.length) ticksOut.splice(j, vals.length - j); 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) { 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); // 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, roundDays); // 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. ax.tick0 = Lib.dateTick0(ax.calendar, true); } 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(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); if(Math.abs(rangeexp) > 3) { 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 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 else 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) else 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; } else throw 'unrecognized dtick ' + String(dtick); }; // calculate the first tick on an axis axes.tickFirst = function(ax) { var r2l = ax.r2l || Number; var rng = Lib.simpleMap(ax.range, r2l); 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 = rng[0] * 1.0001 - rng[1] * 0.0001; 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; if(arrayMode && Array.isArray(ax.ticktext)) { var rng = Lib.simpleMap(ax.range, ax.r2l); var minDiff = Math.abs(rng[1] - rng[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]); 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; } // Setup ticks and grid lines boundaries // at 1/2 a 'category' to the left/bottom if(ax.tickson === 'boundaries' || ax.showdividers) { var inbounds = function(v) { var p = ax.l2p(v); return p >= 0 && p <= ax._length ? v : null; }; 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} val: calcdata value to format * @param {Optional(number)} val2: a second value to display * * @returns {string} `val` formatted as a string appropriate to this axis, or * `val` and `val2` as a range (ie ' - ') if `val2` is provided and * it's different from `val`. */ axes.hoverLabelText = function(ax, val, val2) { if(val2 !== BADNUM && val2 !== val) { return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } 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, fontColor: tf.color }; } function formatDate(ax, out, hover, extraPrecision) { var tr = ax._tickround; var fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); 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(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 || (headStr !== ax._prevDateHead)) { dateStr += '
' + headStr; ax._prevDateHead = headStr; } } 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, 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]; 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.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; return Lib.syncOrAsync(axList.map(function(axId) { return function() { if(!axId) return; var ax = axes.getFromId(gd, axId); var axDone = axes.drawOne(gd, ax, opts); 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 i, sp, plotinfo; ax.setScale(); var fullLayout = gd._fullLayout; var axId = ax._id; var axLetter = axId.charAt(0); var counterLetter = axes.counterLetter(axId); var mainLinePosition = ax._mainLinePosition; var mainMirrorPosition = ax._mainMirrorPosition; var mainPlotinfo = fullLayout._plots[ax._mainSubplot]; var mainAxLayer = mainPlotinfo[axLetter + 'axislayer']; 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, mainLinePosition, 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); return llbboxes[cls]; } if(!ax.visible) return; var transFn = axes.makeTransFn(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; if(ax.tickson === 'boundaries') { var boundaryVals = getBoundaryVals(ax, vals); valsClipped = axes.clipEnds(ax, boundaryVals); tickVals = ax.ticks === 'inside' ? valsClipped : boundaryVals; } else { valsClipped = axes.clipEnds(ax, vals); tickVals = ax.ticks === 'inside' ? 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), path: gridPath, transFn: transFn }); axes.drawZeroLine(gd, ax, { counterAxis: counterAxis, layer: plotinfo.zerolinelayer, path: gridPath, transFn: transFn }); } } var tickSigns = axes.getTickSigns(ax); var tickSubplots = []; if(ax.ticks) { var mainTickPath = axes.makeTickPath(ax, mainLinePosition, tickSigns[2]); var mirrorTickPath; var fullTickPath; if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { mirrorTickPath = axes.makeTickPath(ax, mainMirrorPosition, tickSigns[3]); fullTickPath = mainTickPath + mirrorTickPath; } else { mirrorTickPath = ''; fullTickPath = mainTickPath; } var tickPath; if(ax.showdividers && ax.ticks === 'outside' && ax.tickson === 'boundaries') { var dividerLookup = {}; for(i = 0; i < dividerVals.length; i++) { dividerLookup[dividerVals[i].x] = 1; } tickPath = function(d) { return dividerLookup[d.x] ? mirrorTickPath : fullTickPath; }; } else { tickPath = fullTickPath; } axes.drawTicks(gd, ax, { vals: tickVals, layer: mainAxLayer, path: tickPath, transFn: transFn }); if(ax.mirror === 'allticks') { 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 spTickPath = axes.makeTickPath(ax, linepositions[0], tickSigns[0]) + axes.makeTickPath(ax, linepositions[1], tickSigns[1]); axes.drawTicks(gd, ax, { vals: tickVals, layer: plotinfo[axLetter + 'axislayer'], path: spTickPath, transFn: transFn }); } 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, transFn: transFn, labelFns: axes.makeLabelFns(ax, mainLinePosition) }); }); 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: transFn, labelFns: axes.makeLabelFns(ax, mainLinePosition + standoff * tickSigns[4]) }); }); seq.push(function() { ax._depth = tickSigns[4] * (getLabelLevelBbox('tick2')[ax.side] - mainLinePosition); return drawDividers(gd, ax, { vals: dividerVals, layer: mainAxLayer, path: axes.makeTickPath(ax, mainLinePosition, tickSigns[4], ax._depth), transFn: transFn }); }); } else if(ax.title.hasOwnProperty('standoff')) { seq.push(function() { ax._depth = tickSigns[4] * (getLabelLevelBbox()[ax.side] - mainLinePosition); }); } var hasRangeSlider = Registry.getComponentMethod('rangeslider', 'isVisible')(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 = ax.ticks === 'outside' ? ax.ticklen : 0; var llbbox; var push; var mirrorPush; var rangeSliderPush; if(ax.automargin || hasRangeSlider) { 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); } } } if(ax.automargin) { push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; var domainIndices = [0, 1]; 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') { push[s] = ax._depth = Math.max(llbbox.height > 0 ? pos - llbbox.left : 0, outsideTickLen); } else { push[s] = ax._depth = Math.max(llbbox.height > 0 ? llbbox.right - pos : 0, outsideTickLen); 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); } Plots.autoMargin(gd, axAutoMarginID(ax), push); Plots.autoMargin(gd, axMirrorAutoMarginID(ax), mirrorPush); Plots.autoMargin(gd, rangeSliderAutoMarginID(ax), rangeSliderPush); }); if(!opts.skipTitle && !(hasRangeSlider && ax.side === 'bottom') ) { seq.push(function() { return drawTitle(gd, ax); }); } return Lib.syncOrAsync(seq); }; 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; // 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, 0); } current = d.text2; } _push(vals[i - 1], 1); } return out; } function calcLabelLevelBbox(ax, cls) { 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 { top = 0; bottom = 0; left = 0; right = 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) { 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 if((ax.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.makeTransFn = function(ax) { var axLetter = ax._id.charAt(0); var offset = ax._offset; return axLetter === 'x' ? function(d) { return 'translate(' + (offset + ax.l2p(d.x)) + ',0)'; } : function(d) { return 'translate(0,' + (offset + ax.l2p(d.x)) + ')'; }; }; /** * 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 {number (optional)} len tick length * @return {string} */ axes.makeTickPath = function(ax, shift, sgn, len) { len = len !== undefined ? len : 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 axLetter = ax._id.charAt(0); var ticksOnOutsideLabels = ax.tickson !== 'boundaries' && ax.ticks === 'outside'; var labelStandoff = 0; var labelShift = 0; if(ticksOnOutsideLabels) { labelStandoff += ax.ticklen; } if(angle && ax.ticks === 'outside') { var rad = Lib.deg2rad(angle); labelStandoff = ax.ticklen * Math.cos(rad) + 1; labelShift = ax.ticklen * Math.sin(rad); } if(ax.showticklabels && (ticksOnOutsideLabels || ax.showline)) { labelStandoff += 0.2 * ax.tickfont.size; } labelStandoff += (ax.linewidth || 1) / 2; var out = { labelStandoff: labelStandoff, labelShift: labelShift }; var x0, y0, ff, flipIt; if(axLetter === 'x') { flipIt = ax.side === 'bottom' ? 1 : -1; x0 = labelShift * flipIt; y0 = shift + labelStandoff * flipIt; ff = ax.side === 'bottom' ? 1 : -0.2; out.xFn = function(d) { return d.dx + x0; }; out.yFn = function(d) { return d.dy + y0 + d.fontSize * ff; }; out.anchorFn = function(d, a) { if(!isNumeric(a) || a === 0 || a === 180) { return 'middle'; } return (a * flipIt < 0) ? 'end' : 'start'; }; out.heightFn = function(d, a, h) { return (a < -60 || a > 60) ? -0.5 * h : ax.side === 'top' ? -h : 0; }; } else if(axLetter === 'y') { flipIt = ax.side === 'right' ? 1 : -1; x0 = labelStandoff; y0 = -labelShift * flipIt; ff = Math.abs(ax.tickangle) === 90 ? 0.5 : 0; out.xFn = function(d) { return d.dx + shift + (x0 + d.fontSize * ff) * flipIt; }; 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 ax.side === 'right' ? 'start' : 'end'; }; out.heightFn = function(d, a, h) { a *= ax.side === 'left' ? 1 : -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 ticks = opts.layer.selectAll('path.' + cls) .data(ax.ticks ? opts.vals : [], tickDataFn); ticks.exit().remove(); ticks.enter().append('path') .classed(cls, 1) .classed('ticks', 1) .classed('crisp', opts.crisp !== false) .call(Color.stroke, ax.tickcolor) .style('stroke-width', Drawing.crispRound(gd, ax.tickwidth, 1) + 'px') .attr('d', opts.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 * - {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 || {}; var cls = ax._id + 'grid'; var vals = opts.vals; var counterAx = opts.counterAxis; if(ax.showgrid === false) { vals = []; } else if(counterAx && axes.shouldShowZeroLine(gd, ax, counterAx)) { var isArrayMode = ax.tickmode === 'array'; for(var i = 0; i < vals.length; i++) { var xi = vals[i].x; if(isArrayMode ? !xi : (Math.abs(xi) < ax.dtick / 100)) { vals = vals.slice(0, i).concat(vals.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; } } } var grid = opts.layer.selectAll('path.' + cls) .data(vals, tickDataFn); grid.exit().remove(); grid.enter().append('path') .classed(cls, 1) .classed('crisp', opts.crisp !== false); ax._gw = Drawing.crispRound(gd, ax.gridwidth, 1); grid.attr('transform', opts.transFn) .attr('d', opts.path) .call(Color.stroke, ax.gridcolor || '#ddd') .style('stroke-width', ax._gw + 'px'); if(typeof opts.path === 'function') grid.attr('d', opts.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 axisIds.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'); }; /** * 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 axLetter = axId.charAt(0); var cls = opts.cls || axId + 'tick'; var vals = opts.vals; 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, d.font, d.fontSize, d.fontColor) .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); } }); 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 += ' translate(0, ' + anchorHeight + ')'; } if(mathjaxGroup.empty()) { thisLabel.select('text').attr({ transform: transform, 'text-anchor': anchor }); } else { var mjWidth = Drawing.bBox(mathjaxGroup.node()).width; var mjShift = mjWidth * {end: -0.5, start: 0.5}[anchor]; mathjaxGroup.attr('transform', transform + (mjShift ? 'translate(' + mjShift + ',0)' : '')); } }); } // 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 && axLetter === 'x' && !isNumeric(tickAngle) && (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D') ) { autoangle = 0; var maxFontSize = 0; var lbbArray = []; var i; 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()); 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 }); }); if((ax.tickson === 'boundaries' || ax.showdividers) && !opts.secondary) { var gap = 2; if(ax.ticks) gap += ax.tickwidth / 2; // TODO should secondary labels also fall into this fix-overlap regime? 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 = 90; break; } } } else { var vLen = vals.length; var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1); var rotate90 = (tickSpacing < maxFontSize * 2.5) || ax.type === 'multicategory'; // any overlap at all - set 30 degrees or 90 degrees for(i = 0; i < lbbArray.length - 1; i++) { if(Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { autoangle = rotate90 ? 90 : 30; 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 = 90; 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 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, _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 extraLines ? fontSize * (CAP_SHIFT + (extraLines * LINE_SPACING)) : fontSize * CAP_SHIFT; } 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; if(ax.title.hasOwnProperty('standoff')) { titleStandoff = ax._depth + ax.title.standoff + approxTitleDepth(ax); } else { if(ax.type === 'multicategory') { titleStandoff = ax._depth; } else { var offsetBase = 1.5; titleStandoff = 10 + fontSize * offsetBase + (ax.linewidth ? ax.linewidth - 1 : 0); } 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; } } 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 === '-') && ( 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'; } /***/ }), /***/ "0648": /***/ (function(module, exports, __webpack_require__) { // 300es builtins/reserved words that were previously valid in v100 var v100 = __webpack_require__("5ecd") // The texture2D|Cube functions have been removed // And the gl_ features are updated v100 = v100.slice().filter(function (b) { return !/^(gl\_|texture)/.test(b) }) module.exports = v100.concat([ // the updated gl_ constants 'gl_VertexID' , 'gl_InstanceID' , 'gl_Position' , 'gl_PointSize' , 'gl_FragCoord' , 'gl_FrontFacing' , 'gl_FragDepth' , 'gl_PointCoord' , 'gl_MaxVertexAttribs' , 'gl_MaxVertexUniformVectors' , 'gl_MaxVertexOutputVectors' , 'gl_MaxFragmentInputVectors' , 'gl_MaxVertexTextureImageUnits' , 'gl_MaxCombinedTextureImageUnits' , 'gl_MaxTextureImageUnits' , 'gl_MaxFragmentUniformVectors' , 'gl_MaxDrawBuffers' , 'gl_MinProgramTexelOffset' , 'gl_MaxProgramTexelOffset' , 'gl_DepthRangeParameters' , 'gl_DepthRange' // other builtins , 'trunc' , 'round' , 'roundEven' , 'isnan' , 'isinf' , 'floatBitsToInt' , 'floatBitsToUint' , 'intBitsToFloat' , 'uintBitsToFloat' , 'packSnorm2x16' , 'unpackSnorm2x16' , 'packUnorm2x16' , 'unpackUnorm2x16' , 'packHalf2x16' , 'unpackHalf2x16' , 'outerProduct' , 'transpose' , 'determinant' , 'inverse' , 'texture' , 'textureSize' , 'textureProj' , 'textureLod' , 'textureOffset' , 'texelFetch' , 'texelFetchOffset' , 'textureProjOffset' , 'textureLodOffset' , 'textureProjLod' , 'textureProjLodOffset' , 'textureGrad' , 'textureGradOffset' , 'textureProjGrad' , 'textureProjGradOffset' ]) /***/ }), /***/ "0681": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); // 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; }; /***/ }), /***/ "06a2": /***/ (function(module, exports, __webpack_require__) { "use strict"; var clear = __webpack_require__("a671d") , assign = __webpack_require__("2031") , callable = __webpack_require__("1a94") , value = __webpack_require__("96ae") , d = __webpack_require__("f508") , autoBind = __webpack_require__("986b") , Symbol = __webpack_require__("1c4a"); var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator; module.exports = Iterator = function (list, context) { if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'"); defineProperties(this, { __list__: d("w", value(list)), __context__: d("w", context), __nextIndex__: d("w", 0) }); if (!context) return; callable(context.on); context.on("_add", this._onAdd); context.on("_delete", this._onDelete); context.on("_clear", this._onClear); }; // Internal %IteratorPrototype% doesn't expose its constructor delete Iterator.prototype.constructor; defineProperties( Iterator.prototype, assign( { _next: d(function () { var i; if (!this.__list__) return undefined; if (this.__redo__) { i = this.__redo__.shift(); if (i !== undefined) return i; } if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; this._unBind(); return undefined; }), next: d(function () { return this._createResult(this._next()); }), _createResult: d(function (i) { if (i === undefined) return { done: true, value: undefined }; return { done: false, value: this._resolve(i) }; }), _resolve: d(function (i) { return this.__list__[i]; }), _unBind: d(function () { this.__list__ = null; delete this.__redo__; if (!this.__context__) return; this.__context__.off("_add", this._onAdd); this.__context__.off("_delete", this._onDelete); this.__context__.off("_clear", this._onClear); this.__context__ = null; }), toString: d(function () { return "[object " + (this[Symbol.toStringTag] || "Object") + "]"; }) }, autoBind({ _onAdd: d(function (index) { if (index >= this.__nextIndex__) return; ++this.__nextIndex__; if (!this.__redo__) { defineProperty(this, "__redo__", d("c", [index])); return; } this.__redo__.forEach(function (redo, i) { if (redo >= index) this.__redo__[i] = ++redo; }, this); this.__redo__.push(index); }), _onDelete: d(function (index) { var i; if (index >= this.__nextIndex__) return; --this.__nextIndex__; if (!this.__redo__) return; i = this.__redo__.indexOf(index); if (i !== -1) this.__redo__.splice(i, 1); this.__redo__.forEach(function (redo, j) { if (redo > index) this.__redo__[j] = --redo; }, this); }), _onClear: d(function () { if (this.__redo__) clear.call(this.__redo__); this.__nextIndex__ = 0; }) }) ) ); defineProperty( Iterator.prototype, Symbol.iterator, d(function () { return this; }) ); /***/ }), /***/ "06ad": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var layoutAttributes = __webpack_require__("60dc"); 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 }; /***/ }), /***/ "06cf": /***/ (function(module, exports, __webpack_require__) { var DESCRIPTORS = __webpack_require__("83ab"); var propertyIsEnumerableModule = __webpack_require__("d1e7"); var createPropertyDescriptor = __webpack_require__("5c6c"); var toIndexedObject = __webpack_require__("fc6a"); var toPrimitive = __webpack_require__("c04e"); var has = __webpack_require__("5135"); var IE8_DOM_DEFINE = __webpack_require__("0cfb"); var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return nativeGetOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]); }; /***/ }), /***/ "075f": /***/ (function(module, exports) { var DEFAULT_NORMALS_EPSILON = 1e-6; var DEFAULT_FACE_EPSILON = 1e-6; //Estimate the vertex normals of a mesh exports.vertexNormals = function(faces, positions, specifiedEpsilon) { var N = positions.length; var normals = new Array(N); var epsilon = specifiedEpsilon === void(0) ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon; //Initialize normal array for(var i=0; i epsilon) { var norm = normals[c]; var w = 1.0 / Math.sqrt(m01 * m21); for(var k=0; k<3; ++k) { var u = (k+1)%3; var v = (k+2)%3; norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]); } } } } //Scale all normals to unit length for(var i=0; i epsilon) { var w = 1.0 / Math.sqrt(m); for(var k=0; k<3; ++k) { norm[k] *= w; } } else { for(var k=0; k<3; ++k) { norm[k] = 0.0; } } } //Return the resulting set of patches return normals; } //Compute face normals of a mesh exports.faceNormals = function(faces, positions, specifiedEpsilon) { var N = faces.length; var normals = new Array(N); var epsilon = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon; for(var i=0; i epsilon) { l = 1.0 / Math.sqrt(l); } else { l = 0.0; } for(var j=0; j<3; ++j) { n[j] *= l; } normals[i] = n; } return normals; } /***/ }), /***/ "076f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); 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; }; /***/ }), /***/ "078e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var overrideAll = __webpack_require__("cb34").overrideAll; var Scene2D = __webpack_require__("e212"); var layoutGlobalAttrs = __webpack_require__("a685"); var xmlnsNamespaces = __webpack_require__("73c9"); var constants = __webpack_require__("d301"); var Cartesian = __webpack_require__("91cd"); var fxAttrs = __webpack_require__("927d"); var getSubplotData = __webpack_require__("ad62").getSubplotData; exports.name = 'gl2d'; exports.attr = ['xaxis', 'yaxis']; exports.idRoot = ['x', 'y']; exports.idRegex = constants.idRegex; exports.attrRegex = constants.attrRegex; exports.attributes = __webpack_require__("3ff7"); 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); } }; /***/ }), /***/ "07db": /***/ (function(module, exports, __webpack_require__) { var sprintf = __webpack_require__("e19f").sprintf; var glConstants = __webpack_require__("b42a"); var shaderName = __webpack_require__("b2dd"); var addLineNumbers = __webpack_require__("911e"); 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 < errorStrings.length; i++) { var errorString = errorStrings[i]; if (errorString === '' || errorString === "\0") continue; var lineNo = parseInt(errorString.split(':')[2]); if (isNaN(lineNo)) { throw new Error(sprintf('Could not parse error: %s', errorString)); } errors[lineNo] = errorString; } var lines = addLineNumbers(src).split('\n'); for (var i = 0; i < lines.length; i++) { if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue; var line = lines[i]; longForm += line + '\n'; if (errors[i+1]) { var e = errors[i+1]; e = e.substr(e.split(':', 3).join(':').length + 1).trim(); longForm += sprintf('^^^ %s\n\n', e); } } return { long: longForm.trim(), short: shortForm.trim() }; } /***/ }), /***/ "07dd": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); var attributes = __webpack_require__("a08c"); var colorscaleDefaults = __webpack_require__("4183"); 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); ['x', 'y', 'z'].forEach(function(dim) { 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 }; /***/ }), /***/ "0804": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // projection names to d3 function name exports.projNames = { // d3.geo.projection 'equirectangular': 'equirectangular', 'mercator': 'mercator', 'orthographic': 'orthographic', 'natural earth': 'naturalEarth', 'kavrayskiy7': 'kavrayskiy7', 'miller': 'miller', 'robinson': 'robinson', 'eckert4': 'eckert4', 'azimuthal equal area': 'azimuthalEqualArea', 'azimuthal equidistant': 'azimuthalEquidistant', 'conic equal area': 'conicEqualArea', 'conic conformal': 'conicConformal', 'conic equidistant': 'conicEquidistant', 'gnomonic': 'gnomonic', 'stereographic': 'stereographic', 'mollweide': 'mollweide', 'hammer': 'hammer', 'transverse mercator': 'transverseMercator', 'albers usa': 'albersUsa', 'winkel tripel': 'winkel3', 'aitoff': 'aitoff', 'sinusoidal': 'sinusoidal' }; // 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' }; /***/ }), /***/ "085f": /***/ (function(module, exports, __webpack_require__) { "use strict"; var doubleBits = __webpack_require__("abc0") var SMALLEST_DENORM = Math.pow(2, -1074) var UINT_MAX = (-1)>>>0 module.exports = nextafter function nextafter(x, y) { if(isNaN(x) || isNaN(y)) { return NaN } if(x === y) { return x } if(x === 0) { if(y < 0) { return -SMALLEST_DENORM } else { return SMALLEST_DENORM } } var hi = doubleBits.hi(x) var lo = doubleBits.lo(x) if((y > x) === (x > 0)) { if(lo === UINT_MAX) { hi += 1 lo = 0 } else { lo += 1 } } else { if(lo === 0) { lo = UINT_MAX hi -= 1 } else { lo -= 1 } } return doubleBits.pack(lo, hi) } /***/ }), /***/ "089c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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] }; /***/ }), /***/ "08ed": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { moduleType: 'trace', name: 'barpolar', basePlotModule: __webpack_require__("c07c"), categories: ['polar', 'bar', 'showLegend'], attributes: __webpack_require__("792f"), layoutAttributes: __webpack_require__("4ce7"), supplyDefaults: __webpack_require__("5da2"), supplyLayoutDefaults: __webpack_require__("25f3"), calc: __webpack_require__("ce20").calc, crossTraceCalc: __webpack_require__("ce20").crossTraceCalc, plot: __webpack_require__("ec16"), colorbar: __webpack_require__("f3cf"), formatLabels: __webpack_require__("98e74"), style: __webpack_require__("2df3").style, styleOnSelect: __webpack_require__("2df3").styleOnSelect, hoverPoints: __webpack_require__("f11b"), selectPoints: __webpack_require__("7000"), meta: { } }; /***/ }), /***/ "0919": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var countryRegex = __webpack_require__("cec7"); var turfArea = __webpack_require__("3b74"); var turfCentroid = __webpack_require__("8dde"); var turfBbox = __webpack_require__("409f"); var identity = __webpack_require__("306c"); var loggers = __webpack_require__("ae13"); var isPlainObject = __webpack_require__("1385"); var nestedProperty = __webpack_require__("74d6"); var polygon = __webpack_require__("b68b"); // 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 }; /***/ }), /***/ "093d": /***/ (function(module, exports, __webpack_require__) { "use strict"; var rat = __webpack_require__("f7bf") var mul = __webpack_require__("3bd6") module.exports = muls function muls(a, x) { var s = rat(x) var n = a.length var r = new Array(n) for(var i=0; i= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++]; return char; }) }); defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator")); /***/ }), /***/ "0a3e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var identity = __webpack_require__("306c"); 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];} }; /***/ }), /***/ "0a4a": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // CONCATENATED MODULE: ./node_modules/d3-force/src/center.js /* harmony default export */ var center = (function(x, y) { var nodes; if (x == null) x = 0; if (y == null) y = 0; function force() { var i, n = nodes.length, node, sx = 0, sy = 0; for (i = 0; i < n; ++i) { node = nodes[i], sx += node.x, sy += node.y; } for (sx = sx / n - x, sy = sy / n - y, i = 0; i < n; ++i) { node = nodes[i], node.x -= sx, node.y -= sy; } } force.initialize = function(_) { nodes = _; }; force.x = function(_) { return arguments.length ? (x = +_, force) : x; }; force.y = function(_) { return arguments.length ? (y = +_, force) : y; }; return force; }); // CONCATENATED MODULE: ./node_modules/d3-force/src/constant.js /* harmony default export */ var constant = (function(x) { return function() { return x; }; }); // CONCATENATED MODULE: ./node_modules/d3-force/src/jiggle.js /* harmony default export */ var jiggle = (function() { return (Math.random() - 0.5) * 1e-6; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/add.js /* harmony default export */ var add = (function(d) { var x = +this._x.call(null, d), y = +this._y.call(null, d); return add_add(this.cover(x, y), x, y, d); }); function add_add(tree, x, y, d) { if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points var parent, node = tree._root, leaf = {data: d}, x0 = tree._x0, y0 = tree._y0, x1 = tree._x1, y1 = tree._y1, xm, ym, xp, yp, right, bottom, i, j; // If the tree is empty, initialize the root as a leaf. if (!node) return tree._root = leaf, tree; // Find the existing leaf for the new point, or add it. while (node.length) { if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm; if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym; if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree; } // Is the new point is exactly coincident with the existing point? xp = +tree._x.call(null, node.data); yp = +tree._y.call(null, node.data); if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree; // Otherwise, split the leaf node until the old and new point are separated. do { parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4); if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm; if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym; } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm))); return parent[j] = node, parent[i] = leaf, tree; } function addAll(data) { var d, i, n = data.length, x, y, xz = new Array(n), yz = new Array(n), x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; // Compute the points and their extent. for (i = 0; i < n; ++i) { if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue; xz[i] = x; yz[i] = y; if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; } // If there were no (valid) points, abort. if (x0 > x1 || y0 > y1) return this; // Expand the tree to cover the new points. this.cover(x0, y0).cover(x1, y1); // Add the new points. for (i = 0; i < n; ++i) { add_add(this, xz[i], yz[i], data[i]); } return this; } // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/cover.js /* harmony default export */ var cover = (function(x, y) { if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points var x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1; // If the quadtree has no extent, initialize them. // Integer extent are necessary so that if we later double the extent, // the existing quadrant boundaries don’t change due to floating point error! if (isNaN(x0)) { x1 = (x0 = Math.floor(x)) + 1; y1 = (y0 = Math.floor(y)) + 1; } // Otherwise, double repeatedly to cover. else { var z = x1 - x0, node = this._root, parent, i; while (x0 > x || x >= x1 || y0 > y || y >= y1) { i = (y < y0) << 1 | (x < x0); parent = new Array(4), parent[i] = node, node = parent, z *= 2; switch (i) { case 0: x1 = x0 + z, y1 = y0 + z; break; case 1: x0 = x1 - z, y1 = y0 + z; break; case 2: x1 = x0 + z, y0 = y1 - z; break; case 3: x0 = x1 - z, y0 = y1 - z; break; } } if (this._root && this._root.length) this._root = node; } this._x0 = x0; this._y0 = y0; this._x1 = x1; this._y1 = y1; return this; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/data.js /* harmony default export */ var src_data = (function() { var data = []; this.visit(function(node) { if (!node.length) do data.push(node.data); while (node = node.next) }); return data; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/extent.js /* harmony default export */ var extent = (function(_) { return arguments.length ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1]) : isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]]; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/quad.js /* harmony default export */ var src_quad = (function(node, x0, y0, x1, y1) { this.node = node; this.x0 = x0; this.y0 = y0; this.x1 = x1; this.y1 = y1; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/find.js /* harmony default export */ var find = (function(x, y, radius) { var data, x0 = this._x0, y0 = this._y0, x1, y1, x2, y2, x3 = this._x1, y3 = this._y1, quads = [], node = this._root, q, i; if (node) quads.push(new src_quad(node, x0, y0, x3, y3)); if (radius == null) radius = Infinity; else { x0 = x - radius, y0 = y - radius; x3 = x + radius, y3 = y + radius; radius *= radius; } while (q = quads.pop()) { // Stop searching if this quadrant can’t contain a closer node. if (!(node = q.node) || (x1 = q.x0) > x3 || (y1 = q.y0) > y3 || (x2 = q.x1) < x0 || (y2 = q.y1) < y0) continue; // Bisect the current quadrant. if (node.length) { var xm = (x1 + x2) / 2, ym = (y1 + y2) / 2; quads.push( new src_quad(node[3], xm, ym, x2, y2), new src_quad(node[2], x1, ym, xm, y2), new src_quad(node[1], xm, y1, x2, ym), new src_quad(node[0], x1, y1, xm, ym) ); // Visit the closest quadrant first. if (i = (y >= ym) << 1 | (x >= xm)) { q = quads[quads.length - 1]; quads[quads.length - 1] = quads[quads.length - 1 - i]; quads[quads.length - 1 - i] = q; } } // Visit this point. (Visiting coincident points isn’t necessary!) else { var dx = x - +this._x.call(null, node.data), dy = y - +this._y.call(null, node.data), d2 = dx * dx + dy * dy; if (d2 < radius) { var d = Math.sqrt(radius = d2); x0 = x - d, y0 = y - d; x3 = x + d, y3 = y + d; data = node.data; } } } return data; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/remove.js /* harmony default export */ var remove = (function(d) { if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points var parent, node = this._root, retainer, previous, next, x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1, x, y, xm, ym, right, bottom, i, j; // If the tree is empty, initialize the root as a leaf. if (!node) return this; // Find the leaf node for the point. // While descending, also retain the deepest parent with a non-removed sibling. if (node.length) while (true) { if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm; if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym; if (!(parent = node, node = node[i = bottom << 1 | right])) return this; if (!node.length) break; if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i; } // Find the point to remove. while (node.data !== d) if (!(previous = node, node = node.next)) return this; if (next = node.next) delete node.next; // If there are multiple coincident points, remove just the point. if (previous) return (next ? previous.next = next : delete previous.next), this; // If this is the root point, remove it. if (!parent) return this._root = next, this; // Remove this leaf. next ? parent[i] = next : delete parent[i]; // If the parent now contains exactly one leaf, collapse superfluous parents. if ((node = parent[0] || parent[1] || parent[2] || parent[3]) && node === (parent[3] || parent[2] || parent[1] || parent[0]) && !node.length) { if (retainer) retainer[j] = node; else this._root = node; } return this; }); function removeAll(data) { for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]); return this; } // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/root.js /* harmony default export */ var root = (function() { return this._root; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/size.js /* harmony default export */ var size = (function() { var size = 0; this.visit(function(node) { if (!node.length) do ++size; while (node = node.next) }); return size; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/visit.js /* harmony default export */ var visit = (function(callback) { var quads = [], q, node = this._root, child, x0, y0, x1, y1; if (node) quads.push(new src_quad(node, this._x0, this._y0, this._x1, this._y1)); while (q = quads.pop()) { if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) { var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2; if (child = node[3]) quads.push(new src_quad(child, xm, ym, x1, y1)); if (child = node[2]) quads.push(new src_quad(child, x0, ym, xm, y1)); if (child = node[1]) quads.push(new src_quad(child, xm, y0, x1, ym)); if (child = node[0]) quads.push(new src_quad(child, x0, y0, xm, ym)); } } return this; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/visitAfter.js /* harmony default export */ var visitAfter = (function(callback) { var quads = [], next = [], q; if (this._root) quads.push(new src_quad(this._root, this._x0, this._y0, this._x1, this._y1)); while (q = quads.pop()) { var node = q.node; if (node.length) { var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2; if (child = node[0]) quads.push(new src_quad(child, x0, y0, xm, ym)); if (child = node[1]) quads.push(new src_quad(child, xm, y0, x1, ym)); if (child = node[2]) quads.push(new src_quad(child, x0, ym, xm, y1)); if (child = node[3]) quads.push(new src_quad(child, xm, ym, x1, y1)); } next.push(q); } while (q = next.pop()) { callback(q.node, q.x0, q.y0, q.x1, q.y1); } return this; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/x.js function defaultX(d) { return d[0]; } /* harmony default export */ var src_x = (function(_) { return arguments.length ? (this._x = _, this) : this._x; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/y.js function defaultY(d) { return d[1]; } /* harmony default export */ var src_y = (function(_) { return arguments.length ? (this._y = _, this) : this._y; }); // CONCATENATED MODULE: ./node_modules/d3-quadtree/src/quadtree.js function quadtree(nodes, x, y) { var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN); return nodes == null ? tree : tree.addAll(nodes); } function Quadtree(x, y, x0, y0, x1, y1) { this._x = x; this._y = y; this._x0 = x0; this._y0 = y0; this._x1 = x1; this._y1 = y1; this._root = undefined; } function leaf_copy(leaf) { var copy = {data: leaf.data}, next = copy; while (leaf = leaf.next) next = next.next = {data: leaf.data}; return copy; } var treeProto = quadtree.prototype = Quadtree.prototype; treeProto.copy = function() { var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root, nodes, child; if (!node) return copy; if (!node.length) return copy._root = leaf_copy(node), copy; nodes = [{source: node, target: copy._root = new Array(4)}]; while (node = nodes.pop()) { for (var i = 0; i < 4; ++i) { if (child = node.source[i]) { if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)}); else node.target[i] = leaf_copy(child); } } } return copy; }; treeProto.add = add; treeProto.addAll = addAll; treeProto.cover = cover; treeProto.data = src_data; treeProto.extent = extent; treeProto.find = find; treeProto.remove = remove; treeProto.removeAll = removeAll; treeProto.root = root; treeProto.size = size; treeProto.visit = visit; treeProto.visitAfter = visitAfter; treeProto.x = src_x; treeProto.y = src_y; // CONCATENATED MODULE: ./node_modules/d3-force/src/collide.js function collide_x(d) { return d.x + d.vx; } function collide_y(d) { return d.y + d.vy; } /* harmony default export */ var collide = (function(radius) { var nodes, radii, strength = 1, iterations = 1; if (typeof radius !== "function") radius = constant(radius == null ? 1 : +radius); function force() { var i, n = nodes.length, tree, node, xi, yi, ri, ri2; for (var k = 0; k < iterations; ++k) { tree = quadtree(nodes, collide_x, collide_y).visitAfter(prepare); for (i = 0; i < n; ++i) { node = nodes[i]; ri = radii[node.index], ri2 = ri * ri; xi = node.x + node.vx; yi = node.y + node.vy; tree.visit(apply); } } function apply(quad, x0, y0, x1, y1) { var data = quad.data, rj = quad.r, r = ri + rj; if (data) { if (data.index > node.index) { var x = xi - data.x - data.vx, y = yi - data.y - data.vy, l = x * x + y * y; if (l < r * r) { if (x === 0) x = jiggle(), l += x * x; if (y === 0) y = jiggle(), l += y * y; l = (r - (l = Math.sqrt(l))) / l * strength; node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj)); node.vy += (y *= l) * r; data.vx -= x * (r = 1 - r); data.vy -= y * r; } } return; } return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r; } } function prepare(quad) { if (quad.data) return quad.r = radii[quad.data.index]; for (var i = quad.r = 0; i < 4; ++i) { if (quad[i] && quad[i].r > quad.r) { quad.r = quad[i].r; } } } function initialize() { if (!nodes) return; var i, n = nodes.length, node; radii = new Array(n); for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes); } force.initialize = function(_) { nodes = _; initialize(); }; force.iterations = function(_) { return arguments.length ? (iterations = +_, force) : iterations; }; force.strength = function(_) { return arguments.length ? (strength = +_, force) : strength; }; force.radius = function(_) { return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius; }; return force; }); // EXTERNAL MODULE: ./node_modules/d3-collection/src/index.js + 6 modules var src = __webpack_require__("6f04"); // CONCATENATED MODULE: ./node_modules/d3-force/src/link.js function index(d) { return d.index; } function link_find(nodeById, nodeId) { var node = nodeById.get(nodeId); if (!node) throw new Error("missing: " + nodeId); return node; } /* harmony default export */ var src_link = (function(links) { var id = index, strength = defaultStrength, strengths, distance = constant(30), distances, nodes, count, bias, iterations = 1; if (links == null) links = []; function defaultStrength(link) { return 1 / Math.min(count[link.source.index], count[link.target.index]); } function force(alpha) { for (var k = 0, n = links.length; k < iterations; ++k) { for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) { link = links[i], source = link.source, target = link.target; x = target.x + target.vx - source.x - source.vx || jiggle(); y = target.y + target.vy - source.y - source.vy || jiggle(); l = Math.sqrt(x * x + y * y); l = (l - distances[i]) / l * alpha * strengths[i]; x *= l, y *= l; target.vx -= x * (b = bias[i]); target.vy -= y * b; source.vx += x * (b = 1 - b); source.vy += y * b; } } } function initialize() { if (!nodes) return; var i, n = nodes.length, m = links.length, nodeById = Object(src["a" /* map */])(nodes, id), link; for (i = 0, count = new Array(n); i < m; ++i) { link = links[i], link.index = i; if (typeof link.source !== "object") link.source = link_find(nodeById, link.source); if (typeof link.target !== "object") link.target = link_find(nodeById, link.target); count[link.source.index] = (count[link.source.index] || 0) + 1; count[link.target.index] = (count[link.target.index] || 0) + 1; } for (i = 0, bias = new Array(m); i < m; ++i) { link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]); } strengths = new Array(m), initializeStrength(); distances = new Array(m), initializeDistance(); } function initializeStrength() { if (!nodes) return; for (var i = 0, n = links.length; i < n; ++i) { strengths[i] = +strength(links[i], i, links); } } function initializeDistance() { if (!nodes) return; for (var i = 0, n = links.length; i < n; ++i) { distances[i] = +distance(links[i], i, links); } } force.initialize = function(_) { nodes = _; initialize(); }; force.links = function(_) { return arguments.length ? (links = _, initialize(), force) : links; }; force.id = function(_) { return arguments.length ? (id = _, force) : id; }; force.iterations = function(_) { return arguments.length ? (iterations = +_, force) : iterations; }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength; }; force.distance = function(_) { return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance; }; return force; }); // CONCATENATED MODULE: ./node_modules/d3-dispatch/src/dispatch.js var noop = {value: function() {}}; function dispatch() { for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) { if (!(t = arguments[i] + "") || (t in _) || /[\s.]/.test(t)) throw new Error("illegal type: " + t); _[t] = []; } return new Dispatch(_); } function Dispatch(_) { this._ = _; } function parseTypenames(typenames, types) { return typenames.trim().split(/^|\s+/).map(function(t) { var name = "", i = t.indexOf("."); if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i); if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t); return {type: t, name: name}; }); } Dispatch.prototype = dispatch.prototype = { constructor: Dispatch, on: function(typename, callback) { var _ = this._, T = parseTypenames(typename + "", _), t, i = -1, n = T.length; // If no callback was specified, return the callback of the given type and name. if (arguments.length < 2) { while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t; return; } // If a type was specified, set the callback for the given type and name. // Otherwise, if a null callback was specified, remove callbacks of the given name. if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback); while (++i < n) { if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback); else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null); } return this; }, copy: function() { var copy = {}, _ = this._; for (var t in _) copy[t] = _[t].slice(); return new Dispatch(copy); }, call: function(type, that) { if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2]; if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type); for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args); }, apply: function(type, that, args) { if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type); for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args); } }; function get(type, name) { for (var i = 0, n = type.length, c; i < n; ++i) { if ((c = type[i]).name === name) { return c.value; } } } function set(type, name, callback) { for (var i = 0, n = type.length; i < n; ++i) { if (type[i].name === name) { type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1)); break; } } if (callback != null) type.push({name: name, value: callback}); return type; } /* harmony default export */ var src_dispatch = (dispatch); // CONCATENATED MODULE: ./node_modules/d3-timer/src/timer.js var timer_frame = 0, // is an animation frame pending? timeout = 0, // is a timeout pending? interval = 0, // are any timers active? pokeDelay = 1000, // how frequently we check for clock skew taskHead, taskTail, clockLast = 0, clockNow = 0, clockSkew = 0, clock = typeof performance === "object" && performance.now ? performance : Date, setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); }; function now() { return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew); } function clearNow() { clockNow = 0; } function Timer() { this._call = this._time = this._next = null; } Timer.prototype = timer.prototype = { constructor: Timer, restart: function(callback, delay, time) { if (typeof callback !== "function") throw new TypeError("callback is not a function"); time = (time == null ? now() : +time) + (delay == null ? 0 : +delay); if (!this._next && taskTail !== this) { if (taskTail) taskTail._next = this; else taskHead = this; taskTail = this; } this._call = callback; this._time = time; sleep(); }, stop: function() { if (this._call) { this._call = null; this._time = Infinity; sleep(); } } }; function timer(callback, delay, time) { var t = new Timer; t.restart(callback, delay, time); return t; } function timerFlush() { now(); // Get the current time, if not already set. ++timer_frame; // Pretend we’ve set an alarm, if we haven’t already. var t = taskHead, e; while (t) { if ((e = clockNow - t._time) >= 0) t._call.call(null, e); t = t._next; } --timer_frame; } function wake() { clockNow = (clockLast = clock.now()) + clockSkew; timer_frame = timeout = 0; try { timerFlush(); } finally { timer_frame = 0; nap(); clockNow = 0; } } function poke() { var now = clock.now(), delay = now - clockLast; if (delay > pokeDelay) clockSkew -= delay, clockLast = now; } function nap() { var t0, t1 = taskHead, t2, time = Infinity; while (t1) { if (t1._call) { if (time > t1._time) time = t1._time; t0 = t1, t1 = t1._next; } else { t2 = t1._next, t1._next = null; t1 = t0 ? t0._next = t2 : taskHead = t2; } } taskTail = t0; sleep(time); } function sleep(time) { if (timer_frame) return; // Soonest alarm already set, or will be. if (timeout) timeout = clearTimeout(timeout); var delay = time - clockNow; // Strictly less than if we recomputed clockNow. if (delay > 24) { if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew); if (interval) interval = clearInterval(interval); } else { if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay); timer_frame = 1, setFrame(wake); } } // CONCATENATED MODULE: ./node_modules/d3-force/src/simulation.js function simulation_x(d) { return d.x; } function simulation_y(d) { return d.y; } var initialRadius = 10, initialAngle = Math.PI * (3 - Math.sqrt(5)); /* harmony default export */ var src_simulation = (function(nodes) { var simulation, alpha = 1, alphaMin = 0.001, alphaDecay = 1 - Math.pow(alphaMin, 1 / 300), alphaTarget = 0, velocityDecay = 0.6, forces = Object(src["a" /* map */])(), stepper = timer(step), event = src_dispatch("tick", "end"); if (nodes == null) nodes = []; function step() { tick(); event.call("tick", simulation); if (alpha < alphaMin) { stepper.stop(); event.call("end", simulation); } } function tick(iterations) { var i, n = nodes.length, node; if (iterations === undefined) iterations = 1; for (var k = 0; k < iterations; ++k) { alpha += (alphaTarget - alpha) * alphaDecay; forces.each(function (force) { force(alpha); }); for (i = 0; i < n; ++i) { node = nodes[i]; if (node.fx == null) node.x += node.vx *= velocityDecay; else node.x = node.fx, node.vx = 0; if (node.fy == null) node.y += node.vy *= velocityDecay; else node.y = node.fy, node.vy = 0; } } return simulation; } function initializeNodes() { for (var i = 0, n = nodes.length, node; i < n; ++i) { node = nodes[i], node.index = i; if (node.fx != null) node.x = node.fx; if (node.fy != null) node.y = node.fy; if (isNaN(node.x) || isNaN(node.y)) { var radius = initialRadius * Math.sqrt(i), angle = i * initialAngle; node.x = radius * Math.cos(angle); node.y = radius * Math.sin(angle); } if (isNaN(node.vx) || isNaN(node.vy)) { node.vx = node.vy = 0; } } } function initializeForce(force) { if (force.initialize) force.initialize(nodes); return force; } initializeNodes(); return simulation = { tick: tick, restart: function() { return stepper.restart(step), simulation; }, stop: function() { return stepper.stop(), simulation; }, nodes: function(_) { return arguments.length ? (nodes = _, initializeNodes(), forces.each(initializeForce), simulation) : nodes; }, alpha: function(_) { return arguments.length ? (alpha = +_, simulation) : alpha; }, alphaMin: function(_) { return arguments.length ? (alphaMin = +_, simulation) : alphaMin; }, alphaDecay: function(_) { return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay; }, alphaTarget: function(_) { return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget; }, velocityDecay: function(_) { return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay; }, force: function(name, _) { return arguments.length > 1 ? ((_ == null ? forces.remove(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name); }, find: function(x, y, radius) { var i = 0, n = nodes.length, dx, dy, d2, node, closest; if (radius == null) radius = Infinity; else radius *= radius; for (i = 0; i < n; ++i) { node = nodes[i]; dx = x - node.x; dy = y - node.y; d2 = dx * dx + dy * dy; if (d2 < radius) closest = node, radius = d2; } return closest; }, on: function(name, _) { return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name); } }; }); // CONCATENATED MODULE: ./node_modules/d3-force/src/manyBody.js /* harmony default export */ var manyBody = (function() { var nodes, node, alpha, strength = constant(-30), strengths, distanceMin2 = 1, distanceMax2 = Infinity, theta2 = 0.81; function force(_) { var i, n = nodes.length, tree = quadtree(nodes, simulation_x, simulation_y).visitAfter(accumulate); for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply); } function initialize() { if (!nodes) return; var i, n = nodes.length, node; strengths = new Array(n); for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes); } function accumulate(quad) { var strength = 0, q, c, weight = 0, x, y, i; // For internal nodes, accumulate forces from child quadrants. if (quad.length) { for (x = y = i = 0; i < 4; ++i) { if ((q = quad[i]) && (c = Math.abs(q.value))) { strength += q.value, weight += c, x += c * q.x, y += c * q.y; } } quad.x = x / weight; quad.y = y / weight; } // For leaf nodes, accumulate forces from coincident quadrants. else { q = quad; q.x = q.data.x; q.y = q.data.y; do strength += strengths[q.data.index]; while (q = q.next); } quad.value = strength; } function apply(quad, x1, _, x2) { if (!quad.value) return true; var x = quad.x - node.x, y = quad.y - node.y, w = x2 - x1, l = x * x + y * y; // Apply the Barnes-Hut approximation if possible. // Limit forces for very close nodes; randomize direction if coincident. if (w * w / theta2 < l) { if (l < distanceMax2) { if (x === 0) x = jiggle(), l += x * x; if (y === 0) y = jiggle(), l += y * y; if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l); node.vx += x * quad.value * alpha / l; node.vy += y * quad.value * alpha / l; } return true; } // Otherwise, process points directly. else if (quad.length || l >= distanceMax2) return; // Limit forces for very close nodes; randomize direction if coincident. if (quad.data !== node || quad.next) { if (x === 0) x = jiggle(), l += x * x; if (y === 0) y = jiggle(), l += y * y; if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l); } do if (quad.data !== node) { w = strengths[quad.data.index] * alpha / l; node.vx += x * w; node.vy += y * w; } while (quad = quad.next); } force.initialize = function(_) { nodes = _; initialize(); }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength; }; force.distanceMin = function(_) { return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2); }; force.distanceMax = function(_) { return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2); }; force.theta = function(_) { return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2); }; return force; }); // CONCATENATED MODULE: ./node_modules/d3-force/src/radial.js /* harmony default export */ var radial = (function(radius, x, y) { var nodes, strength = constant(0.1), strengths, radiuses; if (typeof radius !== "function") radius = constant(+radius); if (x == null) x = 0; if (y == null) y = 0; function force(alpha) { for (var i = 0, n = nodes.length; i < n; ++i) { var node = nodes[i], dx = node.x - x || 1e-6, dy = node.y - y || 1e-6, r = Math.sqrt(dx * dx + dy * dy), k = (radiuses[i] - r) * strengths[i] * alpha / r; node.vx += dx * k; node.vy += dy * k; } } function initialize() { if (!nodes) return; var i, n = nodes.length; strengths = new Array(n); radiuses = new Array(n); for (i = 0; i < n; ++i) { radiuses[i] = +radius(nodes[i], i, nodes); strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes); } } force.initialize = function(_) { nodes = _, initialize(); }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength; }; force.radius = function(_) { return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius; }; force.x = function(_) { return arguments.length ? (x = +_, force) : x; }; force.y = function(_) { return arguments.length ? (y = +_, force) : y; }; return force; }); // CONCATENATED MODULE: ./node_modules/d3-force/src/x.js /* harmony default export */ var d3_force_src_x = (function(x) { var strength = constant(0.1), nodes, strengths, xz; if (typeof x !== "function") x = constant(x == null ? 0 : +x); function force(alpha) { for (var i = 0, n = nodes.length, node; i < n; ++i) { node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha; } } function initialize() { if (!nodes) return; var i, n = nodes.length; strengths = new Array(n); xz = new Array(n); for (i = 0; i < n; ++i) { strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes); } } force.initialize = function(_) { nodes = _; initialize(); }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength; }; force.x = function(_) { return arguments.length ? (x = typeof _ === "function" ? _ : constant(+_), initialize(), force) : x; }; return force; }); // CONCATENATED MODULE: ./node_modules/d3-force/src/y.js /* harmony default export */ var d3_force_src_y = (function(y) { var strength = constant(0.1), nodes, strengths, yz; if (typeof y !== "function") y = constant(y == null ? 0 : +y); function force(alpha) { for (var i = 0, n = nodes.length, node; i < n; ++i) { node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha; } } function initialize() { if (!nodes) return; var i, n = nodes.length; strengths = new Array(n); yz = new Array(n); for (i = 0; i < n; ++i) { strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes); } } force.initialize = function(_) { nodes = _; initialize(); }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength; }; force.y = function(_) { return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), initialize(), force) : y; }; return force; }); // CONCATENATED MODULE: ./node_modules/d3-force/src/index.js /* concated harmony reexport forceCenter */__webpack_require__.d(__webpack_exports__, "forceCenter", function() { return center; }); /* concated harmony reexport forceCollide */__webpack_require__.d(__webpack_exports__, "forceCollide", function() { return collide; }); /* concated harmony reexport forceLink */__webpack_require__.d(__webpack_exports__, "forceLink", function() { return src_link; }); /* concated harmony reexport forceManyBody */__webpack_require__.d(__webpack_exports__, "forceManyBody", function() { return manyBody; }); /* concated harmony reexport forceRadial */__webpack_require__.d(__webpack_exports__, "forceRadial", function() { return radial; }); /* concated harmony reexport forceSimulation */__webpack_require__.d(__webpack_exports__, "forceSimulation", function() { return src_simulation; }); /* concated harmony reexport forceX */__webpack_require__.d(__webpack_exports__, "forceX", function() { return d3_force_src_x; }); /* concated harmony reexport forceY */__webpack_require__.d(__webpack_exports__, "forceY", function() { return d3_force_src_y; }); /***/ }), /***/ "0adf": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorscaleCalc = __webpack_require__("3aa8"); var Lib = __webpack_require__("fc26"); var convertColumnData = __webpack_require__("d064"); var clean2dArray = __webpack_require__("1b6a"); var interp2d = __webpack_require__("2d0e"); var findEmpties = __webpack_require__("0c3a"); var makeBoundArray = __webpack_require__("d706"); var supplyDefaults = __webpack_require__("eb12"); var lookupCarpet = __webpack_require__("9b68"); var setContours = __webpack_require__("8a7d"); // 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]; } /***/ }), /***/ "0af2": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var calcColorscale = __webpack_require__("09bd"); var calcMarkerSize = __webpack_require__("70b4").calcMarkerSize; var convert = __webpack_require__("c879"); var Axes = __webpack_require__("0642"); var TOO_MANY_POINTS = __webpack_require__("b326").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}]; }; /***/ }), /***/ "0b1d": /***/ (function(module, exports, __webpack_require__) { "use strict"; var twoProduct = __webpack_require__("c01c") var robustSum = __webpack_require__("a026") var robustDiff = __webpack_require__("e100") var robustScale = __webpack_require__("0dd1") var NUM_EXPAND = 6 function cofactor(m, c) { var result = new Array(m.length-1) for(var i=1; i>1 return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") } } function makeProduct(a, b) { if(a.charAt(0) === "m") { if(b.charAt(0) === "w") { var toks = a.split("[") return ["w", b.substr(1), "m", toks[0].substr(1)].join("") } else { return ["prod(", a, ",", b, ")"].join("") } } else { return makeProduct(b, a) } } function sign(s) { if(s & 1 !== 0) { return "-" } return "" } function determinant(m) { if(m.length === 2) { return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")] } else { var expr = [] for(var i=0; i ncnt * 2); } // are the (x,y)-values in gd.data mostly text? // require twice as many DISTINCT categories as distinct numbers function category(a) { // test at most 1000 points var inc = Math.max(1, (a.length - 1) / 1000); var curvenums = 0; var curvecats = 0; var seen = {}; for(var i = 0; i < a.length; i += inc) { var ai = a[Math.round(i)]; var stri = String(ai); if(seen[stri]) continue; seen[stri] = 1; if(typeof ai === 'boolean') curvecats++; else if(Lib.cleanNumber(ai) !== BADNUM) curvenums++; else if(typeof ai === 'string') curvecats++; } return curvecats > curvenums * 2; } // very-loose requirements for multicategory, // trace modules that should never auto-type to multicategory // should be declared with 'noMultiCategory' function multiCategory(a) { return Lib.isArrayOrTypedArray(a[0]) && Lib.isArrayOrTypedArray(a[1]); } /***/ }), /***/ "0b79": /***/ (function(module, exports, __webpack_require__) { /* * World Calendars * https://github.com/alexcjohnson/world-calendars * * Batch-converted from kbwood/calendars * Many thanks to Keith Wood and all of the contributors to the original project! * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* http://keith-wood.name/calendars.html Taiwanese (Minguo) calendar for jQuery v2.0.2. Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010. Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ var main = __webpack_require__("0230"); var assign = __webpack_require__("320c"); var gregorianCalendar = main.instance(); /** Implementation of the Taiwanese calendar. See http://en.wikipedia.org/wiki/Minguo_calendar. @class TaiwanCalendar @param [language=''] {string} The language code (default English) for localisation. */ function TaiwanCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } TaiwanCalendar.prototype = new main.baseCalendar; assign(TaiwanCalendar.prototype, { /** The calendar name. @memberof TaiwanCalendar */ name: 'Taiwan', /** Julian date of start of Taiwan epoch: 1 January 1912 CE (Gregorian). @memberof TaiwanCalendar */ jdEpoch: 2419402.5, /** Difference in years between Taiwan and Gregorian calendars. @memberof TaiwanCalendar */ yearsOffset: 1911, /** Days per month in a common year. @memberof TaiwanCalendar */ daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], /** true if has a year zero, false if not. @memberof TaiwanCalendar */ hasYearZero: false, /** The minimum month number. @memberof TaiwanCalendar */ minMonth: 1, /** The first month in the year. @memberof TaiwanCalendar */ firstMonth: 1, /** The minimum day number. @memberof TaiwanCalendar */ minDay: 1, /** Localisations for the plugin. Entries are objects indexed by the language code ('' being the default US/English). Each object has the following attributes. @memberof TaiwanCalendar @property name {string} The calendar name. @property epochs {string[]} The epoch names. @property monthNames {string[]} The long names of the months of the year. @property monthNamesShort {string[]} The short names of the months of the year. @property dayNames {string[]} The long names of the days of the week. @property dayNamesShort {string[]} The short names of the days of the week. @property dayNamesMin {string[]} The minimal names of the days of the week. @property dateFormat {string} The date format for this calendar. See the options on formatDate for details. @property firstDay {number} The number of the first day of the week, starting at 0. @property isRTL {number} true if this localisation reads right-to-left. */ regionalOptions: { // Localisations '': { name: 'Taiwan', epochs: ['BROC', 'ROC'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], digits: null, dateFormat: 'yyyy/mm/dd', firstDay: 1, isRTL: false } }, /** Determine whether this date is in a leap year. @memberof TaiwanCalendar @param year {CDate|number} The date to examine or the year to examine. @return {boolean} true if this is a leap year, false if not. @throws Error if an invalid year or a different calendar used. */ leapYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear); var year = this._t2gYear(date.year()); return gregorianCalendar.leapYear(year); }, /** Determine the week of the year for a date - ISO 8601. @memberof TaiwanCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {number} The week of the year. @throws Error if an invalid date or a different calendar used. */ weekOfYear: function(year, month, day) { var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear); var year = this._t2gYear(date.year()); return gregorianCalendar.weekOfYear(year, date.month(), date.day()); }, /** Retrieve the number of days in a month. @memberof TaiwanCalendar @param year {CDate|number} The date to examine or the year of the month. @param [month] {number} The month. @return {number} The number of days in this month. @throws Error if an invalid month/year or a different calendar used. */ daysInMonth: function(year, month) { var date = this._validate(year, month, this.minDay, main.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, /** Determine whether this date is a week day. @memberof TaiwanCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {boolean} true if a week day, false if not. @throws Error if an invalid date or a different calendar used. */ weekDay: function(year, month, day) { return (this.dayOfWeek(year, month, day) || 7) < 6; }, /** Retrieve the Julian date equivalent for this date, i.e. days since January 1, 4713 BCE Greenwich noon. @memberof TaiwanCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(year, month, day) { var date = this._validate(year, month, day, main.local.invalidDate); var year = this._t2gYear(date.year()); return gregorianCalendar.toJD(year, date.month(), date.day()); }, /** Create a new date from a Julian date. @memberof TaiwanCalendar @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { var date = gregorianCalendar.fromJD(jd); var year = this._g2tYear(date.year()); return this.newDate(year, date.month(), date.day()); }, /** Convert Taiwanese to Gregorian year. @memberof TaiwanCalendar @private @param year {number} The Taiwanese year. @return {number} The corresponding Gregorian year. */ _t2gYear: function(year) { return year + this.yearsOffset + (year >= -this.yearsOffset && year <= -1 ? 1 : 0); }, /** Convert Gregorian to Taiwanese year. @memberof TaiwanCalendar @private @param year {number} The Gregorian year. @return {number} The corresponding Taiwanese year. */ _g2tYear: function(year) { return year - this.yearsOffset - (year >= 1 && year <= this.yearsOffset ? 1 : 0); } }); // Taiwan calendar implementation main.calendars.taiwan = TaiwanCalendar; /***/ }), /***/ "0b89": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var TAU = Math.PI * 2; var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) { var x = _ref.x, y = _ref.y; x *= rx; y *= ry; var xp = cosphi * x - sinphi * y; var yp = sinphi * x + cosphi * y; return { x: xp + centerx, y: yp + centery }; }; var approxUnitArc = function approxUnitArc(ang1, ang2) { // If 90 degree circular arc, use a constant // as derived from http://spencermortensen.com/articles/bezier-circle var a = ang2 === 1.5707963267948966 ? 0.551915024494 : ang2 === -1.5707963267948966 ? -0.551915024494 : 4 / 3 * Math.tan(ang2 / 4); var x1 = Math.cos(ang1); var y1 = Math.sin(ang1); var x2 = Math.cos(ang1 + ang2); var y2 = Math.sin(ang1 + ang2); return [{ x: x1 - y1 * a, y: y1 + x1 * a }, { x: x2 + y2 * a, y: y2 - x2 * a }, { x: x2, y: y2 }]; }; var vectorAngle = function vectorAngle(ux, uy, vx, vy) { var sign = ux * vy - uy * vx < 0 ? -1 : 1; var dot = ux * vx + uy * vy; if (dot > 1) { dot = 1; } if (dot < -1) { dot = -1; } return sign * Math.acos(dot); }; var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) { var rxsq = Math.pow(rx, 2); var rysq = Math.pow(ry, 2); var pxpsq = Math.pow(pxp, 2); var pypsq = Math.pow(pyp, 2); var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; if (radicant < 0) { radicant = 0; } radicant /= rxsq * pypsq + rysq * pxpsq; radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); var centerxp = radicant * rx / ry * pyp; var centeryp = radicant * -ry / rx * pxp; var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2; var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; var vx1 = (pxp - centerxp) / rx; var vy1 = (pyp - centeryp) / ry; var vx2 = (-pxp - centerxp) / rx; var vy2 = (-pyp - centeryp) / ry; var ang1 = vectorAngle(1, 0, vx1, vy1); var ang2 = vectorAngle(vx1, vy1, vx2, vy2); if (sweepFlag === 0 && ang2 > 0) { ang2 -= TAU; } if (sweepFlag === 1 && ang2 < 0) { ang2 += TAU; } return [centerx, centery, ang1, ang2]; }; var arcToBezier = function arcToBezier(_ref2) { var px = _ref2.px, py = _ref2.py, cx = _ref2.cx, cy = _ref2.cy, rx = _ref2.rx, ry = _ref2.ry, _ref2$xAxisRotation = _ref2.xAxisRotation, xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation, _ref2$largeArcFlag = _ref2.largeArcFlag, largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag, _ref2$sweepFlag = _ref2.sweepFlag, sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag; var curves = []; if (rx === 0 || ry === 0) { return []; } var sinphi = Math.sin(xAxisRotation * TAU / 360); var cosphi = Math.cos(xAxisRotation * TAU / 360); var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2; var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2; if (pxp === 0 && pyp === 0) { return []; } rx = Math.abs(rx); ry = Math.abs(ry); var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); if (lambda > 1) { rx *= Math.sqrt(lambda); ry *= Math.sqrt(lambda); } var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), _getArcCenter2 = _slicedToArray(_getArcCenter, 4), centerx = _getArcCenter2[0], centery = _getArcCenter2[1], ang1 = _getArcCenter2[2], ang2 = _getArcCenter2[3]; // If 'ang2' == 90.0000000001, then `ratio` will evaluate to // 1.0000000001. This causes `segments` to be greater than one, which is an // unecessary split, and adds extra points to the bezier curve. To alleviate // this issue, we round to 1.0 when the ratio is close to 1.0. var ratio = Math.abs(ang2) / (TAU / 4); if (Math.abs(1.0 - ratio) < 0.0000001) { ratio = 1.0; } var segments = Math.max(Math.ceil(ratio), 1); ang2 /= segments; for (var i = 0; i < segments; i++) { curves.push(approxUnitArc(ang1, ang2)); ang1 += ang2; } return curves.map(function (curve) { var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), x1 = _mapToEllipse.x, y1 = _mapToEllipse.y; var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), x2 = _mapToEllipse2.x, y2 = _mapToEllipse2.y; var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), x = _mapToEllipse3.x, y = _mapToEllipse3.y; return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }; }); }; /* harmony default export */ __webpack_exports__["default"] = (arcToBezier); /***/ }), /***/ "0c39": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); var Axes = __webpack_require__("0642"); var arraysToCalcdata = __webpack_require__("424b"); var binFunctions = __webpack_require__("6dcc"); var normFunctions = __webpack_require__("c005"); var doAvg = __webpack_require__("9547"); var getBinSpanLabelRound = __webpack_require__("5913"); function calc(gd, trace) { var pos = []; var size = []; var pa = Axes.getFromId(gd, trace.orientation === 'h' ? trace.yaxis : trace.xaxis); var mainData = trace.orientation === 'h' ? '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 }; } // bin the data // and make histogram-specific pt-number-to-cd-index map object var nMax = size.length; var uniqueValsPerBin = true; var leftGap = Infinity; var rightGap = Infinity; 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); } } var roundFn; if(!uniqueValsPerBin) { roundFn = getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar); } // 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 { 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 if(isOverlay && !Registry.traceIs(trace, '2dMap') && newBinSpec._dataSpan === 0 && pa.type !== 'category' && pa.type !== 'multicategory') { // 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 }; /***/ }), /***/ "0c3a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var maxRowLength = __webpack_require__("fc26").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]; }); }; /***/ }), /***/ "0c5d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var handleSampleDefaults = __webpack_require__("8173"); var handleContoursDefaults = __webpack_require__("d61b"); var handleStyleDefaults = __webpack_require__("41f8"); var attributes = __webpack_require__("348d"); 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('hovertemplate'); }; /***/ }), /***/ "0c85": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isArrayOrTypedArray = __webpack_require__("fc26").isArrayOrTypedArray; var Colorscale = __webpack_require__("c258"); var wrap = __webpack_require__("0a3e").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; } /***/ }), /***/ "0cc1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var xmlnsNamespaces = __webpack_require__("73c9"); var constants = __webpack_require__("000c"); module.exports = function plot(gd, plotinfo, cdimage, imageLayer) { var xa = plotinfo.xaxis; var ya = plotinfo.yaxis; Lib.makeTraceGroups(imageLayer, cdimage, 'im').each(function(cd) { var plotGroup = d3.select(this); var cd0 = cd[0]; var trace = cd0.trace; 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 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; } // Draw each pixel var canvas = document.createElement('canvas'); canvas.width = imageWidth; canvas.height = imageHeight; var context = canvas.getContext('2d'); 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 fmt = constants.colormodel[trace.colormodel].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) || !z[j][i]) continue; c = trace._scaler(z[j][i]); if(c) { context.fillStyle = trace.colormodel + '(' + fmt(c).join(',') + ')'; } else { // Return a transparent pixel context.fillStyle = 'rgba(0,0,0,0)'; } context.fillRect(ipx0, jpx0, ipx1 - ipx0, jpx1 - jpx0); } } 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') }); }); }; /***/ }), /***/ "0cec": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var isArrayOrTypedArray = __webpack_require__("fc26").isArrayOrTypedArray; var BADNUM = __webpack_require__("e806").BADNUM; var Registry = __webpack_require__("371e"); var Axes = __webpack_require__("0642"); var getAxisGroup = __webpack_require__("3c1c").getAxisGroup; var Sieve = __webpack_require__("8b25"); /* * 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]); } } } var opts = { 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(included.length) { setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included, opts); } if(excluded.length) { setGroupPositionsInOverlayMode(pa, sa, excluded, opts); } break; } collectExtents(calcTraces, pa); } 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], { 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, { 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); // 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, { 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 = Array.isArray(poffset); var barwidth = t.barwidth; var barwidthIsArray = Array.isArray(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; calcBar[pLetter] = calcBar.p + (poffsetIsArray ? poffset[j] : poffset) + width / 2; } } } 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 = Array.isArray(poffset); var barwidthIsArray = Array.isArray(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 pts = []; var allBaseAboveZero = true; for(var j = 0; j < calcTrace.length; j++) { var bar = calcTrace[j]; var base = bar.b; var top = base + bar.s; bar[sLetter] = top; pts.push(top); if(bar.hasB) pts.push(base); if(!bar.hasB || !(bar.b > 0 && bar.s > 0)) { allBaseAboveZero = false; } } fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, { tozero: !allBaseAboveZero, 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) { 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], { 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 allBaseAboveZero = true; 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 > 0 && bar.s > 0)) { allBaseAboveZero = false; } } } fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, { tozero: !allBaseAboveZero, padded: padded }); } } // 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))); }; for(i = 0; i < calcTraces.length; i++) { cd = calcTraces[i]; cd[0].t.extents = extents; var poffset = cd[0].t.poffset; var poffsetIsArray = Array.isArray(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; } } } function getAxisLetter(ax) { return ax._id.charAt(0); } module.exports = { crossTraceCalc: crossTraceCalc, setGroupPositions: setGroupPositions }; /***/ }), /***/ "0cfb": /***/ (function(module, exports, __webpack_require__) { var DESCRIPTORS = __webpack_require__("83ab"); var fails = __webpack_require__("d039"); var createElement = __webpack_require__("cc12"); // Thank's IE8 for his funny defineProperty module.exports = !DESCRIPTORS && !fails(function () { return Object.defineProperty(createElement('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "0d59": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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' } }; /***/ }), /***/ "0dd1": /***/ (function(module, exports, __webpack_require__) { "use strict"; var twoProduct = __webpack_require__("c01c") var twoSum = __webpack_require__("d1bd") module.exports = scaleLinearExpansion function scaleLinearExpansion(e, scale) { var n = e.length if(n === 1) { var ts = twoProduct(e[0], scale) if(ts[0]) { return ts } return [ ts[1] ] } var g = new Array(2 * n) var q = [0.1, 0.1] var t = [0.1, 0.1] var count = 0 twoProduct(e[0], scale, q) if(q[0]) { g[count++] = q[0] } for(var i=1; i': 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 }; }; } /***/ }), /***/ "11e1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var Color = __webpack_require__("d115"); var handleStyleDefaults = __webpack_require__("9103"); var attributes = __webpack_require__("40c0"); 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'); coerce('hovertext'); coerce('hovertemplate'); 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'}); }; /***/ }), /***/ "122d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Color = __webpack_require__("d115"); var Template = __webpack_require__("a651"); var handleSubplotDefaults = __webpack_require__("119e"); var getSubplotData = __webpack_require__("ad62").getSubplotData; var handleTickValueDefaults = __webpack_require__("d92f"); var handleTickMarkDefaults = __webpack_require__("27e3"); var handleTickLabelDefaults = __webpack_require__("5008"); var handleCategoryOrderDefaults = __webpack_require__("d18b"); var handleLineGridDefaults = __webpack_require__("743b"); var autoType = __webpack_require__("0b77"); var layoutAttributes = __webpack_require__("ddde"); var setConvert = __webpack_require__("7a52"); var constants = __webpack_require__("f510"); 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); handleCategoryOrderDefaults(axIn, axOut, coerceAxis, { axData: subplotData, dataAttr: dataAttr }); var visible = coerceAxis('visible'); setConvert(axOut, contOut, layoutOut); coerceAxis('uirevision', contOut.uirevision); var dfltColor; var dfltFontColor; if(visible) { dfltColor = coerceAxis('color'); dfltFontColor = (dfltColor === axIn.color) ? dfltColor : opts.font.color; } // 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': var autoRange = coerceAxis('autorange', !axOut.isValidRange(axIn.range)); axIn.autorange = autoRange; if(autoRange && (axType === 'linear' || axType === '-')) coerceAxis('rangemode'); if(autoRange === 'reversed') axOut._m = -1; coerceAxis('range'); axOut.cleanRange('range', {dfltRange: [0, 1]}); if(visible) { coerceAxis('side'); coerceAxis('angle', sector[0]); coerceAxis('title.text'); Lib.coerceFont(coerceAxis, 'title.font', { family: opts.font.family, size: Math.round(opts.font.size * 1.2), color: dfltFontColor }); } 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; } if(visible) { handleTickValueDefaults(axIn, axOut, coerceAxis, axOut.type); handleTickLabelDefaults(axIn, axOut, coerceAxis, axOut.type, { tickSuffixDflt: axOut.thetaunit === 'degrees' ? '°' : undefined }); handleTickMarkDefaults(axIn, axOut, coerceAxis, {outerTicks: true}); var showTickLabels = coerceAxis('showticklabels'); if(showTickLabels) { Lib.coerceFont(coerceAxis, 'tickfont', { family: opts.font.family, size: opts.font.size, color: dfltFontColor }); coerceAxis('tickangle'); coerceAxis('tickformat'); } 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(axType !== 'category') coerceAxis('hoverformat'); axOut._input = axIn; } if(contOut.angularaxis.type === 'category') { coerce('gridshape'); } } function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr) { 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'); } 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, paper_bgcolor: layoutOut.paper_bgcolor, fullData: fullData, layoutOut: layoutOut }); }; /***/ }), /***/ "12c1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager // Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com module.exports = function UndoManager() { var undoCommands = []; var index = -1; var isExecuting = false; var callback; function execute(command, action) { if(!command) return this; isExecuting = true; command[action](); isExecuting = false; return this; } return { add: function(command) { if(isExecuting) return this; undoCommands.splice(index + 1, undoCommands.length - index); undoCommands.push(command); index = undoCommands.length - 1; return this; }, setCallback: function(callbackFunc) { callback = callbackFunc; }, undo: function() { var command = undoCommands[index]; if(!command) return this; execute(command, 'undo'); index -= 1; if(callback) callback(command.undo); return this; }, redo: function() { var command = undoCommands[index + 1]; if(!command) return this; execute(command, 'redo'); index += 1; if(callback) callback(command.redo); return this; }, clear: function() { undoCommands = []; index = -1; }, hasUndo: function() { return index !== -1; }, hasRedo: function() { return index < (undoCommands.length - 1); }, getCommands: function() { return undoCommands; }, getPreviousCommand: function() { return undoCommands[index - 1]; }, getIndex: function() { return index; } }; }; /***/ }), /***/ "12e0": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // a trimmed down version of: // https://github.com/alexcjohnson/world-calendars/blob/master/dist/index.js module.exports = __webpack_require__("0230"); __webpack_require__("54ea"); __webpack_require__("87d2"); __webpack_require__("ad2d"); __webpack_require__("d402"); __webpack_require__("fd3b"); __webpack_require__("becc"); __webpack_require__("3e43"); __webpack_require__("aaa9"); __webpack_require__("a7c5"); __webpack_require__("8a0e"); __webpack_require__("c107"); __webpack_require__("2d7d"); __webpack_require__("0b79"); __webpack_require__("1bbd"); __webpack_require__("7abc"); /***/ }), /***/ "134c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var overrideAll = __webpack_require__("cb34").overrideAll; var fxAttrs = __webpack_require__("927d"); var Scene = __webpack_require__("bb88"); var getSubplotData = __webpack_require__("ad62").getSubplotData; var Lib = __webpack_require__("fc26"); var xmlnsNamespaces = __webpack_require__("73c9"); 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__("cdaf"); exports.layoutAttributes = __webpack_require__("f409"); exports.baseLayoutAttrOverrides = overrideAll({ hoverlabel: fxAttrs.hoverlabel }, 'plot', 'nested'); exports.supplyLayoutDefaults = __webpack_require__("9f41"); 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); } }; /***/ }), /***/ "1368": /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global) {var require;/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 3.3.1 */ (function (global, factory) { true ? module.exports = factory() : undefined; }(this, (function () { 'use strict'; function objectOrFunction(x) { return typeof x === 'function' || typeof x === 'object' && x !== null; } function isFunction(x) { return typeof x === 'function'; } var _isArray = undefined; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { return function () { vertxNext(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var r = require; var vertx = __webpack_require__(0); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { (function () { var callback = _arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); })(); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); _resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then) { asap(function (promise) { var sealed = false; var error = tryThen(then, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { _resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; _reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; _reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { _reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return _resolve(promise, value); }, function (reason) { return _reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$) { if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { handleOwnThenable(promise, maybeThenable); } else { if (then$$ === GET_THEN_ERROR) { _reject(promise, GET_THEN_ERROR.error); } else if (then$$ === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$)) { handleForeignThenable(promise, maybeThenable, then$$); } else { fulfill(promise, maybeThenable); } } } function _resolve(promise, value) { if (promise === value) { _reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function _reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { _reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { _resolve(promise, value); } else if (failed) { _reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { _reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { _resolve(promise, value); }, function rejectPromise(reason) { _reject(promise, reason); }); } catch (e) { _reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { _reject(this.promise, validationError()); } } function validationError() { return new Error('Array Methods must be provided an Array'); }; Enumerator.prototype._enumerate = function () { var length = this.length; var _input = this._input; for (var i = 0; this._state === PENDING && i < length; i++) { this._eachEntry(_input[i], i); } }; Enumerator.prototype._eachEntry = function (entry, i) { var c = this._instanceConstructor; var resolve$$ = c.resolve; if (resolve$$ === resolve) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$) { return resolve$$(entry); }), i); } } else { this._willSettleAt(resolve$$(entry), i); } }; Enumerator.prototype._settledAt = function (state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { _reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function (promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); _reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } Promise.all = all; Promise.race = race; Promise.resolve = resolve; Promise.reject = reject; Promise._setScheduler = setScheduler; Promise._setAsap = setAsap; Promise._asap = asap; Promise.prototype = { constructor: Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: then, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function _catch(onRejection) { return this.then(null, onRejection); } }; function polyfill() { var local = undefined; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise; } polyfill(); // Strange compat.. Promise.polyfill = polyfill; Promise.Promise = Promise; return Promise; }))); //# sourceMappingURL=es6-promise.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("4362"), __webpack_require__("c8ba"))) /***/ }), /***/ "1385": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // 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) === Object.prototype ); }; /***/ }), /***/ "13a0": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3Hierarchy = __webpack_require__("c947"); var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var makeColorScaleFn = __webpack_require__("c258").makeColorScaleFuncFromTrace; var makePullColorFn = __webpack_require__("86b8").makePullColorFn; var generateExtendedColors = __webpack_require__("86b8").generateExtendedColors; var colorscaleCalc = __webpack_require__("c258").calc; var ALMOST_EQUAL = __webpack_require__("e806").ALMOST_EQUAL; var sunburstExtendedColorWays = {}; var treemapExtendedColorWays = {}; 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.'); } } 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. Error: ' + e.message); } 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, '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? 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 === 'treemap' ? treemapExtendedColorWays : sunburstExtendedColorWays ); } var dfltColorCount = 0; 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 { // root gets no coloring by default cdi.color = 'rgba(0,0,0,0)'; } } } for(var i = 0; i < calcdata.length; i++) { var cd = calcdata[i]; var cd0 = cd[0]; if(cd0.trace.type === desiredType && cd0.hierarchy) { 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; } /***/ }), /***/ "13a4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); // 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]; }; /***/ }), /***/ "13c3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * @module color-space/hsl */ var rgb = __webpack_require__("1bea"); module.exports = { name: 'hsl', min: [0,0,0], max: [360,100,100], channel: ['hue', 'saturation', 'lightness'], alias: ['HSL'], rgb: function(hsl) { var h = hsl[0] / 360, s = hsl[1] / 100, l = hsl[2] / 100, t1, t2, t3, rgb, val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * - (i - 1); if (t3 < 0) { t3++; } else if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; } }; //extend rgb rgb.hsl = function(rgb) { var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255, min = Math.min(r, g, b), max = Math.max(r, g, b), delta = max - min, h, s, l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g)/ delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; /***/ }), /***/ "13c4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Plots = __webpack_require__("bb71"); var axisIds = __webpack_require__("3c1c"); var Lib = __webpack_require__("fc26"); var Icons = __webpack_require__("7559"); 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', title: function(gd) { return _(gd, 'Zoom'); }, attr: 'dragmode', val: 'zoom', icon: Icons.zoombox, click: handleCartesian }; modeBarButtons.pan2d = { name: 'pan2d', title: function(gd) { return _(gd, 'Pan'); }, attr: 'dragmode', val: 'pan', icon: Icons.pan, click: handleCartesian }; modeBarButtons.select2d = { name: 'select2d', title: function(gd) { return _(gd, 'Box Select'); }, attr: 'dragmode', val: 'select', icon: Icons.selectbox, click: handleCartesian }; modeBarButtons.lasso2d = { name: 'lasso2d', title: function(gd) { return _(gd, 'Lasso Select'); }, attr: 'dragmode', val: 'lasso', icon: Icons.lasso, click: handleCartesian }; modeBarButtons.zoomIn2d = { name: 'zoomIn2d', title: function(gd) { return _(gd, 'Zoom in'); }, attr: 'zoom', val: 'in', icon: Icons.zoom_plus, click: handleCartesian }; modeBarButtons.zoomOut2d = { name: 'zoomOut2d', title: function(gd) { return _(gd, 'Zoom out'); }, attr: 'zoom', val: 'out', icon: Icons.zoom_minus, click: handleCartesian }; modeBarButtons.autoScale2d = { name: 'autoScale2d', title: function(gd) { return _(gd, 'Autoscale'); }, attr: 'zoom', val: 'auto', icon: Icons.autoscale, click: handleCartesian }; modeBarButtons.resetScale2d = { name: 'resetScale2d', title: function(gd) { return _(gd, 'Reset axes'); }, attr: 'zoom', val: 'reset', icon: Icons.home, click: handleCartesian }; modeBarButtons.hoverClosestCartesian = { name: 'hoverClosestCartesian', 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', 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._rangeInitial === undefined) { aobj[axName + '.autorange'] = true; } else { var rangeInitial = ax._rangeInitial.slice(); aobj[axName + '.range[0]'] = rangeInitial[0]; aobj[axName + '.range[1]'] = rangeInitial[1]; } // 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', title: function(gd) { return _(gd, 'Zoom'); }, attr: 'scene.dragmode', val: 'zoom', icon: Icons.zoombox, click: handleDrag3d }; modeBarButtons.pan3d = { name: 'pan3d', 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', title: function(gd) { return _(gd, 'Reset camera to default'); }, attr: 'resetDefault', icon: Icons.home, click: handleCamera3d }; modeBarButtons.resetCameraLastSave3d = { name: 'resetCameraLastSave3d', 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 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 scene = fullLayout[sceneId]._scene; var didUpdate; if(attr === 'resetLastSave') { aobj[camera + '.up'] = scene.viewInitial.up; aobj[camera + '.eye'] = scene.viewInitial.eye; aobj[camera + '.center'] = scene.viewInitial.center; didUpdate = true; } else if(attr === '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; } } Registry.call('_guiRelayout', gd, aobj); } modeBarButtons.hoverClosest3d = { name: 'hoverClosest3d', 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', title: function(gd) { return _(gd, 'Zoom in'); }, attr: 'zoom', val: 'in', icon: Icons.zoom_plus, click: handleGeo }; modeBarButtons.zoomOutGeo = { name: 'zoomOutGeo', title: function(gd) { return _(gd, 'Zoom out'); }, attr: 'zoom', val: 'out', icon: Icons.zoom_minus, click: handleGeo }; modeBarButtons.resetGeo = { name: 'resetGeo', title: function(gd) { return _(gd, 'Reset'); }, attr: 'reset', val: null, icon: Icons.autoscale, click: handleGeo }; modeBarButtons.hoverClosestGeo = { name: 'hoverClosestGeo', 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', 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', 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', title: function(gd) { return _(gd, 'Reset view'); }, attr: 'reset', icon: Icons.home, click: function(gd) { resetView(gd, 'mapbox'); } }; modeBarButtons.zoomInMapbox = { name: 'zoomInMapbox', title: function(gd) { return _(gd, 'Zoom in'); }, attr: 'zoom', val: 'in', icon: Icons.zoom_plus, click: handleMapboxZoom }; modeBarButtons.zoomOutMapbox = { name: 'zoomOutMapbox', 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); } /***/ }), /***/ "13d5": /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__("23e7"); var $reduce = __webpack_require__("d58f").left; var arrayMethodIsStrict = __webpack_require__("a640"); var arrayMethodUsesToLength = __webpack_require__("ae40"); var STRICT_METHOD = arrayMethodIsStrict('reduce'); var USES_TO_LENGTH = arrayMethodUsesToLength('reduce', { 1: 0 }); // `Array.prototype.reduce` method // https://tc39.github.io/ecma262/#sec-array.prototype.reduce $({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, { reduce: function reduce(callbackfn /* , initialValue */) { return $reduce(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); } }); /***/ }), /***/ "1417": /***/ (function(module, exports) { module.exports = multiply; /** * Multiplies two mat4's * * @param {mat4} out the receiving matrix * @param {mat4} a the first operand * @param {mat4} b the second operand * @returns {mat4} out */ function multiply(out, a, b) { var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; // Cache only the current line of the second matrix var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; return out; }; /***/ }), /***/ "145a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var getModuleCalcData = __webpack_require__("ad62").getModuleCalcData; var parcatsPlot = __webpack_require__("3e11"); 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(); } }; /***/ }), /***/ "1477": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isBrowser = __webpack_require__("dcf3") function detect() { var supported = false try { var opts = Object.defineProperty({}, 'passive', { get: function() { supported = true } }) window.addEventListener('test', null, opts) window.removeEventListener('test', null, opts) } catch(e) { supported = false } return supported } module.exports = isBrowser && detect() /***/ }), /***/ "14ab": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function () { var assign = Object.assign, obj; if (typeof assign !== "function") return false; obj = { foo: "raz" }; assign(obj, { bar: "dwa" }, { trzy: "trzy" }); return obj.foo + obj.bar + obj.trzy === "razdwatrzy"; }; /***/ }), /***/ "14b6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var annAttrs = __webpack_require__("bb4a"); var overrideAll = __webpack_require__("cb34").overrideAll; var templatedArray = __webpack_require__("a651").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'); /***/ }), /***/ "14c3": /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__("c6b6"); var regexpExec = __webpack_require__("9263"); // `RegExpExec` abstract operation // https://tc39.github.io/ecma262/#sec-regexpexec module.exports = function (R, S) { var exec = R.exec; if (typeof exec === 'function') { var result = exec.call(R, S); if (typeof result !== 'object') { throw TypeError('RegExp exec method returned something other than an Object or null'); } return result; } if (classof(R) !== 'RegExp') { throw TypeError('RegExp#exec called on incompatible receiver'); } return regexpExec.call(R, S); }; /***/ }), /***/ "14cf": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function () { var from = Array.from, arr, result; if (typeof from !== "function") return false; arr = ["raz", "dwa"]; result = from(arr); return Boolean(result && result !== arr && result[1] === "dwa"); }; /***/ }), /***/ "158b": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = findMedian var genPartition = __webpack_require__("8e58") var partitionStartLessThan = genPartition('lostart && 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 < hi) { if(hi - lo < PARTITION_THRESHOLD) { insertionSort(d, axis, lo, hi, boxes, ids) value = boxes[elemSize*mid+axis] break } //Select pivot using median-of-3 var count = hi - lo var pivot0 = (Math.random()*count+lo)|0 var value0 = boxes[elemSize*pivot0 + axis] var pivot1 = (Math.random()*count+lo)|0 var value1 = boxes[elemSize*pivot1 + axis] var pivot2 = (Math.random()*count+lo)|0 var value2 = boxes[elemSize*pivot2 + axis] if(value0 <= value1) { if(value2 >= 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 0) { for (var a = 0; a < facets; a++) { var a1 = (a+1) % facets; verts.push( previousVerts[a], currentVerts[a], currentVerts[a1], currentVerts[a1], previousVerts[a1], previousVerts[a] ); vectors.push( previousVector, currentVector, currentVector, currentVector, previousVector, previousVector ); intensities.push( previousIntensity, currentIntensity, currentIntensity, currentIntensity, previousIntensity, previousIntensity ); var len = verts.length; faces.push( [len-6, len-5, len-4], [len-3, len-2, len-1] ); } } var tmp1 = previousVerts; previousVerts = currentVerts; currentVerts = tmp1; var tmp2 = previousVector; previousVector = currentVector; currentVector = tmp2; var tmp3 = previousIntensity; previousIntensity = currentIntensity; currentIntensity = tmp3; } return { positions: verts, cells: faces, vectors: vectors, vertexIntensity: intensities }; }; var createTubes = function(streams, colormap, maxDivergence, minDistance) { var maxNorm = 0; for (var i=0; i v) return i-1; } return i; }; var clamp = function(v, min, max) { return v < min ? min : (v > max ? max : v); }; var sampleMeshgrid = function(point, vectorField, gridInfo) { var vectors = vectorField.vectors; var meshgrid = vectorField.meshgrid; var x = point[0]; var y = point[1]; var z = point[2]; var w = meshgrid[0].length; var h = meshgrid[1].length; var d = meshgrid[2].length; // Find the index of the nearest smaller value in the meshgrid for each coordinate of (x,y,z). // The nearest smaller value index for x is the index x0 such that // meshgrid[0][x0] < x and for all x1 > x0, meshgrid[0][x1] >= x. var x0 = findLastSmallerIndex(meshgrid[0], x); var y0 = findLastSmallerIndex(meshgrid[1], y); var z0 = findLastSmallerIndex(meshgrid[2], z); // Get the nearest larger meshgrid value indices. // From the above "nearest smaller value", we know that // meshgrid[0][x0] < x // meshgrid[0][x0+1] >= x var x1 = x0 + 1; var y1 = y0 + 1; var z1 = z0 + 1; x0 = clamp(x0, 0, w-1); x1 = clamp(x1, 0, w-1); y0 = clamp(y0, 0, h-1); y1 = clamp(y1, 0, h-1); z0 = clamp(z0, 0, d-1); z1 = clamp(z1, 0, d-1); // Reject points outside the meshgrid, return a zero vector. if (x0 < 0 || y0 < 0 || z0 < 0 || x1 > w-1 || y1 > h-1 || z1 > d-1) { return vec3.create(); } // Normalize point coordinates to 0..1 scaling factor between x0 and x1. var mX0 = meshgrid[0][x0]; var mX1 = meshgrid[0][x1]; var mY0 = meshgrid[1][y0]; var mY1 = meshgrid[1][y1]; var mZ0 = meshgrid[2][z0]; var mZ1 = meshgrid[2][z1]; var xf = (x - mX0) / (mX1 - mX0); var yf = (y - mY0) / (mY1 - mY0); var zf = (z - mZ0) / (mZ1 - mZ0); if (!isFinite(xf)) xf = 0.5; if (!isFinite(yf)) yf = 0.5; if (!isFinite(zf)) zf = 0.5; var x0off; var x1off; var y0off; var y1off; var z0off; var z1off; if(gridInfo.reversedX) { x0 = w - 1 - x0; x1 = w - 1 - x1; } if(gridInfo.reversedY) { y0 = h - 1 - y0; y1 = h - 1 - y1; } if(gridInfo.reversedZ) { z0 = d - 1 - z0; z1 = d - 1 - z1; } switch(gridInfo.filled) { case 5: // 'zyx' z0off = z0; z1off = z1; y0off = y0*d; y1off = y1*d; x0off = x0*d*h; x1off = x1*d*h; break; case 4: // 'zxy' z0off = z0; z1off = z1; x0off = x0*d; x1off = x1*d; y0off = y0*d*w; y1off = y1*d*w; break; case 3: // 'yzx' y0off = y0; y1off = y1; z0off = z0*h; z1off = z1*h; x0off = x0*h*d; x1off = x1*h*d; break; case 2: // 'yxz' y0off = y0; y1off = y1; x0off = x0*h; x1off = x1*h; z0off = z0*h*w; z1off = z1*h*w; break; case 1: // 'xzy' x0off = x0; x1off = x1; z0off = z0*w; z1off = z1*w; y0off = y0*w*d; y1off = y1*w*d; break; default: // case 0: // 'xyz' x0off = x0; x1off = x1; y0off = y0*w; y1off = y1*w; z0off = z0*w*h; z1off = z1*w*h; break; } // Sample data vectors around the (x,y,z) point. var v000 = vectors[x0off + y0off + z0off]; var v001 = vectors[x0off + y0off + z1off]; var v010 = vectors[x0off + y1off + z0off]; var v011 = vectors[x0off + y1off + z1off]; var v100 = vectors[x1off + y0off + z0off]; var v101 = vectors[x1off + y0off + z1off]; var v110 = vectors[x1off + y1off + z0off]; var v111 = vectors[x1off + y1off + z1off]; var c00 = vec3.create(); var c01 = vec3.create(); var c10 = vec3.create(); var c11 = vec3.create(); vec3.lerp(c00, v000, v100, xf); vec3.lerp(c01, v001, v101, xf); vec3.lerp(c10, v010, v110, xf); vec3.lerp(c11, v011, v111, xf); var c0 = vec3.create(); var c1 = vec3.create(); vec3.lerp(c0, c00, c10, yf); vec3.lerp(c1, c01, c11, yf); var c = vec3.create(); vec3.lerp(c, c0, c1, zf); return c; }; var vabs = function(dst, v) { var x = v[0]; var y = v[1]; var z = v[2]; dst[0] = x < 0 ? -x : x; dst[1] = y < 0 ? -y : y; dst[2] = z < 0 ? -z : z; return dst; }; var findMinSeparation = function(xs) { var minSeparation = Infinity; xs.sort(function(a, b) { return a - b; }); var len = xs.length; for (var i=1; i maxX || y < minY || y > maxY || z < minZ || z > maxZ ); }; var boundsSize = vec3.distance(bounds[0], bounds[1]); var maxStepSize = 10 * boundsSize / maxLength; var maxStepSizeSq = maxStepSize * maxStepSize; var minDistance = 1; var maxDivergence = 0; // For component-wise divergence vec3.create(); // In case we need to do component-wise divergence visualization // var tmp = vec3.create(); var len = positions.length; if (len > 1) { minDistance = calculateMinPositionDistance(positions); } for (var i = 0; i < len; i++) { var p = vec3.create(); vec3.copy(p, positions[i]); var stream = [p]; var velocities = []; var v = getVelocity(p); var op = p; velocities.push(v); var divergences = []; var dv = getDivergence(p, v); var dvLength = vec3.length(dv); if (isFinite(dvLength) && dvLength > maxDivergence) { maxDivergence = dvLength; } // In case we need to do component-wise divergence visualization // vec3.max(maxDivergence, maxDivergence, vabs(tmp, dv)); divergences.push(dvLength); streams.push({points: stream, velocities: velocities, divergences: divergences}); var j = 0; while (j < maxLength * 100 && stream.length < maxLength && inBounds(p)) { j++; var np = vec3.clone(v); var sqLen = vec3.squaredLength(np); if (sqLen === 0) { break; } else if (sqLen > maxStepSizeSq) { vec3.scale(np, np, maxStepSize / Math.sqrt(sqLen)); } vec3.add(np, np, p); v = getVelocity(np); if (vec3.squaredDistance(op, np) - maxStepSizeSq > -0.0001 * maxStepSizeSq) { stream.push(np); op = np; velocities.push(v); var dv = getDivergence(np, v); var dvLength = vec3.length(dv); if (isFinite(dvLength) && dvLength > maxDivergence) { maxDivergence = dvLength; } // In case we need to do component-wise divergence visualization //vec3.max(maxDivergence, maxDivergence, vabs(tmp, dv)); divergences.push(dvLength); } p = np; } } var tubes = createTubes(streams, vectorField.colormap, maxDivergence, minDistance); if (absoluteTubeSize) { tubes.tubeScale = absoluteTubeSize; } else { // Avoid division by zero. if (maxDivergence === 0) { maxDivergence = 1; } tubes.tubeScale = tubeSize * 0.5 * minDistance / maxDivergence; } return tubes; }; var shaders = __webpack_require__("aee4"); var createMesh = __webpack_require__("2969").createMesh; module.exports.createTubeMesh = function(gl, params) { return createMesh(gl, params, { shaders: shaders, traceType: 'streamtube' }); } /***/ }), /***/ "16ef": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("7c39"), layoutAttributes: __webpack_require__("36fc"), supplyDefaults: __webpack_require__("49d8"), crossTraceDefaults: __webpack_require__("abc9").crossTraceDefaults, supplyLayoutDefaults: __webpack_require__("870c"), calc: __webpack_require__("b8c0"), crossTraceCalc: __webpack_require__("e9d4"), plot: __webpack_require__("8298"), style: __webpack_require__("c451"), styleOnSelect: __webpack_require__("52e8").styleOnSelect, hoverPoints: __webpack_require__("ca92"), selectPoints: __webpack_require__("71b1"), moduleType: 'trace', name: 'violin', basePlotModule: __webpack_require__("91cd"), categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'violinLayout', 'zoomScale'], meta: { } }; /***/ }), /***/ "1729": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Color = __webpack_require__("d115"); // 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) ); Lib.coerceFont(coerce, 'hoverlabel.font', { family: globalHoverLabel.font.family, size: globalHoverLabel.font.size, color: globalHoverLabel.font.color || hoverBorder }); } coerce('captureevents', !!hoverText); }; /***/ }), /***/ "1735": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("02ea"), supplyDefaults: __webpack_require__("2ff0"), colorbar: { min: 'cmin', max: 'cmax' }, calc: __webpack_require__("0054"), plot: __webpack_require__("baab"), moduleType: 'trace', name: 'surface', basePlotModule: __webpack_require__("134c"), categories: ['gl3d', '2dMap', 'showLegend'], meta: { } }; /***/ }), /***/ "175e": /***/ (function(module, exports, __webpack_require__) { "use strict"; function unique_pred(list, compare) { var ptr = 1 , len = list.length , a=list[0], b=list[0] for(var i=1; i 1.0) { t = 1.0 } var ti = 1.0 - t var n = a.length var r = new Array(n) for(var i=0; i 0) || (a > 0 && b < 0)) { var p = lerpW(s, b, t, a) pos.push(p) neg.push(p.slice()) } if(b < 0) { neg.push(t.slice()) } else if(b > 0) { pos.push(t.slice()) } else { pos.push(t.slice()) neg.push(t.slice()) } a = b } return { positive: pos, negative: neg } } function positive(points, plane) { var pos = [] var a = planeT(points[points.length-1], plane) for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { pos.push(lerpW(s, b, t, a)) } if(b >= 0) { pos.push(t.slice()) } a = b } return pos } function negative(points, plane) { var neg = [] var a = planeT(points[points.length-1], plane) for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { neg.push(lerpW(s, b, t, a)) } if(b <= 0) { neg.push(t.slice()) } a = b } return neg } /***/ }), /***/ "1793": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isFunction = __webpack_require__("6321"); var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString; module.exports = function (value) { if (!isFunction(value)) return false; if (classRe.test(functionToString.call(value))) return false; return true; }; /***/ }), /***/ "17c2": /***/ (function(module, exports, __webpack_require__) { "use strict"; var $forEach = __webpack_require__("b727").forEach; var arrayMethodIsStrict = __webpack_require__("a640"); var arrayMethodUsesToLength = __webpack_require__("ae40"); var STRICT_METHOD = arrayMethodIsStrict('forEach'); var USES_TO_LENGTH = arrayMethodUsesToLength('forEach'); // `Array.prototype.forEach` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.foreach module.exports = (!STRICT_METHOD || !USES_TO_LENGTH) ? function forEach(callbackfn /* , thisArg */) { return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } : [].forEach; /***/ }), /***/ "182a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var getModuleCalcData = __webpack_require__("ad62").getModuleCalcData; var tablePlot = __webpack_require__("26dd"); 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(); } }; /***/ }), /***/ "1876": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var polybool = __webpack_require__("2441"); var Registry = __webpack_require__("371e"); var Color = __webpack_require__("d115"); var Fx = __webpack_require__("a5c4"); var Lib = __webpack_require__("fc26"); var polygon = __webpack_require__("b68b"); var throttle = __webpack_require__("7df2"); var makeEventData = __webpack_require__("c4c7").makeEventData; var getFromId = __webpack_require__("3c1c").getFromId; var clearGlCanvases = __webpack_require__("821b"); var redrawReglTraces = __webpack_require__("a392").redrawReglTraces; var constants = __webpack_require__("d301"); var MINSELECT = constants.MINSELECT; var filteredPolygon = polygon.filter; var polygonTester = polygon.tester; function getAxId(ax) { return ax._id; } function prepSelect(e, startX, startY, dragOptions, mode) { var gd = dragOptions.gd; var fullLayout = gd._fullLayout; var zoomLayer = fullLayout._zoomlayer; var dragBBox = dragOptions.element.getBoundingClientRect(); var plotinfo = dragOptions.plotinfo; var xs = plotinfo.xaxis._offset; var ys = plotinfo.yaxis._offset; var x0 = startX - dragBBox.left; var y0 = startY - dragBBox.top; var x1 = x0; var y1 = y0; var path0 = 'M' + x0 + ',' + y0; var pw = dragOptions.xaxes[0]._length; var ph = dragOptions.yaxes[0]._length; var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); var subtract = e.altKey; var filterPoly, selectionTester, mergedPolygons, currentPolygon; var i, searchInfo, eventData; coerceSelectionsCache(e, gd, dragOptions); if(mode === 'lasso') { filterPoly = filteredPolygon([[x0, y0]], constants.BENDPX); } var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); outlines.enter() .append('path') .attr('class', function(d) { return 'select-outline select-outline-' + d + ' select-outline-' + plotinfo.id; }) .attr('transform', 'translate(' + xs + ', ' + ys + ')') .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', 'translate(' + xs + ', ' + ys + ')') .attr('d', 'M0,0Z'); 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); // in v2 (once log ranges are fixed), // we'll be able to p2r here for all axis types function p2r(ax, v) { return ax.type === 'log' ? ax.p2d(v) : ax.p2r(v); } function axValue(ax) { var index = (ax._id.charAt(0) === 'y') ? 1 : 0; return function(v) { return p2r(ax, v[index]); }; } function ascending(a, b) { return a - b; } // allow subplots to override fillRangeItems routine var fillRangeItems; if(plotinfo.fillRangeItems) { fillRangeItems = plotinfo.fillRangeItems; } else { if(mode === 'select') { fillRangeItems = function(eventData, poly) { var ranges = eventData.range = {}; for(i = 0; i < allAxes.length; i++) { var ax = allAxes[i]; var axLetter = ax._id.charAt(0); ranges[ax._id] = [ p2r(ax, poly[axLetter + 'min']), p2r(ax, poly[axLetter + 'max']) ].sort(ascending); } }; } else { fillRangeItems = function(eventData, poly, filterPoly) { var dataPts = eventData.lassoPoints = {}; for(i = 0; i < allAxes.length; i++) { var ax = allAxes[i]; dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); } }; } } dragOptions.moveFn = function(dx0, dy0) { x1 = Math.max(0, Math.min(pw, dx0 + x0)); y1 = Math.max(0, Math.min(ph, dy0 + y0)); var dx = Math.abs(x1 - x0); var dy = Math.abs(y1 - y0); if(mode === 'select') { var direction = fullLayout.selectdirection; if(fullLayout.selectdirection === '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 = fullLayout.selectdirection; } if(direction === 'h') { // horizontal motion: make a vertical box currentPolygon = [[x0, 0], [x0, ph], [x1, ph], [x1, 0]]; currentPolygon.xmin = Math.min(x0, x1); currentPolygon.xmax = Math.max(x0, x1); currentPolygon.ymin = Math.min(0, ph); currentPolygon.ymax = Math.max(0, ph); // 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: make a horizontal box currentPolygon = [[0, y0], [0, y1], [pw, y1], [pw, y0]]; currentPolygon.xmin = Math.min(0, pw); currentPolygon.xmax = Math.max(0, pw); currentPolygon.ymin = Math.min(y0, y1); currentPolygon.ymax = 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 = [[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(mode === 'lasso') { 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; selectionTester = multiTester(dragOptions.selectionDefs.concat([currentPolygon])); } else { mergedPolygons = [currentPolygon]; selectionTester = polygonTester(currentPolygon); } // draw selection drawSelection(mergedPolygons, outlines); throttle.throttle( throttleID, constants.SELECTDELAY, function() { selection = []; var thisSelection; var traceSelections = []; var traceSelection; for(i = 0; i < searchTraces.length; i++) { searchInfo = searchTraces[i]; traceSelection = searchInfo._module.selectPoints(searchInfo, selectionTester); traceSelections.push(traceSelection); thisSelection = fillSelectionItem(traceSelection, searchInfo); if(selection.length) { for(var j = 0; j < thisSelection.length; j++) { selection.push(thisSelection[j]); } } else selection = thisSelection; } eventData = {points: selection}; updateSelectedState(gd, searchTraces, eventData); fillRangeItems(eventData, currentPolygon, filterPoly); dragOptions.gd.emit('plotly_selecting', eventData); } ); }; dragOptions.clickFn = function(numClicks, evt) { var clickmode = fullLayout.clickmode; corners.remove(); 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); gd.emit('plotly_deselect', null); } else { if(clickmode.indexOf('select') > -1) { selectOnClick(evt, gd, dragOptions.xaxes, dragOptions.yaxes, dragOptions.subplot, dragOptions, outlines); } if(clickmode === 'event') { // TODO: remove in v2 - 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 v2 also emitts proper // event data when clickmode is having 'select' in its flag list. gd.emit('plotly_selected', undefined); } } Fx.click(gd, evt); }).catch(Lib.error); }; dragOptions.doneFn = function() { corners.remove(); throttle.done(throttleID).then(function() { throttle.clear(throttleID); dragOptions.gd.emit('plotly_selected', eventData); if(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(dragOptions.doneFnCompleted) { dragOptions.doneFnCompleted(selection); } }).catch(Lib.error); }; } function selectOnClick(evt, gd, xAxes, yAxes, subplot, dragOptions, polygonOutlines) { var hoverData = gd._hoverdata; var clickmode = gd._fullLayout.clickmode; var sendEvents = clickmode.indexOf('event') > -1; var selection = []; var searchTraces, searchInfo, currentSelectionDef, selectionTester, 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) { gd.emit('plotly_deselect', null); } } else { subtract = evt.shiftKey && (pointOrBinSelected !== undefined ? pointOrBinSelected : isPointOrBinSelected(clickedPtInfo)); currentSelectionDef = newPointSelectionDef(clickedPtInfo.pointNumber, clickedPtInfo.searchInfo, subtract); var allSelectionDefs = dragOptions.selectionDefs.concat([currentSelectionDef]); selectionTester = multiTester(allSelectionDefs); for(i = 0; i < searchTraces.length; i++) { traceSelection = searchTraces[i]._module.selectPoints(searchTraces[i], selectionTester); 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) drawSelection(dragOptions.mergedPolygons, polygonOutlines); if(sendEvents) { gd.emit('plotly_selected', 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) { 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 = polygon.tester(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 === false; } } 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 selectingOnSameSubplot = ( fullLayout._lastSelectedSubplot && fullLayout._lastSelectedSubplot === plotinfo.id ); var hasModifierKey = evt.shiftKey || evt.altKey; 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) { clearSelect(gd); fullLayout._lastSelectedSubplot = plotinfo.id; } } function clearSelectionsCache(dragOptions) { var plotinfo = dragOptions.plotinfo; plotinfo.selection = {}; plotinfo.selection.selectionDefs = dragOptions.selectionDefs = []; plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; } function determineSearchTraces(gd, xAxes, yAxes, subplot) { 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(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 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) continue; if(yAxisIds.indexOf(trace.yaxis) === -1) 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 drawSelection(polygons, outlines) { var paths = []; var i, d; for(i = 0; i < polygons.length; i++) { var ppts = polygons[i]; paths.push(ppts.join('L') + 'L' + ppts[0]); } d = polygons.length > 0 ? 'M' + paths.join('M') + 'Z' : 'M0,0Z'; outlines.attr('d', d); } 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, searchInfo, cd, trace; // 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; } } 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(i = 0; i < pts.length; i++) { var pt = pts[i]; var data = pt.data; var fullData = pt.fullData; if(pt.pointIndices) { [].push.apply(data.selectedpoints, pt.pointIndices); if(trace._fullInput !== trace) { [].push.apply(fullData.selectedpoints, pt.pointIndices); } } else { data.selectedpoints.push(pt.pointIndex); if(trace._fullInput !== trace) { fullData.selectedpoints.push(pt.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; } } } var hasRegl = false; for(i = 0; i < searchTraces.length; i++) { searchInfo = searchTraces[i]; cd = searchInfo.cd; trace = cd[0].trace; if(Registry.traceIs(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 res; if(subtract) { res = polybool.difference({ regions: list, inverted: false }, { regions: [poly], inverted: false }); return res.regions; } res = polybool.union({ regions: list, inverted: false }, { regions: [poly], inverted: false }); return res.regions; } 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; } // until we get around to persistent selections, remove the outline // here. The selection itself will be removed when the plot redraws // at the end. function clearSelect(gd) { var fullLayout = gd._fullLayout || {}; var zoomlayer = fullLayout._zoomlayer; if(zoomlayer) { zoomlayer.selectAll('.select-outline').remove(); } } module.exports = { prepSelect: prepSelect, clearSelect: clearSelect, selectOnClick: selectOnClick }; /***/ }), /***/ "18a2": /***/ (function(module, exports, __webpack_require__) { "use strict"; var rationalize = __webpack_require__("2195") module.exports = div function div(a, b) { return rationalize(a[0].mul(b[1]), a[1].mul(b[0])) } /***/ }), /***/ "18bb": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var attributes = __webpack_require__("1c82"); var handleDomainDefaults = __webpack_require__("81f0").defaults; var Template = __webpack_require__("a651"); var handleArrayContainerDefaults = __webpack_require__("e5ac"); var cn = __webpack_require__("49b4"); var handleTickValueDefaults = __webpack_require__("d92f"); var handleTickMarkDefaults = __webpack_require__("27e3"); var handleTickLabelDefaults = __webpack_require__("5008"); 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'); coerce('number.font.color', layout.font.color); coerce('number.font.family', layout.font.family); coerce('number.font.size'); 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) { coerce('delta.font.color', layout.font.color); coerce('delta.font.family', layout.font.family); coerce('delta.font.size'); 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'); deltaFontSize = traceOut.delta.font.size; } traceOut._scaleNumbers = (!traceOut._hasNumber || auto[0]) && (!traceOut._hasDelta || auto[1]) || false; // Title attributes coerce('title.font.color', layout.font.color); coerce('title.font.family', layout.font.family); coerce('title.font.size', 0.25 * (bignumberFontSize || deltaFontSize || cn.defaultNumberFontSize)); 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 = {outerTicks: true}; handleTickValueDefaults(axisIn, axisOut, coerceGaugeAxis, 'linear'); 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 }; /***/ }), /***/ "18ec": /***/ (function(module, exports, __webpack_require__) { "use strict"; var str = "razdwatrzy"; module.exports = function () { if (typeof str.contains !== "function") return false; return str.contains("dwa") === true && str.contains("foo") === false; }; /***/ }), /***/ "191c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var constants = __webpack_require__("de69"); var subTypes = __webpack_require__("de81"); var handleMarkerDefaults = __webpack_require__("5047"); var handleLineDefaults = __webpack_require__("59be"); var handleLineShapeDefaults = __webpack_require__("eb07"); var handleTextDefaults = __webpack_require__("e9f7"); var handleFillColorDefaults = __webpack_require__("3802"); var attributes = __webpack_require__("ce65"); 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.hasLines(traceOut)) { handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce); handleLineShapeDefaults(traceIn, traceOut, coerce); coerce('connectgaps'); } if(subTypes.hasMarkers(traceOut)) { handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } 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); }; /***/ }), /***/ "1936": /***/ (function(module, exports) { module.exports = [ // current 'precision' , 'highp' , 'mediump' , 'lowp' , 'attribute' , 'const' , 'uniform' , 'varying' , 'break' , 'continue' , 'do' , 'for' , 'while' , 'if' , 'else' , 'in' , 'out' , 'inout' , 'float' , 'int' , 'uint' , 'void' , 'bool' , 'true' , 'false' , 'discard' , 'return' , 'mat2' , 'mat3' , 'mat4' , 'vec2' , 'vec3' , 'vec4' , 'ivec2' , 'ivec3' , 'ivec4' , 'bvec2' , 'bvec3' , 'bvec4' , 'sampler1D' , 'sampler2D' , 'sampler3D' , 'samplerCube' , 'sampler1DShadow' , 'sampler2DShadow' , 'struct' // future , 'asm' , 'class' , 'union' , 'enum' , 'typedef' , 'template' , 'this' , 'packed' , 'goto' , 'switch' , 'default' , 'inline' , 'noinline' , 'volatile' , 'public' , 'static' , 'extern' , 'external' , 'interface' , 'long' , 'short' , 'double' , 'half' , 'fixed' , 'unsigned' , 'input' , 'output' , 'hvec2' , 'hvec3' , 'hvec4' , 'dvec2' , 'dvec3' , 'dvec4' , 'fvec2' , 'fvec3' , 'fvec4' , 'sampler2DRect' , 'sampler3DRect' , 'sampler2DRectShadow' , 'sizeof' , 'cast' , 'namespace' , 'using' ] /***/ }), /***/ "1978": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' module.exports = function makeBubbleSizeFn(trace) { 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 / 2); // don't show non-numeric and negative sizes return (isNumeric(baseSize) && (baseSize > 0)) ? Math.max(baseSize, sizeMin) : 0; }; }; /***/ }), /***/ "1999": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var isNumeric = __webpack_require__("19b2"); var Plots = __webpack_require__("bb71"); var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var Drawing = __webpack_require__("83d1"); var Color = __webpack_require__("d115"); var svgTextUtils = __webpack_require__("0379"); var interactConstants = __webpack_require__("72a4"); var OPPOSITE_SIDE = __webpack_require__("63dc").OPPOSITE_SIDE; var numStripRE = / [XY][0-9]* /; /** * 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 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 fullLayout = gd._fullLayout; var opacity = 1; var isplaceholder = false; var title = cont.title; var txt = (title && title.text ? title.text : '').trim(); var font = title && title.font ? title.font : {}; var fontFamily = font.family; var fontSize = font.size; var fontColor = font.color; // only make this title editable if we positively identify its property // as one that has editing enabled. 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]; if(txt === '') opacity = 0; // 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. else if(txt.replace(numStripRE, ' % ') === placeholder.replace(numStripRE, ' % ')) { opacity = 0.2; isplaceholder = true; if(!editable) txt = ''; } if(options._meta) { txt = Lib.templateString(txt, options._meta); } else if(fullLayout._meta) { txt = Lib.templateString(txt, fullLayout._meta); } var elShouldExist = txt || editable; if(!group) { group = Lib.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') .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(); if(!elShouldExist) return group; function titleLayout(titleEl) { Lib.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { var transformVal; if(transform) { transformVal = ''; if(transform.rotate) { transformVal += 'rotate(' + [transform.rotate, attributes.x, attributes.y] + ')'; } if(transform.offset) { transformVal += 'translate(0, ' + transform.offset + ')'; } } else { transformVal = null; } titleEl.attr('transform', transformVal); titleEl.style({ 'font-family': fontFamily, 'font-size': d3.round(fontSize, 2) + 'px', fill: Color.rgb(fontColor), opacity: opacity * Color.opacity(fontColor), 'font-weight': Plots.fontWeight }) .attr(attributes) .call(svgTextUtils.convertToTspans, gd); return Plots.previousPromises(gd); } function scootTitle(titleElIn) { 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()); var paperbb = { left: 0, top: 0, right: fullLayout.width, bottom: fullLayout.height }; 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); } if(shift > 0 || maxshift < 0) { var shiftTemplate = { left: [-shift, 0], right: [shift, 0], top: [0, -shift], bottom: [0, shift] }[avoid.side]; titleGroup.attr('transform', 'translate(' + shiftTemplate + ')'); } } } el.call(titleLayout); function setPlaceholder() { opacity = 0; isplaceholder = true; el.text(placeholder) .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(); 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); }); } el.classed('js-placeholder', isplaceholder); return group; } module.exports = { draw: draw }; /***/ }), /***/ "19b2": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * inspired by is-number * but significantly simplified and sped up by ignoring number and string constructors * ie these return false: * new Number(1) * new String('1') */ var allBlankCharCodes = __webpack_require__("e9b4"); module.exports = function(n) { var type = typeof n; if(type === 'string') { var original = n; n = +n; // whitespace strings cast to zero - filter them out if(n===0 && allBlankCharCodes(original)) return false; } else if(type !== 'number') return false; return n - n < 1; }; /***/ }), /***/ "19e1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var mod = __webpack_require__("d3dc").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; }; /***/ }), /***/ "1a06": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var handleXYZDefaults = __webpack_require__("41e0"); var handleConstraintDefaults = __webpack_require__("86df"); var handleContoursDefaults = __webpack_require__("d61b"); var handleStyleDefaults = __webpack_require__("41f8"); var attributes = __webpack_require__("43ef"); 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; } coerce('text'); coerce('hovertext'); coerce('hovertemplate'); coerce('hoverongaps'); 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); } }; /***/ }), /***/ "1a3f": /***/ (function(module, exports, __webpack_require__) { "use strict"; var convexHull1d = __webpack_require__("1f25") var convexHull2d = __webpack_require__("8ff7") var convexHullnd = __webpack_require__("ca39") module.exports = convexHull function convexHull(points) { var n = points.length if(n === 0) { return [] } else if(n === 1) { return [[0]] } var d = points[0].length if(d === 0) { return [] } else if(d === 1) { return convexHull1d(points) } else if(d === 2) { return convexHull2d(points) } return convexHullnd(points, d) } /***/ }), /***/ "1a40": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var cleanNumber = Lib.cleanNumber; var ms2DateTime = Lib.ms2DateTime; var dateTime2ms = Lib.dateTime2ms; var ensureNumber = Lib.ensureNumber; var isArrayOrTypedArray = Lib.isArrayOrTypedArray; var numConstants = __webpack_require__("e806"); var FP_SAFE = numConstants.FP_SAFE; var BADNUM = numConstants.BADNUM; var LOG_CLIP = numConstants.LOG_CLIP; var constants = __webpack_require__("d301"); var axisIds = __webpack_require__("3c1c"); 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 v2.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) { // 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 l2p(v) { if(!isNumeric(v)) return BADNUM; // include 2 fractional digits on pixel, for PDF zooming etc return d3.round(ax._b + ax._m * v, 2); } function p2l(px) { return (px - ax._b) / ax._m; } // 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 = getCategoryPosition(v); return index !== undefined ? index : ax.fraction2r(0.5); }; 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(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 matchGroups = fullLayout._axisMatchGroups; if(matchGroups && matchGroups.length && ax._categories.length === 0) { for(i = 0; i < matchGroups.length; i++) { var group = matchGroups[i]; if(group[axId]) { 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); }; /* * 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) { 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 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; } 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(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 occuring, 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); if(axLetter === 'y') { 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; } if(!isFinite(ax._m) || !isFinite(ax._b) || ax._length < 0) { fullLayout._replotting = false; throw new Error('Something went wrong with axis scaling'); } }; // 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) { 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); } } 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; } } return arrayOut; }; ax.isValidRange = function(range) { return ( Array.isArray(range) && range.length === 2 && isNumeric(ax.r2l(range[0])) && isNumeric(ax.r2l(range[1])) ); }; 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; } }; // should skip if not category nor multicategory ax.clearCalc = function() { var emptyCategories = function() { ax._categories = []; ax._categoriesMap = {}; }; var matchGroups = fullLayout._axisMatchGroups; if(matchGroups && matchGroups.length) { var found = false; for(var i = 0; i < matchGroups.length; i++) { var group = matchGroups[i]; if(group[axId]) { found = true; 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 { emptyCategories(); } break; } } if(!found) emptyCategories(); } else { 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 = []; var emptyCategories = function() { ax._categories = []; ax._categoriesMap = {}; }; 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.utc : d3.time.format.utc; 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 : d3.format; // and for bar charts and box plots: reset forced minimum tick spacing delete ax._minDtick; delete ax._forceTick0; }; /***/ }), /***/ "1a5e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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'] }; /***/ }), /***/ "1a88": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // CONCATENATED MODULE: ./node_modules/d3-path/src/path.js var pi = Math.PI, tau = 2 * pi, epsilon = 1e-6, tauEpsilon = tau - epsilon; function Path() { this._x0 = this._y0 = // start of current subpath this._x1 = this._y1 = null; // end of current subpath this._ = ""; } function path() { return new Path; } Path.prototype = path.prototype = { constructor: Path, moveTo: function(x, y) { this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y); }, closePath: function() { if (this._x1 !== null) { this._x1 = this._x0, this._y1 = this._y0; this._ += "Z"; } }, lineTo: function(x, y) { this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y); }, quadraticCurveTo: function(x1, y1, x, y) { this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y); }, bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y); }, arcTo: function(x1, y1, x2, y2, r) { x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r; var x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01; // Is the radius negative? Error. if (r < 0) throw new Error("negative radius: " + r); // Is this path empty? Move to (x1,y1). if (this._x1 === null) { this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1); } // Or, is (x1,y1) coincident with (x0,y0)? Do nothing. else if (!(l01_2 > epsilon)); // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear? // Equivalently, is (x1,y1) coincident with (x2,y2)? // Or, is the radius zero? Line to (x1,y1). else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) { this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1); } // Otherwise, draw an arc! else { var x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21; // If the start tangent is not coincident with (x0,y0), line to. if (Math.abs(t01 - 1) > epsilon) { this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01); } this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21); } }, arc: function(x, y, r, a0, a1, ccw) { x = +x, y = +y, r = +r, ccw = !!ccw; var dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x + dx, y0 = y + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0; // Is the radius negative? Error. if (r < 0) throw new Error("negative radius: " + r); // Is this path empty? Move to (x0,y0). if (this._x1 === null) { this._ += "M" + x0 + "," + y0; } // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0). else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) { this._ += "L" + x0 + "," + y0; } // Is this arc empty? We’re done. if (!r) return; // Does the angle go the wrong way? Flip the direction. if (da < 0) da = da % tau + tau; // Is this a complete circle? Draw two arcs to complete the circle. if (da > tauEpsilon) { this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0); } // Is this arc non-empty? Draw an arc! else if (da > epsilon) { this._ += "A" + r + "," + r + ",0," + (+(da >= pi)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1)); } }, rect: function(x, y, w, h) { this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z"; }, toString: function() { return this._; } }; /* harmony default export */ var src_path = (path); // CONCATENATED MODULE: ./node_modules/d3-shape/src/array.js var slice = Array.prototype.slice; // CONCATENATED MODULE: ./node_modules/d3-shape/src/constant.js /* harmony default export */ var constant = (function(x) { return function constant() { return x; }; }); // CONCATENATED MODULE: ./node_modules/d3-shape/src/point.js function point_x(p) { return p[0]; } function point_y(p) { return p[1]; } // CONCATENATED MODULE: ./node_modules/d3-shape/src/pointRadial.js /* harmony default export */ var pointRadial = (function(x, y) { return [(y = +y) * Math.cos(x -= Math.PI / 2), y * Math.sin(x)]; }); // CONCATENATED MODULE: ./node_modules/d3-shape/src/link/index.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return linkHorizontal; }); /* unused harmony export linkVertical */ /* unused harmony export linkRadial */ function linkSource(d) { return d.source; } function linkTarget(d) { return d.target; } function link_link(curve) { var source = linkSource, target = linkTarget, x = point_x, y = point_y, context = null; function link() { var buffer, argv = slice.call(arguments), s = source.apply(this, argv), t = target.apply(this, argv); if (!context) context = buffer = src_path(); curve(context, +x.apply(this, (argv[0] = s, argv)), +y.apply(this, argv), +x.apply(this, (argv[0] = t, argv)), +y.apply(this, argv)); if (buffer) return context = null, buffer + "" || null; } link.source = function(_) { return arguments.length ? (source = _, link) : source; }; link.target = function(_) { return arguments.length ? (target = _, link) : target; }; link.x = function(_) { return arguments.length ? (x = typeof _ === "function" ? _ : constant(+_), link) : x; }; link.y = function(_) { return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), link) : y; }; link.context = function(_) { return arguments.length ? ((context = _ == null ? null : _), link) : context; }; return link; } function curveHorizontal(context, x0, y0, x1, y1) { context.moveTo(x0, y0); context.bezierCurveTo(x0 = (x0 + x1) / 2, y0, x0, y1, x1, y1); } function curveVertical(context, x0, y0, x1, y1) { context.moveTo(x0, y0); context.bezierCurveTo(x0, y0 = (y0 + y1) / 2, x1, y0, x1, y1); } function curveRadial(context, x0, y0, x1, y1) { var p0 = pointRadial(x0, y0), p1 = pointRadial(x0, y0 = (y0 + y1) / 2), p2 = pointRadial(x1, y0), p3 = pointRadial(x1, y1); context.moveTo(p0[0], p0[1]); context.bezierCurveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]); } function linkHorizontal() { return link_link(curveHorizontal); } function linkVertical() { return link_link(curveVertical); } function linkRadial() { var l = link_link(curveRadial); l.angle = l.x, delete l.x; l.radius = l.y, delete l.y; return l; } /***/ }), /***/ "1a94": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function (fn) { if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); return fn; }; /***/ }), /***/ "1aea": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Fx = __webpack_require__("a5c4"); var dragElement = __webpack_require__("4efe"); var setCursor = __webpack_require__("0f37"); var makeDragBox = __webpack_require__("9676").makeDragBox; var DRAGGERSIZE = __webpack_require__("d301").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); }; /***/ }), /***/ "1b06": /***/ (function(module, exports) { module.exports = lerp; /** * Performs a linear interpolation between two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @param {Number} t interpolation amount between the two inputs * @returns {vec3} out */ function lerp(out, a, b, t) { var ax = a[0], ay = a[1], az = a[2] out[0] = ax + t * (b[0] - ax) out[1] = ay + t * (b[1] - ay) out[2] = az + t * (b[2] - az) return out } /***/ }), /***/ "1b6a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var BADNUM = __webpack_require__("e806").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; }; /***/ }), /***/ "1b88": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var loggers = __webpack_require__("ae13"); /** * 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); } module.exports = { getGraphDiv: getGraphDiv, isPlotDiv: isPlotDiv, removeElement: removeElement, addStyleRule: addStyleRule, addRelatedStyleRule: addRelatedStyleRule, deleteRelatedStyleRule: deleteRelatedStyleRule }; /***/ }), /***/ "1bbd": /***/ (function(module, exports, __webpack_require__) { /* * World Calendars * https://github.com/alexcjohnson/world-calendars * * Batch-converted from kbwood/calendars * Many thanks to Keith Wood and all of the contributors to the original project! * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* http://keith-wood.name/calendars.html Thai calendar for jQuery v2.0.2. Written by Keith Wood (wood.keith{at}optusnet.com.au) February 2010. Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ var main = __webpack_require__("0230"); var assign = __webpack_require__("320c"); var gregorianCalendar = main.instance(); /** Implementation of the Thai calendar. See http://en.wikipedia.org/wiki/Thai_calendar. @class ThaiCalendar @param [language=''] {string} The language code (default English) for localisation. */ function ThaiCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } ThaiCalendar.prototype = new main.baseCalendar; assign(ThaiCalendar.prototype, { /** The calendar name. @memberof ThaiCalendar */ name: 'Thai', /** Julian date of start of Thai epoch: 1 January 543 BCE (Gregorian). @memberof ThaiCalendar */ jdEpoch: 1523098.5, /** Difference in years between Thai and Gregorian calendars. @memberof ThaiCalendar */ yearsOffset: 543, /** Days per month in a common year. @memberof ThaiCalendar */ daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], /** true if has a year zero, false if not. @memberof ThaiCalendar */ hasYearZero: false, /** The minimum month number. @memberof ThaiCalendar */ minMonth: 1, /** The first month in the year. @memberof ThaiCalendar */ firstMonth: 1, /** The minimum day number. @memberof ThaiCalendar */ minDay: 1, /** Localisations for the plugin. Entries are objects indexed by the language code ('' being the default US/English). Each object has the following attributes. @memberof ThaiCalendar @property name {string} The calendar name. @property epochs {string[]} The epoch names. @property monthNames {string[]} The long names of the months of the year. @property monthNamesShort {string[]} The short names of the months of the year. @property dayNames {string[]} The long names of the days of the week. @property dayNamesShort {string[]} The short names of the days of the week. @property dayNamesMin {string[]} The minimal names of the days of the week. @property dateFormat {string} The date format for this calendar. See the options on formatDate for details. @property firstDay {number} The number of the first day of the week, starting at 0. @property isRTL {number} true if this localisation reads right-to-left. */ regionalOptions: { // Localisations '': { name: 'Thai', epochs: ['BBE', 'BE'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], digits: null, dateFormat: 'dd/mm/yyyy', firstDay: 0, isRTL: false } }, /** Determine whether this date is in a leap year. @memberof ThaiCalendar @param year {CDate|number} The date to examine or the year to examine. @return {boolean} true if this is a leap year, false if not. @throws Error if an invalid year or a different calendar used. */ leapYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear); var year = this._t2gYear(date.year()); return gregorianCalendar.leapYear(year); }, /** Determine the week of the year for a date - ISO 8601. @memberof ThaiCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {number} The week of the year. @throws Error if an invalid date or a different calendar used. */ weekOfYear: function(year, month, day) { var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear); var year = this._t2gYear(date.year()); return gregorianCalendar.weekOfYear(year, date.month(), date.day()); }, /** Retrieve the number of days in a month. @memberof ThaiCalendar @param year {CDate|number} The date to examine or the year of the month. @param [month] {number} The month. @return {number} The number of days in this month. @throws Error if an invalid month/year or a different calendar used. */ daysInMonth: function(year, month) { var date = this._validate(year, month, this.minDay, main.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, /** Determine whether this date is a week day. @memberof ThaiCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {boolean} true if a week day, false if not. @throws Error if an invalid date or a different calendar used. */ weekDay: function(year, month, day) { return (this.dayOfWeek(year, month, day) || 7) < 6; }, /** Retrieve the Julian date equivalent for this date, i.e. days since January 1, 4713 BCE Greenwich noon. @memberof ThaiCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(year, month, day) { var date = this._validate(year, month, day, main.local.invalidDate); var year = this._t2gYear(date.year()); return gregorianCalendar.toJD(year, date.month(), date.day()); }, /** Create a new date from a Julian date. @memberof ThaiCalendar @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { var date = gregorianCalendar.fromJD(jd); var year = this._g2tYear(date.year()); return this.newDate(year, date.month(), date.day()); }, /** Convert Thai to Gregorian year. @memberof ThaiCalendar @private @param year {number} The Thai year. @return {number} The corresponding Gregorian year. */ _t2gYear: function(year) { return year - this.yearsOffset - (year >= 1 && year <= this.yearsOffset ? 1 : 0); }, /** Convert Gregorian to Thai year. @memberof ThaiCalendar @private @param year {number} The Gregorian year. @return {number} The corresponding Thai year. */ _g2tYear: function(year) { return year + this.yearsOffset + (year >= -this.yearsOffset && year <= -1 ? 1 : 0); } }); // Thai calendar implementation main.calendars.thai = ThaiCalendar; /***/ }), /***/ "1bbe": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var Icons = __webpack_require__("7559"); 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; }; /** * @return {HTMLDivElement} The logo image wrapped in a group */ proto.getLogo = function() { var group = this.createGroup(); var a = document.createElement('a'); a.href = 'https://plot.ly/'; a.target = '_blank'; a.setAttribute('data-title', Lib._(this.graphInfo, 'Produced with Plotly')); 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; /***/ }), /***/ "1be4": /***/ (function(module, exports, __webpack_require__) { var getBuiltIn = __webpack_require__("d066"); module.exports = getBuiltIn('document', 'documentElement'); /***/ }), /***/ "1bea": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * RGB space. * * @module color-space/rgb */ module.exports = { name: 'rgb', min: [0,0,0], max: [255,255,255], channel: ['red', 'green', 'blue'], alias: ['RGB'] }; /***/ }), /***/ "1bef": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var subtypes = __webpack_require__("de81"); var BADNUM = __webpack_require__("e806").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; }; /***/ }), /***/ "1c0b": /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') { throw TypeError(String(it) + ' is not a function'); } return it; }; /***/ }), /***/ "1c0b8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var attrs = __webpack_require__("8f38"); var oppAxisAttrs = __webpack_require__("5844"); var helpers = __webpack_require__("4c66"); module.exports = { moduleType: 'component', name: 'rangeslider', schema: { subplots: { xaxis: { rangeslider: Lib.extendFlat({}, attrs, { yaxis: oppAxisAttrs }) } } }, layoutAttributes: __webpack_require__("8f38"), handleDefaults: __webpack_require__("6b10"), calcAutorange: __webpack_require__("4cd2"), draw: __webpack_require__("8b1d"), isVisible: helpers.isVisible, makeData: helpers.makeData, autoMarginOpts: helpers.autoMarginOpts }; /***/ }), /***/ "1c1a": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isValue = __webpack_require__("62c4") , setPrototypeOf = __webpack_require__("e0f6") , object = __webpack_require__("68e6") , ensureValue = __webpack_require__("96ae") , randomUniq = __webpack_require__("6599") , d = __webpack_require__("f508") , getIterator = __webpack_require__("8a50") , forOf = __webpack_require__("c351") , toStringTagSymbol = __webpack_require__("1c4a").toStringTag , isNative = __webpack_require__("7d72") , isArray = Array.isArray, defineProperty = Object.defineProperty , objHasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf , WeakMapPoly; module.exports = WeakMapPoly = function (/* Iterable*/) { var iterable = arguments[0], self; if (!(this instanceof WeakMapPoly)) throw new TypeError("Constructor requires 'new'"); self = isNative && setPrototypeOf && (WeakMap !== WeakMapPoly) ? setPrototypeOf(new WeakMap(), getPrototypeOf(this)) : this; if (isValue(iterable)) { if (!isArray(iterable)) iterable = getIterator(iterable); } defineProperty(self, "__weakMapData__", d("c", "$weakMap$" + randomUniq())); if (!iterable) return self; forOf(iterable, function (val) { ensureValue(val); self.set(val[0], val[1]); }); return self; }; if (isNative) { if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap); WeakMapPoly.prototype = Object.create(WeakMap.prototype, { constructor: d(WeakMapPoly) }); } Object.defineProperties(WeakMapPoly.prototype, { delete: d(function (key) { if (objHasOwnProperty.call(object(key), this.__weakMapData__)) { delete key[this.__weakMapData__]; return true; } return false; }), get: d(function (key) { if (!objHasOwnProperty.call(object(key), this.__weakMapData__)) return undefined; return key[this.__weakMapData__]; }), has: d(function (key) { return objHasOwnProperty.call(object(key), this.__weakMapData__); }), set: d(function (key, value) { defineProperty(object(key), this.__weakMapData__, d("c", value)); return this; }), toString: d(function () { return "[object WeakMap]"; }) }); defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d("c", "WeakMap")); /***/ }), /***/ "1c1c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Color = __webpack_require__("d115"); var Registry = __webpack_require__("371e"); var handleXYDefaults = __webpack_require__("076f"); var handleStyleDefaults = __webpack_require__("9103"); var getAxisGroup = __webpack_require__("3c1c").getAxisGroup; var attributes = __webpack_require__("fb5a"); 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; } 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 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; } } function crossTraceDefaults(fullData, fullLayout) { var traceIn, traceOut; function coerce(attr) { return Lib.coerce(traceOut._input, traceOut, attributes, attr); } if(fullLayout.barmode === 'group') { for(var i = 0; i < fullData.length; i++) { traceOut = fullData[i]; if(traceOut.type === 'bar') { traceIn = traceOut._input; handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce); } } } } 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, handleGroupingDefaults: handleGroupingDefaults, handleText: handleText }; /***/ }), /***/ "1c4a": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__("ba61")() ? __webpack_require__("7c4a").Symbol : __webpack_require__("94ee"); /***/ }), /***/ "1c4d": /***/ (function(module, exports, __webpack_require__) { "use strict"; var sizes = __webpack_require__("fde6") module.exports = { isSize: function isSize(value) { return /^[\d\.]/.test(value) || value.indexOf('/') !== -1 || sizes.indexOf(value) !== -1 } } /***/ }), /***/ "1c82": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var extendFlat = __webpack_require__("9092").extendFlat; var extendDeep = __webpack_require__("9092").extendDeep; var overrideAll = __webpack_require__("cb34").overrideAll; var fontAttrs = __webpack_require__("9845"); var colorAttrs = __webpack_require__("dfb3"); var domainAttrs = __webpack_require__("81f0").attributes; var axesAttrs = __webpack_require__("d798"); var templatedArray = __webpack_require__("a651").templatedArray; var delta = __webpack_require__("b8ce"); var FORMAT_LINK = __webpack_require__("78df").FORMAT_LINK; 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', }, 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', }, 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, { }), 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.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, showticklabels: axesAttrs.showticklabels, 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, 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) } }; /***/ }), /***/ "1cfc": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("6386"); /***/ }), /***/ "1d19": /***/ (function(module, exports, __webpack_require__) { "use strict"; /* @module to-float32 */ module.exports = float32 module.exports.float32 = module.exports.float = float32 module.exports.fract32 = module.exports.fract = fract32 var narr = new Float32Array(1) // return fractional part of float32 array function fract32 (arr) { if (arr.length) { var fract = float32(arr) for (var i = 0, l = fract.length; i < l; i++) { fract[i] = arr[i] - fract[i] } return fract } // number return float32(arr - float32(arr)) } // make sure data is float32 array function float32 (arr) { if (arr.length) { if (arr instanceof Float32Array) return arr var float = new Float32Array(arr) float.set(arr) return float } // number narr[0] = arr return narr[0] } /***/ }), /***/ "1d4c": /***/ (function(module, exports, __webpack_require__) { "use strict"; var compile = __webpack_require__("c535") var CACHE = {} function sort(array) { var order = array.order var dtype = array.dtype var typeSig = [order, dtype ] var typeName = typeSig.join(":") var compiled = CACHE[typeName] if(!compiled) { CACHE[typeName] = compiled = compile(order, dtype) } compiled(array) return array } module.exports = sort /***/ }), /***/ "1d5b": /***/ (function(module, exports, __webpack_require__) { "use strict"; var ndarray = __webpack_require__("b5bb") var ops = __webpack_require__("62d6") var pool = __webpack_require__("cea5") module.exports = createTexture2D var linearTypes = null var filterTypes = null var wrapTypes = null function lazyInitLinearTypes(gl) { linearTypes = [ gl.LINEAR, gl.NEAREST_MIPMAP_LINEAR, gl.LINEAR_MIPMAP_NEAREST, gl.LINEAR_MIPMAP_NEAREST ] filterTypes = [ gl.NEAREST, gl.LINEAR, gl.NEAREST_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR, gl.LINEAR_MIPMAP_NEAREST, gl.LINEAR_MIPMAP_LINEAR ] wrapTypes = [ gl.REPEAT, gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT ] } function acceptTextureDOM (obj) { return ( ('undefined' != typeof HTMLCanvasElement && obj instanceof HTMLCanvasElement) || ('undefined' != typeof HTMLImageElement && obj instanceof HTMLImageElement) || ('undefined' != typeof HTMLVideoElement && obj instanceof HTMLVideoElement) || ('undefined' != typeof ImageData && obj instanceof ImageData)) } var convertFloatToUint8 = function(out, inp) { ops.muls(out, inp, 255.0) } function reshapeTexture(tex, w, h) { var gl = tex.gl var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) if(w < 0 || w > maxSize || h < 0 || h > maxSize) { throw new Error('gl-texture2d: Invalid texture size') } tex._shape = [w, h] tex.bind() gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null) tex._mipLevels = [0] return tex } function Texture2D(gl, handle, width, height, format, type) { this.gl = gl this.handle = handle this.format = format this.type = type this._shape = [width, height] this._mipLevels = [0] this._magFilter = gl.NEAREST this._minFilter = gl.NEAREST this._wrapS = gl.CLAMP_TO_EDGE this._wrapT = gl.CLAMP_TO_EDGE this._anisoSamples = 1 var parent = this var wrapVector = [this._wrapS, this._wrapT] Object.defineProperties(wrapVector, [ { get: function() { return parent._wrapS }, set: function(v) { return parent.wrapS = v } }, { get: function() { return parent._wrapT }, set: function(v) { return parent.wrapT = v } } ]) this._wrapVector = wrapVector var shapeVector = [this._shape[0], this._shape[1]] Object.defineProperties(shapeVector, [ { get: function() { return parent._shape[0] }, set: function(v) { return parent.width = v } }, { get: function() { return parent._shape[1] }, set: function(v) { return parent.height = v } } ]) this._shapeVector = shapeVector } var proto = Texture2D.prototype Object.defineProperties(proto, { minFilter: { get: function() { return this._minFilter }, set: function(v) { this.bind() var gl = this.gl if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { if(!gl.getExtension('OES_texture_float_linear')) { v = gl.NEAREST } } if(filterTypes.indexOf(v) < 0) { throw new Error('gl-texture2d: Unknown filter mode ' + v) } gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v) return this._minFilter = v } }, magFilter: { get: function() { return this._magFilter }, set: function(v) { this.bind() var gl = this.gl if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { if(!gl.getExtension('OES_texture_float_linear')) { v = gl.NEAREST } } if(filterTypes.indexOf(v) < 0) { throw new Error('gl-texture2d: Unknown filter mode ' + v) } gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v) return this._magFilter = v } }, mipSamples: { get: function() { return this._anisoSamples }, set: function(i) { var psamples = this._anisoSamples this._anisoSamples = Math.max(i, 1)|0 if(psamples !== this._anisoSamples) { var ext = this.gl.getExtension('EXT_texture_filter_anisotropic') if(ext) { this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples) } } return this._anisoSamples } }, wrapS: { get: function() { return this._wrapS }, set: function(v) { this.bind() if(wrapTypes.indexOf(v) < 0) { throw new Error('gl-texture2d: Unknown wrap mode ' + v) } this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v) return this._wrapS = v } }, wrapT: { get: function() { return this._wrapT }, set: function(v) { this.bind() if(wrapTypes.indexOf(v) < 0) { throw new Error('gl-texture2d: Unknown wrap mode ' + v) } this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v) return this._wrapT = v } }, wrap: { get: function() { return this._wrapVector }, set: function(v) { if(!Array.isArray(v)) { v = [v,v] } if(v.length !== 2) { throw new Error('gl-texture2d: Must specify wrap mode for rows and columns') } for(var i=0; i<2; ++i) { if(wrapTypes.indexOf(v[i]) < 0) { throw new Error('gl-texture2d: Unknown wrap mode ' + v) } } this._wrapS = v[0] this._wrapT = v[1] var gl = this.gl this.bind() gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT) return v } }, shape: { get: function() { return this._shapeVector }, set: function(x) { if(!Array.isArray(x)) { x = [x|0,x|0] } else { if(x.length !== 2) { throw new Error('gl-texture2d: Invalid texture shape') } } reshapeTexture(this, x[0]|0, x[1]|0) return [x[0]|0, x[1]|0] } }, width: { get: function() { return this._shape[0] }, set: function(w) { w = w|0 reshapeTexture(this, w, this._shape[1]) return w } }, height: { get: function() { return this._shape[1] }, set: function(h) { h = h|0 reshapeTexture(this, this._shape[0], h) return h } } }) proto.bind = function(unit) { var gl = this.gl if(unit !== undefined) { gl.activeTexture(gl.TEXTURE0 + (unit|0)) } gl.bindTexture(gl.TEXTURE_2D, this.handle) if(unit !== undefined) { return (unit|0) } return gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0 } proto.dispose = function() { this.gl.deleteTexture(this.handle) } proto.generateMipmap = function() { this.bind() this.gl.generateMipmap(this.gl.TEXTURE_2D) //Update mip levels var l = Math.min(this._shape[0], this._shape[1]) for(var i=0; l>0; ++i, l>>>=1) { if(this._mipLevels.indexOf(i) < 0) { this._mipLevels.push(i) } } } proto.setPixels = function(data, x_off, y_off, mip_level) { var gl = this.gl this.bind() if(Array.isArray(x_off)) { mip_level = y_off y_off = x_off[1]|0 x_off = x_off[0]|0 } else { x_off = x_off || 0 y_off = y_off || 0 } mip_level = mip_level || 0 var directData = acceptTextureDOM(data) ? data : data.raw if(directData) { var needsMip = this._mipLevels.indexOf(mip_level) < 0 if(needsMip) { gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, directData) this._mipLevels.push(mip_level) } else { gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, directData) } } else if(data.shape && data.stride && data.data) { if(data.shape.length < 2 || x_off + data.shape[1] > this._shape[1]>>>mip_level || y_off + data.shape[0] > this._shape[0]>>>mip_level || x_off < 0 || y_off < 0) { throw new Error('gl-texture2d: Texture dimensions are out of bounds') } texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data) } else { throw new Error('gl-texture2d: Unsupported data type') } } function isPacked(shape, stride) { if(shape.length === 3) { return (stride[2] === 1) && (stride[1] === shape[0]*shape[2]) && (stride[0] === shape[2]) } return (stride[0] === 1) && (stride[1] === shape[0]) } function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) { var dtype = array.dtype var shape = array.shape.slice() if(shape.length < 2 || shape.length > 3) { throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d') } var type = 0, format = 0 var packed = isPacked(shape, array.stride.slice()) if(dtype === 'float32') { type = gl.FLOAT } else if(dtype === 'float64') { type = gl.FLOAT packed = false dtype = 'float32' } else if(dtype === 'uint8') { type = gl.UNSIGNED_BYTE } else { type = gl.UNSIGNED_BYTE packed = false dtype = 'uint8' } var channels = 1 if(shape.length === 2) { format = gl.LUMINANCE shape = [shape[0], shape[1], 1] array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) } else if(shape.length === 3) { if(shape[2] === 1) { format = gl.ALPHA } else if(shape[2] === 2) { format = gl.LUMINANCE_ALPHA } else if(shape[2] === 3) { format = gl.RGB } else if(shape[2] === 4) { format = gl.RGBA } else { throw new Error('gl-texture2d: Invalid shape for pixel coords') } channels = shape[2] } else { throw new Error('gl-texture2d: Invalid shape for texture') } //For 1-channel textures allow conversion between formats if((format === gl.LUMINANCE || format === gl.ALPHA) && (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) { format = cformat } if(format !== cformat) { throw new Error('gl-texture2d: Incompatible texture format for setPixels') } var size = array.size var needsMip = mipLevels.indexOf(mip_level) < 0 if(needsMip) { mipLevels.push(mip_level) } if(type === ctype && packed) { //Array data types are compatible, can directly copy into texture if(array.offset === 0 && array.data.length === size) { if(needsMip) { gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data) } else { gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data) } } else { if(needsMip) { gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size)) } else { gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size)) } } } else { //Need to do type conversion to pack data into buffer var pack_buffer if(ctype === gl.FLOAT) { pack_buffer = pool.mallocFloat32(size) } else { pack_buffer = pool.mallocUint8(size) } var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { convertFloatToUint8(pack_view, array) } else { ops.assign(pack_view, array) } if(needsMip) { gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size)) } else { gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size)) } if(ctype === gl.FLOAT) { pool.freeFloat32(pack_buffer) } else { pool.freeUint8(pack_buffer) } } } function initTexture(gl) { var tex = gl.createTexture() gl.bindTexture(gl.TEXTURE_2D, tex) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) return tex } function createTextureShape(gl, width, height, format, type) { var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) if(width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) { throw new Error('gl-texture2d: Invalid texture shape') } if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { throw new Error('gl-texture2d: Floating point textures not supported on this platform') } var tex = initTexture(gl) gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null) return new Texture2D(gl, tex, width, height, format, type) } function createTextureDOM(gl, directData, width, height, format, type) { var tex = initTexture(gl) gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, directData) return new Texture2D(gl, tex, width, height, format, type) } //Creates a texture from an ndarray function createTextureArray(gl, array) { var dtype = array.dtype var shape = array.shape.slice() var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) { throw new Error('gl-texture2d: Invalid texture size') } var packed = isPacked(shape, array.stride.slice()) var type = 0 if(dtype === 'float32') { type = gl.FLOAT } else if(dtype === 'float64') { type = gl.FLOAT packed = false dtype = 'float32' } else if(dtype === 'uint8') { type = gl.UNSIGNED_BYTE } else { type = gl.UNSIGNED_BYTE packed = false dtype = 'uint8' } var format = 0 if(shape.length === 2) { format = gl.LUMINANCE shape = [shape[0], shape[1], 1] array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) } else if(shape.length === 3) { if(shape[2] === 1) { format = gl.ALPHA } else if(shape[2] === 2) { format = gl.LUMINANCE_ALPHA } else if(shape[2] === 3) { format = gl.RGB } else if(shape[2] === 4) { format = gl.RGBA } else { throw new Error('gl-texture2d: Invalid shape for pixel coords') } } else { throw new Error('gl-texture2d: Invalid shape for texture') } if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { type = gl.UNSIGNED_BYTE packed = false } var buffer, buf_store var size = array.size if(!packed) { var stride = [shape[2], shape[2]*shape[0], 1] buf_store = pool.malloc(size, dtype) var buf_array = ndarray(buf_store, shape, stride, 0) if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { convertFloatToUint8(buf_array, array) } else { ops.assign(buf_array, array) } buffer = buf_store.subarray(0, size) } else if (array.offset === 0 && array.data.length === size) { buffer = array.data } else { buffer = array.data.subarray(array.offset, array.offset + size) } var tex = initTexture(gl) gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) if(!packed) { pool.free(buf_store) } return new Texture2D(gl, tex, shape[0], shape[1], format, type) } function createTexture2D(gl) { if(arguments.length <= 1) { throw new Error('gl-texture2d: Missing arguments for texture2d constructor') } if(!linearTypes) { lazyInitLinearTypes(gl) } if(typeof arguments[1] === 'number') { return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE) } if(Array.isArray(arguments[1])) { return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) } if(typeof arguments[1] === 'object') { var obj = arguments[1] var directData = acceptTextureDOM(obj) ? obj : obj.raw if (directData) { return createTextureDOM(gl, directData, obj.width|0, obj.height|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) } else if(obj.shape && obj.data && obj.stride) { return createTextureArray(gl, obj) } } throw new Error('gl-texture2d: Invalid arguments for texture2d constructor') } /***/ }), /***/ "1d80": /***/ (function(module, exports) { // `RequireObjectCoercible` abstract operation // https://tc39.github.io/ecma262/#sec-requireobjectcoercible module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /***/ "1d9e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var Color = __webpack_require__("d115"); var Colorscale = __webpack_require__("c258"); var BADNUM = __webpack_require__("e806").BADNUM; var makeBlank = __webpack_require__("2169").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; }; /***/ }), /***/ "1db7": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var c = __webpack_require__("f7a4"); var d3 = __webpack_require__("6e58"); var keyFun = __webpack_require__("0a3e").keyFun; var repeat = __webpack_require__("0a3e").repeat; var sortAsc = __webpack_require__("fc26").sorterAsc; 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) { var background = axisBrush.selectAll('.background').data(repeat); background.enter() .append('rect') .classed('background', true) .call(barHorizontalSetup) .call(backgroundBarHorizontalSetup) .style('pointer-events', 'auto') // parent pointer events are disabled; we must have it to register events .attr('transform', 'translate(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', c.bar.strokeColor) .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) { var axisBrush = axisOverlays.selectAll('.' + c.cn.axisBrush) .data(repeat, keyFun); axisBrush.enter() .append('g') .classed(c.cn.axisBrush, true); renderAxisBrush(axisBrush); } 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); } 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 }; /***/ }), /***/ "1db7e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var hasColorscale = __webpack_require__("215c").hasColorscale; var extractOpts = __webpack_require__("215c").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'}); } }; /***/ }), /***/ "1ddb": /***/ (function(module, exports, __webpack_require__) { "use strict"; var bindAttribs = __webpack_require__("8c75") function VAOEmulated(gl) { this.gl = gl this._elements = null this._attributes = null this._elementsType = gl.UNSIGNED_SHORT } VAOEmulated.prototype.bind = function() { bindAttribs(this.gl, this._elements, this._attributes) } VAOEmulated.prototype.update = function(attributes, elements, elementsType) { this._elements = elements this._attributes = attributes this._elementsType = elementsType || this.gl.UNSIGNED_SHORT } VAOEmulated.prototype.dispose = function() { } VAOEmulated.prototype.unbind = function() { } VAOEmulated.prototype.draw = function(mode, count, offset) { offset = offset || 0 var gl = this.gl if(this._elements) { gl.drawElements(mode, count, this._elementsType, offset) } else { gl.drawArrays(mode, offset, count) } } function createVAOEmulated(gl) { return new VAOEmulated(gl) } module.exports = createVAOEmulated /***/ }), /***/ "1dde": /***/ (function(module, exports, __webpack_require__) { var fails = __webpack_require__("d039"); var wellKnownSymbol = __webpack_require__("b622"); var V8_VERSION = __webpack_require__("2d00"); var SPECIES = wellKnownSymbol('species'); module.exports = function (METHOD_NAME) { // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/677 return V8_VERSION >= 51 || !fails(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; /***/ }), /***/ "1e03": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { moduleType: 'locale', name: 'en-US', dictionary: { 'Click to enter Colorscale title': 'Click to enter Colorscale title' }, format: { date: '%m/%d/%Y' } }; /***/ }), /***/ "1e0a": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function (value) { try { return value.toString(); } catch (error) { try { return String(value); } catch (error2) { return null; } } }; /***/ }), /***/ "1ea6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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' } }; /***/ }), /***/ "1ebf": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var scatterAttrs = __webpack_require__("107c"); var barAttrs = __webpack_require__("fb5a"); var colorAttrs = __webpack_require__("dfb3"); var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var extendFlat = __webpack_require__("9092").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', }, 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', }, 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'}), 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: scatterAttrs.fillcolor, whiskerwidth: { valType: 'number', min: 0, max: 1, dflt: 0.5, 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', } }; /***/ }), /***/ "1f25": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = convexHull1d function convexHull1d(points) { var lo = 0 var hi = 0 for(var i=1; i points[hi][0]) { hi = i } } if(lo < hi) { return [[lo], [hi]] } else if(lo > hi) { return [[hi], [lo]] } else { return [[lo]] } } /***/ }), /***/ "1fac": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = gradient var dup = __webpack_require__("84af") var cwiseCompiler = __webpack_require__("40ce") var TEMPLATE_CACHE = {} var GRADIENT_CACHE = {} var EmptyProc = { body: "", args: [], thisVars: [], localVars: [] } var centralDiff = cwiseCompiler({ args: [ 'array', 'array', 'array' ], pre: EmptyProc, post: EmptyProc, body: { args: [ { name: 'out', lvalue: true, rvalue: false, count: 1 }, { name: 'left', lvalue: false, rvalue: true, count: 1 }, { name: 'right', lvalue: false, rvalue: true, count: 1 }], body: "out=0.5*(left-right)", thisVars: [], localVars: [] }, funcName: 'cdiff' }) var zeroOut = cwiseCompiler({ args: [ 'array' ], pre: EmptyProc, post: EmptyProc, body: { args: [ { name: 'out', lvalue: true, rvalue: false, count: 1 }], body: "out=0", thisVars: [], localVars: [] }, funcName: 'zero' }) function generateTemplate(d) { if(d in TEMPLATE_CACHE) { return TEMPLATE_CACHE[d] } var code = [] for(var i=0; i= 0) { pickStr.push('0') } else if(facet.indexOf(-(i+1)) >= 0) { pickStr.push('s['+i+']-1') } else { pickStr.push('-1') loStr.push('1') hiStr.push('s['+i+']-2') } } var boundStr = '.lo(' + loStr.join() + ').hi(' + hiStr.join() + ')' if(loStr.length === 0) { boundStr = '' } if(cod > 0) { code.push('if(1') for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { continue } code.push('&&s[', i, ']>2') } code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr) for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { continue } code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr) } code.push(');') } for(var i=0; i1){dst.set(', pickStr.join(), ',', bnd, ',0.5*(src.get(', cPickStr.join(), ')-src.get(', dPickStr.join(), ')))}else{dst.set(', pickStr.join(), ',', bnd, ',0)};') } else { code.push('if(s[', bnd, ']>1){diff(', outStr, ',src.pick(', cPickStr.join(), ')', boundStr, ',src.pick(', dPickStr.join(), ')', boundStr, ');}else{zero(', outStr, ');};') } break case 'mirror': if(cod === 0) { code.push('dst.set(', pickStr.join(), ',', bnd, ',0);') } else { code.push('zero(', outStr, ');') } break case 'wrap': var aPickStr = pickStr.slice() var bPickStr = pickStr.slice() if(facet[i] < 0) { aPickStr[bnd] = 's[' + bnd + ']-2' bPickStr[bnd] = '0' } else { aPickStr[bnd] = 's[' + bnd + ']-1' bPickStr[bnd] = '1' } if(cod === 0) { code.push('if(s[', bnd, ']>2){dst.set(', pickStr.join(), ',', bnd, ',0.5*(src.get(', aPickStr.join(), ')-src.get(', bPickStr.join(), ')))}else{dst.set(', pickStr.join(), ',', bnd, ',0)};') } else { code.push('if(s[', bnd, ']>2){diff(', outStr, ',src.pick(', aPickStr.join(), ')', boundStr, ',src.pick(', bPickStr.join(), ')', boundStr, ');}else{zero(', outStr, ');};') } break default: throw new Error('ndarray-gradient: Invalid boundary condition') } } if(cod > 0) { code.push('};') } } //Enumerate ridges, facets, etc. of hypercube for(var i=0; i<(1< 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk( uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) )) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } /***/ }), /***/ "2015": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var Template = __webpack_require__("a651"); var attributes = __webpack_require__("8c2d"); 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); } }; /***/ }), /***/ "2031": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__("14ab")() ? Object.assign : __webpack_require__("f60e"); /***/ }), /***/ "20314": /***/ (function(module, exports, __webpack_require__) { "use strict"; function iota(n) { var result = new Array(n) for(var i=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 }; /***/ }), /***/ "2160": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isValue = __webpack_require__("62c4"); var map = { function: true, object: true }; module.exports = function (value) { return (isValue(value) && map[typeof value]) || false; }; /***/ }), /***/ "2169": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var BADNUM = __webpack_require__("e806").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: [] }; }; /***/ }), /***/ "2195": /***/ (function(module, exports, __webpack_require__) { "use strict"; var num2bn = __webpack_require__("def6") var sign = __webpack_require__("0fba") 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 ] } /***/ }), /***/ "21d9": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = boundary var bnd = __webpack_require__("566e") var reduce = __webpack_require__("941b") function boundary(cells) { return reduce(bnd(cells)) } /***/ }), /***/ "21dd": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("f657"); /***/ }), /***/ "223c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var Drawing = __webpack_require__("83d1"); var svgTextUtils = __webpack_require__("0379"); var partition = __webpack_require__("c8b8"); var styleOne = __webpack_require__("da8c").styleOne; var constants = __webpack_require__("23cc"); var helpers = __webpack_require__("fb56"); var attachFxHandlers = __webpack_require__("6962"); 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 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) { 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', '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, { 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)); } }); }; /***/ }), /***/ "2244": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var layoutAttributes = __webpack_require__("91ce"); 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'); } }; /***/ }), /***/ "2292": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function () { var weakMap, obj; if (typeof WeakMap !== "function") return false; try { // WebKit doesn't support arguments and crashes weakMap = new WeakMap([[obj = {}, "one"], [{}, "two"], [{}, "three"]]); } catch (e) { return false; } if (String(weakMap) !== "[object WeakMap]") return false; if (typeof weakMap.set !== "function") return false; if (weakMap.set({}, 1) !== weakMap) return false; if (typeof weakMap.delete !== "function") return false; if (typeof weakMap.has !== "function") return false; if (weakMap.get(obj) !== "one") return false; return true; }; /***/ }), /***/ "22926": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var handleArrayContainerDefaults = __webpack_require__("e5ac"); var attributes = __webpack_require__("26e4"); var subTypes = __webpack_require__("de81"); var handleMarkerDefaults = __webpack_require__("5047"); var mergeLength = __webpack_require__("8cdc"); var isOpenSymbol = __webpack_require__("50da").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'); handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce); 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'; } } /***/ }), /***/ "22b4": /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.shader = getShaderReference exports.program = createProgram var GLError = __webpack_require__("a3fd") var formatCompilerError = __webpack_require__("07db"); var weakMap = typeof WeakMap === 'undefined' ? __webpack_require__("fcc5") : WeakMap var CACHE = new weakMap() var SHADER_COUNTER = 0 function ShaderReference(id, src, type, shader, programs, count, cache) { this.id = id this.src = src this.type = type this.shader = shader this.count = count this.programs = [] this.cache = cache } ShaderReference.prototype.dispose = function() { if(--this.count === 0) { var cache = this.cache var gl = cache.gl //Remove program references var programs = this.programs for(var i=0, n=programs.length; i 1.0){ return 0 } else { return Math.acos(cosine) } } /***/ }), /***/ "2335": /***/ (function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /***/ "2357": /***/ (function(module, exports, __webpack_require__) { "use strict"; var ch = __webpack_require__("0000") var uniq = __webpack_require__("175e") 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 minSensoryWidth ? sensoryWidth / 2 : minSensoryWidth; g.append('circle') .attr({ 'data-line-point': 'start-point', 'cx': xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x0 : x2p(shapeOptions.x0), 'cy': yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y0 : y2p(shapeOptions.y0), '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), 'cy': yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y1 : y2p(shapeOptions.y1), 'r': circleRadius }) .style(circleStyle) .classed('cursor-grab', true); return g; } function updateDragMode(evt) { 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) { // 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; } function endDrag() { 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() { 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); } 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 newN = (~dragMode.indexOf('n')) ? n0 + dy : n0; var newS = (~dragMode.indexOf('s')) ? s0 + dy : s0; var newW = (~dragMode.indexOf('w')) ? w0 + dx : w0; var newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; // Do things in opposing direction for y-axis. // Hint: for data-sized shapes the reversal of axis direction is done in p2y. if(~dragMode.indexOf('n') && yPixelSized) newN = n0 - dy; if(~dragMode.indexOf('s') && yPixelSized) 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); } 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 getPathString(gd, options) { var type = options.type; 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 x0, x1, y0, y1; if(xa) { x2r = helpers.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) { y2r = helpers.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 = helpers.decodeDate(x2p); if(ya && ya.type === 'date') y2p = helpers.decodeDate(y2p); return convertPath(options, x2p, y2p); } if(options.xsizemode === 'pixel') { var xAnchorPos = x2p(options.xanchor); x0 = xAnchorPos + options.x0; x1 = xAnchorPos + options.x1; } else { x0 = x2p(options.x0); x1 = x2p(options.x1); } if(options.ysizemode === 'pixel') { var yAnchorPos = y2p(options.yanchor); y0 = yAnchorPos - options.y0; y1 = yAnchorPos - options.y1; } else { y0 = y2p(options.y0); y1 = y2p(options.y1); } 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 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; }); } /***/ }), /***/ "2381": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable new-cap */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var Color = __webpack_require__("d115"); var micropolar = __webpack_require__("3a99"); var UndoManager = __webpack_require__("12c1"); var extendDeepAll = Lib.extendDeepAll; var manager = module.exports = {}; manager.framework = function(_gd) { var config, previousConfigClone, plot, convertedInput, container; var undoManager = new UndoManager(); function exports(_inputConfig, _container) { if(_container) container = _container; d3.select(d3.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove(); config = (!config) ? _inputConfig : extendDeepAll(config, _inputConfig); if(!plot) plot = micropolar.Axis(); convertedInput = micropolar.adapter.plotly().convert(config); plot.config(convertedInput).render(container); _gd.data = config.data; _gd.layout = config.layout; manager.fillLayout(_gd); return config; } exports.isPolar = true; exports.svg = function() { return plot.svg(); }; exports.getConfig = function() { return config; }; exports.getLiveConfig = function() { return micropolar.adapter.plotly().convert(plot.getLiveConfig(), true); }; exports.getLiveScales = function() { return {t: plot.angularScale(), r: plot.radialScale()}; }; exports.setUndoPoint = function() { var that = this; var configClone = micropolar.util.cloneJson(config); (function(_configClone, _previousConfigClone) { undoManager.add({ undo: function() { if(_previousConfigClone) that(_previousConfigClone); }, redo: function() { that(_configClone); } }); })(configClone, previousConfigClone); previousConfigClone = micropolar.util.cloneJson(configClone); }; exports.undo = function() { undoManager.undo(); }; exports.redo = function() { undoManager.redo(); }; return exports; }; manager.fillLayout = function(_gd) { var container = d3.select(_gd).selectAll('.plot-container'); var paperDiv = container.selectAll('.svg-container'); var paper = _gd.framework && _gd.framework.svg && _gd.framework.svg(); var dflts = { width: 800, height: 600, paper_bgcolor: Color.background, _container: container, _paperdiv: paperDiv, _paper: paper }; _gd._fullLayout = extendDeepAll(dflts, _gd.layout); }; /***/ }), /***/ "23cb": /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__("a691"); var max = Math.max; var min = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). module.exports = function (index, length) { var integer = toInteger(index); return integer < 0 ? max(integer + length, 0) : min(integer, length); }; /***/ }), /***/ "23cc": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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 }; /***/ }), /***/ "23e7": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("da84"); var getOwnPropertyDescriptor = __webpack_require__("06cf").f; var createNonEnumerableProperty = __webpack_require__("9112"); var redefine = __webpack_require__("6eeb"); var setGlobal = __webpack_require__("ce4e"); var copyConstructorProperties = __webpack_require__("e893"); var isForced = __webpack_require__("94ca"); /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ module.exports = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global; } else if (STATIC) { target = global[TARGET] || setGlobal(TARGET, {}); } else { target = (global[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } }; /***/ }), /***/ "241c": /***/ (function(module, exports, __webpack_require__) { var internalObjectKeys = __webpack_require__("ca84"); var enumBugKeys = __webpack_require__("7839"); var hiddenKeys = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return internalObjectKeys(O, hiddenKeys); }; /***/ }), /***/ "2441": /***/ (function(module, exports, __webpack_require__) { /* * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc * @license MIT * @preserve Project Home: https://github.com/voidqk/polybooljs */ var BuildLog = __webpack_require__("a6dc"); var Epsilon = __webpack_require__("f8a5"); var Intersecter = __webpack_require__("9935"); var SegmentChainer = __webpack_require__("a626"); var SegmentSelector = __webpack_require__("b924"); var GeoJSON = __webpack_require__("34cc"); var buildLog = false; var epsilon = Epsilon(); var PolyBool; PolyBool = { // getter/setter for buildLog buildLog: function(bl){ if (bl === true) buildLog = BuildLog(); else if (bl === false) buildLog = false; return buildLog === false ? false : buildLog.list; }, // getter/setter for epsilon epsilon: function(v){ return epsilon.epsilon(v); }, // core API segments: function(poly){ var i = Intersecter(true, epsilon, buildLog); poly.regions.forEach(i.addRegion); return { segments: i.calculate(poly.inverted), inverted: poly.inverted }; }, combine: function(segments1, segments2){ var i3 = Intersecter(false, epsilon, buildLog); return { combined: i3.calculate( segments1.segments, segments1.inverted, segments2.segments, segments2.inverted ), inverted1: segments1.inverted, inverted2: segments2.inverted }; }, selectUnion: function(combined){ return { segments: SegmentSelector.union(combined.combined, buildLog), inverted: combined.inverted1 || combined.inverted2 } }, selectIntersect: function(combined){ return { segments: SegmentSelector.intersect(combined.combined, buildLog), inverted: combined.inverted1 && combined.inverted2 } }, selectDifference: function(combined){ return { segments: SegmentSelector.difference(combined.combined, buildLog), inverted: combined.inverted1 && !combined.inverted2 } }, selectDifferenceRev: function(combined){ return { segments: SegmentSelector.differenceRev(combined.combined, buildLog), inverted: !combined.inverted1 && combined.inverted2 } }, selectXor: function(combined){ return { segments: SegmentSelector.xor(combined.combined, buildLog), inverted: combined.inverted1 !== combined.inverted2 } }, polygon: function(segments){ return { regions: SegmentChainer(segments.segments, epsilon, buildLog), inverted: segments.inverted }; }, // GeoJSON converters polygonFromGeoJSON: function(geojson){ return GeoJSON.toPolygon(PolyBool, geojson); }, polygonToGeoJSON: function(poly){ return GeoJSON.fromPolygon(PolyBool, epsilon, poly); }, // helper functions for common operations union: function(poly1, poly2){ return operate(poly1, poly2, PolyBool.selectUnion); }, intersect: function(poly1, poly2){ return operate(poly1, poly2, PolyBool.selectIntersect); }, difference: function(poly1, poly2){ return operate(poly1, poly2, PolyBool.selectDifference); }, differenceRev: function(poly1, poly2){ return operate(poly1, poly2, PolyBool.selectDifferenceRev); }, xor: function(poly1, poly2){ return operate(poly1, poly2, PolyBool.selectXor); } }; function operate(poly1, poly2, selector){ var seg1 = PolyBool.segments(poly1); var seg2 = PolyBool.segments(poly2); var comb = PolyBool.combine(seg1, seg2); var seg3 = selector(comb); return PolyBool.polygon(seg3); } if (typeof window === 'object') window.PolyBool = PolyBool; module.exports = PolyBool; /***/ }), /***/ "2456": /***/ (function(module, exports) { module.exports = squaredLength; /** * Calculates the squared length of a vec3 * * @param {vec3} a vector to calculate squared length of * @returns {Number} squared length of a */ function squaredLength(a) { var x = a[0], y = a[1], z = a[2] return x*x + y*y + z*z } /***/ }), /***/ "24ad": /***/ (function(module, exports, __webpack_require__) { "use strict"; "use restrict"; var bits = __webpack_require__("a48a") , UnionFind = __webpack_require__("dca5") //Returns the dimension of a cell complex function dimension(cells) { var d = 0 , max = Math.max for(var i=0, il=cells.length; i> 1 , s = compareCells(cells[mid], c) if(s <= 0) { if(s === 0) { r = mid } lo = mid + 1 } else if(s > 0) { hi = mid - 1 } } return r } exports.findCell = findCell; //Builds an index for an n-cell. This is more general than dual, but less efficient function incidence(from_cells, to_cells) { var index = new Array(from_cells.length) for(var i=0, il=index.length; i= from_cells.length || compareCells(from_cells[idx], b) !== 0) { break } } } } return index } exports.incidence = incidence //Computes the dual of the mesh. This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices function dual(cells, vertex_count) { if(!vertex_count) { return incidence(unique(skeleton(cells, 0)), cells, 0) } var res = new Array(vertex_count) for(var i=0; i>> k) & 1) { b.push(c[k]) } } result.push(b) } } return normalize(result) } exports.explode = explode //Enumerates all of the n-cells of a cell complex function skeleton(cells, n) { if(n < 0) { return [] } var result = [] , k0 = (1<<(n+1))-1 for(var i=0; i 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; /* * calculate the *primary* pixel position * which is the arrowhead if there is one, * otherwise the text anchor point */ if(ax) { // 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 { if(axLetter === 'x') { alignPosition = options[axLetter]; basePx = gs.l + gs.w * alignPosition; } else { alignPosition = 1 - options[axLetter]; 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) { posPx.tail = ax._offset + ax.r2p(arrowLength); // tail is data-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: 'translate(' + 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', xa ? xa.p2r(xa.r2p(options.x) + dx) : (options.x + (dx / gs.w))); modifyItem('y', ya ? ya.p2r(ya.r2p(options.y) + dy) : (options.y - (dy / gs.h))); if(options.axref === options.xref) { modifyItem('ax', xa.p2r(xa.r2p(options.ax) + dx)); } if(options.ayref === options.yref) { modifyItem('ay', ya.p2r(ya.r2p(options.ay) + dy)); } arrowGroup.attr('transform', 'translate(' + 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) { if(options.axref === options.xref) { modifyItem('ax', xa.p2r(xa.r2p(options.ax) + dx)); } else { modifyItem('ax', options.ax + dx); } if(options.ayref === options.yref) { modifyItem('ay', ya.p2r(ya.r2p(options.ay) + dy)); } else { modifyItem('ay', options.ay + dy); } drawArrow(dx, dy); } else if(!subplotId) { var xUpdate, yUpdate; if(xa) { xUpdate = xa.p2r(xa.r2p(options.x) + dx); } 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) { yUpdate = ya.p2r(ya.r2p(options.y) + dy); } 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: 'translate(' + 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); } /***/ }), /***/ "25be": /***/ (function(module, exports, __webpack_require__) { "use strict"; var d = __webpack_require__("f508") , validateSymbol = __webpack_require__("b380"); var registry = Object.create(null); module.exports = function (SymbolPolyfill) { return Object.defineProperties(SymbolPolyfill, { for: d(function (key) { if (registry[key]) return registry[key]; return (registry[key] = SymbolPolyfill(String(key))); }), keyFor: d(function (symbol) { var key; validateSymbol(symbol); for (key in registry) { if (registry[key] === symbol) return key; } return undefined; }) }); }; /***/ }), /***/ "25f3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var attrs = __webpack_require__("4ce7"); 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; } } } }; /***/ }), /***/ "25f9": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); /* * 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 surrouding 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; }; /***/ }), /***/ "262a": /***/ (function(module, exports, __webpack_require__) { "use strict"; var resolveException = __webpack_require__("84d3") , is = __webpack_require__("936a"); module.exports = function (value/*, options*/) { if (is(value)) return value; return resolveException(value, "Cannot use %v", arguments[1]); }; /***/ }), /***/ "2638": /***/ (function(module, exports) { module.exports = create /** * Creates a new, empty vec4 * * @returns {vec4} a new 4D vector */ function create () { var out = new Float32Array(4) out[0] = 0 out[1] = 0 out[2] = 0 out[3] = 0 return out } /***/ }), /***/ "265e": /***/ (function(module, exports) { module.exports = copy /** * Copy the values from one vec4 to another * * @param {vec4} out the receiving vector * @param {vec4} a the source vector * @returns {vec4} out */ function copy (out, a) { out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[3] return out } /***/ }), /***/ "26a7": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createErrorBars var createBuffer = __webpack_require__("efce") var createVAO = __webpack_require__("b205") var createShader = __webpack_require__("531f") 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; i 0) { 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 } /***/ }), /***/ "26cf": /***/ (function(module, exports, __webpack_require__) { "use strict"; var pool = __webpack_require__("cea5") var inverse = __webpack_require__("f31e") function rank(permutation) { var n = permutation.length switch(n) { case 0: case 1: return 0 case 2: return permutation[1] default: break } var p = pool.mallocUint32(n) var pinv = pool.mallocUint32(n) var r = 0, s, t, i inverse(permutation, pinv) for(i=0; i0; --i) { t = pinv[i] s = p[i] p[i] = p[t] p[t] = s pinv[i] = pinv[s] pinv[s] = t r = (r + s) * i } pool.freeUint32(pinv) pool.freeUint32(p) return r } function unrank(n, r, p) { switch(n) { case 0: if(p) { return p } return [] case 1: if(p) { p[0] = 0 return p } else { return [0] } case 2: if(p) { if(r) { p[0] = 0 p[1] = 1 } else { p[0] = 1 p[1] = 0 } return p } else { return r ? [0,1] : [1,0] } default: break } p = p || new Array(n) var s, t, i, nf=1 p[0] = 0 for(i=1; i0; --i) { s = (r / nf)|0 r = (r - s * nf)|0 nf = (nf / i)|0 t = p[i]|0 p[i] = p[s]|0 p[s] = t|0 } return p } exports.rank = rank exports.unrank = unrank /***/ }), /***/ "26d1": /***/ (function(module, exports) { module.exports = transformQuat; /** * Transforms the vec3 with a quat * * @param {vec3} out the receiving vector * @param {vec3} a the vector to transform * @param {quat} q quaternion to transform with * @returns {vec3} out */ function transformQuat(out, a, q) { // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations var x = a[0], y = a[1], z = a[2], qx = q[0], qy = q[1], qz = q[2], qw = q[3], // calculate quat * vec ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z // calculate result * inverse quat out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx return out } /***/ }), /***/ "26dd": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var c = __webpack_require__("0d59"); var d3 = __webpack_require__("6e58"); var gup = __webpack_require__("0a3e"); var Drawing = __webpack_require__("83d1"); var svgUtil = __webpack_require__("0379"); var raiseToTop = __webpack_require__("fc26").raiseToTop; var cancelEeaseColumn = __webpack_require__("fc26").cancelTransition; var prepareData = __webpack_require__("8766"); var splitData = __webpack_require__("7815"); var Color = __webpack_require__("d115"); 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 'translate(' + 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) { cvEnter .on('mousemove', function(d) { tableControlView .filter(function(dd) {return d === dd;}) .call(renderScrollbarKit, gd); }) .on('mousewheel', 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 'translate(' + 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 'translate(' + 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 'translate(' + d.x + ' 0)';}); movedColumn .call(cancelEeaseColumn) .attr('transform', 'translate(' + 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 'translate(' + 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 'translate(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) }; 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 ? d3.format(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 'translate(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 'translate(' + 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 'translate(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];} /***/ }), /***/ "26e4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var scatterAttrs = __webpack_require__("107c"); var colorScaleAttrs = __webpack_require__("f4e9"); var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var scatterGlAttrs = __webpack_require__("c20e"); var cartesianIdRegex = __webpack_require__("d301").idRegex; var templatedArray = __webpack_require__("a651").templatedArray; var extendFlat = __webpack_require__("9092").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, 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 v2? 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(), 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 }; /***/ }), /***/ "2705": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var constants = __webpack_require__("de69"); var subTypes = __webpack_require__("de81"); var handleMarkerDefaults = __webpack_require__("5047"); var handleLineDefaults = __webpack_require__("59be"); var handleLineShapeDefaults = __webpack_require__("eb07"); var handleTextDefaults = __webpack_require__("e9f7"); var handleFillColorDefaults = __webpack_require__("3802"); var attributes = __webpack_require__("5aae"); 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.hasLines(traceOut)) { handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce); handleLineShapeDefaults(traceIn, traceOut, coerce); coerce('connectgaps'); } if(subTypes.hasMarkers(traceOut)) { handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } 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'); Lib.coerceSelectionMarkerOpacity(traceOut, coerce); }; /***/ }), /***/ "2781": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("0e9a"); /***/ }), /***/ "27a4": /***/ (function(module, exports) { module.exports = cross; /** * Computes the cross product of two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function cross(out, a, b) { var ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2] out[0] = ay * bz - az * by out[1] = az * bx - ax * bz out[2] = ax * by - ay * bx return out } /***/ }), /***/ "27c6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); var helpers = __webpack_require__("50da"); var attributes = __webpack_require__("c20e"); var constants = __webpack_require__("de69"); var subTypes = __webpack_require__("de81"); var handleXYDefaults = __webpack_require__("076f"); var handleMarkerDefaults = __webpack_require__("5047"); var handleLineDefaults = __webpack_require__("59be"); var handleFillColorDefaults = __webpack_require__("3802"); var handleTextDefaults = __webpack_require__("e9f7"); 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; } var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines'; coerce('text'); coerce('hovertext'); coerce('hovertemplate'); coerce('mode', defaultMode); if(subTypes.hasLines(traceOut)) { coerce('connectgaps'); handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce); coerce('line.shape'); } if(subTypes.hasMarkers(traceOut)) { handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce); coerce('marker.line.width', isOpen || isBubble ? 1 : 0); } if(subTypes.hasText(traceOut)) { coerce('texttemplate'); handleTextDefaults(traceIn, traceOut, layout, coerce); } 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); }; /***/ }), /***/ "27e3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var layoutAttributes = __webpack_require__("d798"); /** * options: inherits outerTicks from axes.handleAxisDefaults */ module.exports = function handleTickDefaults(containerIn, containerOut, coerce, options) { var tickLen = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'ticklen'); var tickWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickwidth'); var tickColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickcolor', containerOut.color); var showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); if(!showTicks) { delete containerOut.ticklen; delete containerOut.tickwidth; delete containerOut.tickcolor; } }; /***/ }), /***/ "283e": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createLines var createBuffer = __webpack_require__("efce") var createShader = __webpack_require__("28dd") var shaders = __webpack_require__("b44d") function Lines(plot, vbo, shader) { this.plot = plot this.vbo = vbo this.shader = shader } var proto = Lines.prototype proto.bind = function() { var shader = this.shader this.vbo.bind() this.shader.bind() shader.attributes.coord.pointer() shader.uniforms.screenBox = this.plot.screenBox } proto.drawLine = (function() { var start = [0,0] var end = [0,0] return function(startX, startY, endX, endY, width, color) { var plot = this.plot var shader = this.shader var gl = plot.gl start[0] = startX start[1] = startY end[0] = endX end[1] = endY shader.uniforms.start = start shader.uniforms.end = end shader.uniforms.width = width * plot.pixelRatio shader.uniforms.color = color gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) } }()) proto.dispose = function() { this.vbo.dispose() this.shader.dispose() } function createLines(plot) { var gl = plot.gl var vbo = createBuffer(gl, [ -1,-1, -1,1, 1,-1, 1,1]) var shader = createShader(gl, shaders.lineVert, shaders.lineFrag) var lines = new Lines(plot, vbo, shader) return lines } /***/ }), /***/ "28a0": /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /***/ "28dd": /***/ (function(module, exports, __webpack_require__) { "use strict"; var createUniformWrapper = __webpack_require__("d064b") var createAttributeWrapper = __webpack_require__("7e91") var makeReflect = __webpack_require__("eb73") var shaderCache = __webpack_require__("22b4") var runtime = __webpack_require__("d41a") var GLError = __webpack_require__("a3fd") //Shader object function Shader(gl) { this.gl = gl this.gl.lastAttribCount = 0 // fixme where else should we store info, safe but not nice on the gl object //Default initialize these to null this._vref = this._fref = this._relink = this.vertShader = this.fragShader = this.program = this.attributes = this.uniforms = this.types = null } var proto = Shader.prototype proto.bind = function() { if(!this.program) { this._relink() } // ensuring that we have the right number of enabled vertex attributes var i var newAttribCount = this.gl.getProgramParameter(this.program, this.gl.ACTIVE_ATTRIBUTES) // more robust approach //var newAttribCount = Object.keys(this.attributes).length // avoids the probably immaterial introspection slowdown var oldAttribCount = this.gl.lastAttribCount if(newAttribCount > oldAttribCount) { for(i = oldAttribCount; i < newAttribCount; i++) { this.gl.enableVertexAttribArray(i) } } else if(oldAttribCount > newAttribCount) { for(i = newAttribCount; i < oldAttribCount; i++) { this.gl.disableVertexAttribArray(i) } } this.gl.lastAttribCount = newAttribCount this.gl.useProgram(this.program) } proto.dispose = function() { // disabling vertex attributes so new shader starts with zero // and it's also useful if all shaders are disposed but the // gl context is reused for subsequent replotting var oldAttribCount = this.gl.lastAttribCount for (var i = 0; i < oldAttribCount; i++) { this.gl.disableVertexAttribArray(i) } this.gl.lastAttribCount = 0 if(this._fref) { this._fref.dispose() } if(this._vref) { this._vref.dispose() } this.attributes = this.types = this.vertShader = this.fragShader = this.program = this._relink = this._fref = this._vref = null } function compareAttributes(a, b) { if(a.name < b.name) { return -1 } return 1 } //Update export hook for glslify-live proto.update = function( vertSource , fragSource , uniforms , attributes) { //If only one object passed, assume glslify style output if(!fragSource || arguments.length === 1) { var obj = vertSource vertSource = obj.vertex fragSource = obj.fragment uniforms = obj.uniforms attributes = obj.attributes } var wrapper = this var gl = wrapper.gl //Compile vertex and fragment shaders var pvref = wrapper._vref wrapper._vref = shaderCache.shader(gl, gl.VERTEX_SHADER, vertSource) if(pvref) { pvref.dispose() } wrapper.vertShader = wrapper._vref.shader var pfref = this._fref wrapper._fref = shaderCache.shader(gl, gl.FRAGMENT_SHADER, fragSource) if(pfref) { pfref.dispose() } wrapper.fragShader = wrapper._fref.shader //If uniforms/attributes is not specified, use RT reflection if(!uniforms || !attributes) { //Create initial test program var testProgram = gl.createProgram() gl.attachShader(testProgram, wrapper.fragShader) gl.attachShader(testProgram, wrapper.vertShader) gl.linkProgram(testProgram) if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) { var errLog = gl.getProgramInfoLog(testProgram) throw new GLError(errLog, 'Error linking program:' + errLog) } //Load data from runtime uniforms = uniforms || runtime.uniforms(gl, testProgram) attributes = attributes || runtime.attributes(gl, testProgram) //Release test program gl.deleteProgram(testProgram) } //Sort attributes lexicographically // overrides undefined WebGL behavior for attribute locations attributes = attributes.slice() attributes.sort(compareAttributes) //Convert attribute types, read out locations var attributeUnpacked = [] var attributeNames = [] var attributeLocations = [] var i for(i=0; 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 maxNorm) { maxNorm = vec3.length(u); } if (i) { // 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 || 0.5; if (vectorfield.absoluteConeSize) { coneScale = vectorfield.absoluteConeSize * invertedMaxNorm; } geo.coneScale = coneScale; // Build the cone model. for (var i = 0, j = 0; i < positions.length; i++) { var p = positions[i]; var x = p[0], y = p[1], z = p[2]; var d = positionVectors[i]; var intensity = vec3.length(d) * invertedMaxNorm; for (var k = 0, l = 8; k < l; k++) { geo.positions.push([x, y, z, j++]); geo.positions.push([x, y, z, j++]); geo.positions.push([x, y, z, j++]); geo.positions.push([x, y, z, j++]); geo.positions.push([x, y, z, j++]); geo.positions.push([x, y, z, j++]); geo.vectors.push(d); geo.vectors.push(d); geo.vectors.push(d); geo.vectors.push(d); geo.vectors.push(d); geo.vectors.push(d); geo.vertexIntensity.push(intensity, intensity, intensity); geo.vertexIntensity.push(intensity, intensity, intensity); var m = geo.positions.length; geo.cells.push([m-6, m-5, m-4], [m-3, m-2, m-1]); } } return geo; }; var shaders = __webpack_require__("f280"); module.exports.createMesh = __webpack_require__("6b3c"); module.exports.createConeMesh = function(gl, params) { return module.exports.createMesh(gl, params, { shaders: shaders, traceType: 'cone' }); } /***/ }), /***/ "2969f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "296e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // 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; }; /***/ }), /***/ "299d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var createScatter = __webpack_require__("96e3"); var createLine = __webpack_require__("e8ee"); var createError = __webpack_require__("b113"); var Text = __webpack_require__("ad68"); var Lib = __webpack_require__("fc26"); var prepareRegl = __webpack_require__("cf42"); var subTypes = __webpack_require__("de81"); var linkTraces = __webpack_require__("00bd"); var styleTextSelection = __webpack_require__("e38a").styleTextSelection; function getViewport(fullLayout, xaxis, yaxis) { var gs = fullLayout._size; var width = fullLayout.width; var height = fullLayout.height; return [ gs.l + xaxis.domain[0] * gs.w, gs.b + yaxis.domain[0] * gs.h, (width - gs.r) - (1 - xaxis.domain[1]) * gs.w, (height - gs.t) - (1 - yaxis.domain[1]) * gs.h ]; } 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']); 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) { // 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; 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]); 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 selectMode = dragmode === 'lasso' || dragmode === 'select'; 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 || selectMode || clickSelectEnabled) { if(!selectMode) selectMode = 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(selectMode) { // 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), // 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); }); } }; /***/ }), /***/ "2a16": /***/ (function(module, exports) { module.exports = scale; /** * Scales a vec3 by a scalar number * * @param {vec3} out the receiving vector * @param {vec3} a the vector to scale * @param {Number} b amount to scale the vector by * @returns {vec3} out */ function scale(out, a, b) { out[0] = a[0] * b out[1] = a[1] * b out[2] = a[2] * b return out } /***/ }), /***/ "2a27": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var attributes = __webpack_require__("97d1"); var Color = __webpack_require__("d115"); var handleDomainDefaults = __webpack_require__("81f0").defaults; var handleText = __webpack_require__("1c1c").handleText; var TEXTPAD = __webpack_require__("1a5e").TEXTPAD; var Colorscale = __webpack_require__("c258"); 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', Array.isArray(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; var lineWidth = coerce('marker.line.width'); if(lineWidth) coerce('marker.line.color', layout.paper_bgcolor); var colors = coerce('marker.colors'); 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', !(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); if(withColorscale) { colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}); } 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'); } handleDomainDefaults(traceOut, layout, coerce); // do not support transforms for now traceOut._length = null; }; /***/ }), /***/ "2aa9": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "2ad6": /***/ (function(module, exports, __webpack_require__) { "use strict"; var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__; /** * Copyright Marc J. Schmidt. See the LICENSE file at the top-level * directory of this distribution and at * https://github.com/marcj/css-element-queries/blob/master/LICENSE. */ (function (root, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }(typeof window !== 'undefined' ? window : this, function () { // Make sure it does not throw in a SSR (Server Side Rendering) situation if (typeof window === "undefined") { return null; } // https://github.com/Semantic-Org/Semantic-UI/issues/3855 // https://github.com/marcj/css-element-queries/issues/257 var globalWindow = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); // Only used for the dirty checking, so the event callback count is limited to max 1 call per fps per sensor. // In combination with the event based resize sensor this saves cpu time, because the sensor is too fast and // would generate too many unnecessary events. var requestAnimationFrame = globalWindow.requestAnimationFrame || globalWindow.mozRequestAnimationFrame || globalWindow.webkitRequestAnimationFrame || function (fn) { return globalWindow.setTimeout(fn, 20); }; /** * Iterate over each of the provided element(s). * * @param {HTMLElement|HTMLElement[]} elements * @param {Function} callback */ function forEachElement(elements, callback){ var elementsType = Object.prototype.toString.call(elements); var isCollectionTyped = ('[object Array]' === elementsType || ('[object NodeList]' === elementsType) || ('[object HTMLCollection]' === elementsType) || ('[object Object]' === elementsType) || ('undefined' !== typeof jQuery && elements instanceof jQuery) //jquery || ('undefined' !== typeof Elements && elements instanceof Elements) //mootools ); var i = 0, j = elements.length; if (isCollectionTyped) { for (; i < j; i++) { callback(elements[i]); } } else { callback(elements); } } /** * Get element size * @param {HTMLElement} element * @returns {Object} {width, height} */ function getElementSize(element) { if (!element.getBoundingClientRect) { return { width: element.offsetWidth, height: element.offsetHeight } } var rect = element.getBoundingClientRect(); return { width: Math.round(rect.width), height: Math.round(rect.height) } } /** * Apply CSS styles to element. * * @param {HTMLElement} element * @param {Object} style */ function setStyle(element, style) { Object.keys(style).forEach(function(key) { element.style[key] = style[key]; }); } /** * Class for dimension change detection. * * @param {Element|Element[]|Elements|jQuery} element * @param {Function} callback * * @constructor */ var ResizeSensor = function(element, callback) { /** * * @constructor */ function EventQueue() { var q = []; this.add = function(ev) { q.push(ev); }; var i, j; this.call = function(sizeInfo) { for (i = 0, j = q.length; i < j; i++) { q[i].call(this, sizeInfo); } }; this.remove = function(ev) { var newQueue = []; for(i = 0, j = q.length; i < j; i++) { if(q[i] !== ev) newQueue.push(q[i]); } q = newQueue; }; this.length = function() { return q.length; } } /** * * @param {HTMLElement} element * @param {Function} resized */ function attachResizeEvent(element, resized) { if (!element) return; if (element.resizedAttached) { element.resizedAttached.add(resized); return; } element.resizedAttached = new EventQueue(); element.resizedAttached.add(resized); element.resizeSensor = document.createElement('div'); element.resizeSensor.dir = 'ltr'; element.resizeSensor.className = 'resize-sensor'; var style = { pointerEvents: 'none', position: 'absolute', left: '0px', top: '0px', right: '0px', bottom: '0px', overflow: 'hidden', zIndex: '-1', visibility: 'hidden', maxWidth: '100%' }; var styleChild = { position: 'absolute', left: '0px', top: '0px', transition: '0s', }; setStyle(element.resizeSensor, style); var expand = document.createElement('div'); expand.className = 'resize-sensor-expand'; setStyle(expand, style); var expandChild = document.createElement('div'); setStyle(expandChild, styleChild); expand.appendChild(expandChild); var shrink = document.createElement('div'); shrink.className = 'resize-sensor-shrink'; setStyle(shrink, style); var shrinkChild = document.createElement('div'); setStyle(shrinkChild, styleChild); setStyle(shrinkChild, { width: '200%', height: '200%' }); shrink.appendChild(shrinkChild); element.resizeSensor.appendChild(expand); element.resizeSensor.appendChild(shrink); element.appendChild(element.resizeSensor); var computedStyle = window.getComputedStyle(element); var position = computedStyle ? computedStyle.getPropertyValue('position') : null; if ('absolute' !== position && 'relative' !== position && 'fixed' !== position) { element.style.position = 'relative'; } var dirty, rafId; var size = getElementSize(element); var lastWidth = 0; var lastHeight = 0; var initialHiddenCheck = true; var lastAnimationFrame = 0; var resetExpandShrink = function () { var width = element.offsetWidth; var height = element.offsetHeight; expandChild.style.width = (width + 10) + 'px'; expandChild.style.height = (height + 10) + 'px'; expand.scrollLeft = width + 10; expand.scrollTop = height + 10; shrink.scrollLeft = width + 10; shrink.scrollTop = height + 10; }; var reset = function() { // Check if element is hidden if (initialHiddenCheck) { var invisible = element.offsetWidth === 0 && element.offsetHeight === 0; if (invisible) { // Check in next frame if (!lastAnimationFrame){ lastAnimationFrame = requestAnimationFrame(function(){ lastAnimationFrame = 0; reset(); }); } return; } else { // Stop checking initialHiddenCheck = false; } } resetExpandShrink(); }; element.resizeSensor.resetSensor = reset; var onResized = function() { rafId = 0; if (!dirty) return; lastWidth = size.width; lastHeight = size.height; if (element.resizedAttached) { element.resizedAttached.call(size); } }; var onScroll = function() { size = getElementSize(element); dirty = size.width !== lastWidth || size.height !== lastHeight; if (dirty && !rafId) { rafId = requestAnimationFrame(onResized); } reset(); }; var addEvent = function(el, name, cb) { if (el.attachEvent) { el.attachEvent('on' + name, cb); } else { el.addEventListener(name, cb); } }; addEvent(expand, 'scroll', onScroll); addEvent(shrink, 'scroll', onScroll); // Fix for custom Elements requestAnimationFrame(reset); } forEachElement(element, function(elem){ attachResizeEvent(elem, callback); }); this.detach = function(ev) { ResizeSensor.detach(element, ev); }; this.reset = function() { element.resizeSensor.resetSensor(); }; }; ResizeSensor.reset = function(element) { forEachElement(element, function(elem){ elem.resizeSensor.resetSensor(); }); }; ResizeSensor.detach = function(element, ev) { forEachElement(element, function(elem){ if (!elem) return; if(elem.resizedAttached && typeof ev === "function"){ elem.resizedAttached.remove(ev); if(elem.resizedAttached.length()) return; } if (elem.resizeSensor) { if (elem.contains(elem.resizeSensor)) { elem.removeChild(elem.resizeSensor); } delete elem.resizeSensor; delete elem.resizedAttached; } }); }; if (typeof MutationObserver !== "undefined") { var observer = new MutationObserver(function (mutations) { for (var i in mutations) { if (mutations.hasOwnProperty(i)) { var items = mutations[i].addedNodes; for (var j = 0; j < items.length; j++) { if (items[j].resizeSensor) { ResizeSensor.reset(items[j]); } } } } }); document.addEventListener("DOMContentLoaded", function (event) { observer.observe(document.body, { childList: true, subtree: true, }); }); } return ResizeSensor; })); /***/ }), /***/ "2c66": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("2456") /***/ }), /***/ "2c8d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { var isBrowser = __webpack_require__("dcf3") var hasHover if (typeof global.matchMedia === 'function') { hasHover = !global.matchMedia('(hover: none)').matches } else { hasHover = isBrowser } module.exports = hasHover /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("c8ba"))) /***/ }), /***/ "2d00": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("da84"); var userAgent = __webpack_require__("342f"); var process = global.process; var versions = process && process.versions; var v8 = versions && versions.v8; var match, version; if (v8) { match = v8.split('.'); version = match[0] + match[1]; } else if (userAgent) { match = userAgent.match(/Edge\/(\d+)/); if (!match || match[1] >= 74) { match = userAgent.match(/Chrome\/(\d+)/); if (match) version = match[1]; } } module.exports = version && +version; /***/ }), /***/ "2d0e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); 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; } /***/ }), /***/ "2d12": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("08ed"); /***/ }), /***/ "2d1c": /***/ (function(module, exports) { module.exports = negate; /** * Negates the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to negate * @returns {vec3} out */ function negate(out, a) { out[0] = -a[0] out[1] = -a[1] out[2] = -a[2] return out } /***/ }), /***/ "2d7d": /***/ (function(module, exports, __webpack_require__) { /* * World Calendars * https://github.com/alexcjohnson/world-calendars * * Batch-converted from kbwood/calendars * Many thanks to Keith Wood and all of the contributors to the original project! * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* http://keith-wood.name/calendars.html Persian calendar for jQuery v2.0.2. Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009. Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ var main = __webpack_require__("0230"); var assign = __webpack_require__("320c"); /** Implementation of the Persian or Jalali calendar. Based on code from http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php. See also http://en.wikipedia.org/wiki/Iranian_calendar. @class PersianCalendar @param [language=''] {string} The language code (default English) for localisation. */ function PersianCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } PersianCalendar.prototype = new main.baseCalendar; assign(PersianCalendar.prototype, { /** The calendar name. @memberof PersianCalendar */ name: 'Persian', /** Julian date of start of Persian epoch: 19 March 622 CE. @memberof PersianCalendar */ jdEpoch: 1948320.5, /** Days per month in a common year. @memberof PersianCalendar */ daysPerMonth: [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29], /** true if has a year zero, false if not. @memberof PersianCalendar */ hasYearZero: false, /** The minimum month number. @memberof PersianCalendar */ minMonth: 1, /** The first month in the year. @memberof PersianCalendar */ firstMonth: 1, /** The minimum day number. @memberof PersianCalendar */ minDay: 1, /** Localisations for the plugin. Entries are objects indexed by the language code ('' being the default US/English). Each object has the following attributes. @memberof PersianCalendar @property name {string} The calendar name. @property epochs {string[]} The epoch names. @property monthNames {string[]} The long names of the months of the year. @property monthNamesShort {string[]} The short names of the months of the year. @property dayNames {string[]} The long names of the days of the week. @property dayNamesShort {string[]} The short names of the days of the week. @property dayNamesMin {string[]} The minimal names of the days of the week. @property dateFormat {string} The date format for this calendar. See the options on formatDate for details. @property firstDay {number} The number of the first day of the week, starting at 0. @property isRTL {number} true if this localisation reads right-to-left. */ regionalOptions: { // Localisations '': { name: 'Persian', epochs: ['BP', 'AP'], monthNames: ['Farvardin', 'Ordibehesht', 'Khordad', 'Tir', 'Mordad', 'Shahrivar', 'Mehr', 'Aban', 'Azar', 'Day', 'Bahman', 'Esfand'], monthNamesShort: ['Far', 'Ord', 'Kho', 'Tir', 'Mor', 'Sha', 'Meh', 'Aba', 'Aza', 'Day', 'Bah', 'Esf'], dayNames: ['Yekshambe', 'Doshambe', 'Seshambe', 'Chæharshambe', 'Panjshambe', 'Jom\'e', 'Shambe'], dayNamesShort: ['Yek', 'Do', 'Se', 'Chæ', 'Panj', 'Jom', 'Sha'], dayNamesMin: ['Ye','Do','Se','Ch','Pa','Jo','Sh'], digits: null, dateFormat: 'yyyy/mm/dd', firstDay: 6, isRTL: false } }, /** Determine whether this date is in a leap year. @memberof PersianCalendar @param year {CDate|number} The date to examine or the year to examine. @return {boolean} true if this is a leap year, false if not. @throws Error if an invalid year or a different calendar used. */ leapYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear); return (((((date.year() - (date.year() > 0 ? 474 : 473)) % 2820) + 474 + 38) * 682) % 2816) < 682; }, /** Determine the week of the year for a date. @memberof PersianCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {number} The week of the year. @throws Error if an invalid date or a different calendar used. */ weekOfYear: function(year, month, day) { // Find Saturday of this week starting on Saturday var checkDate = this.newDate(year, month, day); checkDate.add(-((checkDate.dayOfWeek() + 1) % 7), 'd'); return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1; }, /** Retrieve the number of days in a month. @memberof PersianCalendar @param year {CDate|number} The date to examine or the year of the month. @param [month] {number} The month. @return {number} The number of days in this month. @throws Error if an invalid month/year or a different calendar used. */ daysInMonth: function(year, month) { var date = this._validate(year, month, this.minDay, main.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0); }, /** Determine whether this date is a week day. @memberof PersianCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {boolean} true if a week day, false if not. @throws Error if an invalid date or a different calendar used. */ weekDay: function(year, month, day) { return this.dayOfWeek(year, month, day) !== 5; }, /** Retrieve the Julian date equivalent for this date, i.e. days since January 1, 4713 BCE Greenwich noon. @memberof PersianCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(year, month, day) { var date = this._validate(year, month, day, main.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); var epBase = year - (year >= 0 ? 474 : 473); var epYear = 474 + mod(epBase, 2820); return day + (month <= 7 ? (month - 1) * 31 : (month - 1) * 30 + 6) + Math.floor((epYear * 682 - 110) / 2816) + (epYear - 1) * 365 + Math.floor(epBase / 2820) * 1029983 + this.jdEpoch - 1; }, /** Create a new date from a Julian date. @memberof PersianCalendar @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { jd = Math.floor(jd) + 0.5; var depoch = jd - this.toJD(475, 1, 1); var cycle = Math.floor(depoch / 1029983); var cyear = mod(depoch, 1029983); var ycycle = 2820; if (cyear !== 1029982) { var aux1 = Math.floor(cyear / 366); var aux2 = mod(cyear, 366); ycycle = Math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1; } var year = ycycle + (2820 * cycle) + 474; year = (year <= 0 ? year - 1 : year); var yday = jd - this.toJD(year, 1, 1) + 1; var month = (yday <= 186 ? Math.ceil(yday / 31) : Math.ceil((yday - 6) / 30)); var day = jd - this.toJD(year, month, 1) + 1; return this.newDate(year, month, day); } }); // Modulus function which works for non-integers. function mod(a, b) { return a - (b * Math.floor(a / b)); } // Persian (Jalali) calendar implementation main.calendars.persian = PersianCalendar; main.calendars.jalali = PersianCalendar; /***/ }), /***/ "2d9a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var isPlainObject = Lib.isPlainObject; var PlotSchema = __webpack_require__("6921"); var Plots = __webpack_require__("bb71"); var plotAttributes = __webpack_require__("a876"); var Template = __webpack_require__("a651"); var dfltConfig = __webpack_require__("3ff5").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; } /***/ }), /***/ "2dbe": /***/ (function(module, exports, __webpack_require__) { "use strict"; var stringifyFont = __webpack_require__("c243") var defaultChars = [32, 126] module.exports = atlas function atlas(options) { options = options || {} var shape = options.shape ? options.shape : options.canvas ? [options.canvas.width, options.canvas.height] : [512, 512] var canvas = options.canvas || document.createElement('canvas') var font = options.font var step = typeof options.step === 'number' ? [options.step, options.step] : options.step || [32, 32] var chars = options.chars || defaultChars if (font && typeof font !== 'string') font = stringifyFont(font) if (!Array.isArray(chars)) { chars = String(chars).split('') } else if (chars.length === 2 && typeof chars[0] === 'number' && typeof chars[1] === 'number' ) { var newchars = [] for (var i = chars[0], j = 0; i <= chars[1]; i++) { newchars[j++] = String.fromCharCode(i) } chars = newchars } shape = shape.slice() canvas.width = shape[0] canvas.height = shape[1] var ctx = canvas.getContext('2d') ctx.fillStyle = '#000' ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.font = font ctx.textAlign = 'center' ctx.textBaseline = 'middle' ctx.fillStyle = '#fff' var x = step[0] / 2 var y = step[1] / 2 for (var i = 0; i < chars.length; i++) { ctx.fillText(chars[i], x, y) if ((x += step[0]) > shape[0] - step[0]/2) (x = step[0]/2), (y += step[1]) } return canvas } /***/ }), /***/ "2dd7": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var layoutAttributes = __webpack_require__("7ba3"); module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt); } coerce('sunburstcolorway', layoutOut.colorway); coerce('extendsunburstcolors'); }; /***/ }), /***/ "2dd9": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = compressExpansion function compressExpansion(e) { var m = e.length var Q = e[e.length-1] var bottom = m for(var i=m-2; i>=0; --i) { var a = Q var b = e[i] Q = a + b var bv = Q - a var q = b - bv if(q) { e[--bottom] = Q Q = q } } var top = 0 for(var i=bottom; i 1) || (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0 && !d[0].trace.marker.line.width)) { d3.select(this).attr('shape-rendering', 'crispEdges'); } }); s.selectAll('g.points').each(function(d) { var sel = d3.select(this); var trace = d[0].trace; stylePoints(sel, trace, gd); }); Registry.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { Drawing.pointStyle(sel.selectAll('path'), trace, gd); styleTextPoints(sel, trace, gd); } function styleTextPoints(sel, trace, gd) { sel.selectAll('text').each(function(d) { var tx = d3.select(this); var font = Lib.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd)); Drawing.font(tx, font); }); } function styleOnSelect(gd, cd, sel) { var trace = cd[0].trace; if(trace.selectedpoints) { stylePointsInSelectionMode(sel, trace, gd); } else { stylePoints(sel, trace, gd); Registry.getComponentMethod('errorbars', 'style')(sel); } } function stylePointsInSelectionMode(s, trace, gd) { Drawing.selectedPointStyle(s.selectAll('path'), trace); styleTextInSelectionMode(s.selectAll('text'), trace, gd); } function styleTextInSelectionMode(txs, trace, gd) { txs.each(function(d) { var tx = d3.select(this); var font; if(d.selected) { font = Lib.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd)); var selectedFontColor = trace.selected.textfont && trace.selected.textfont.color; if(selectedFontColor) { font.color = selectedFontColor; } Drawing.font(tx, font); } else { Drawing.selectedTextStyle(tx, trace); } }); } function determineFont(tx, d, trace, gd) { var layoutFont = gd._fullLayout.font; var textFont = trace.textfont; if(tx.classed('bartext-inside')) { var barColor = getBarColor(d, trace); textFont = getInsideTextFont(trace, d.i, layoutFont, barColor); } else if(tx.classed('bartext-outside')) { textFont = getOutsideTextFont(trace, d.i, layoutFont); } return textFont; } function getTextFont(trace, index, defaultValue) { return getFontValue( attributeTextFont, trace.textfont, index, defaultValue); } function getInsideTextFont(trace, index, layoutFont, barColor) { var defaultFont = getTextFont(trace, index, layoutFont); var wouldFallBackToLayoutFont = (trace._input.textfont === undefined || trace._input.textfont.color === undefined) || (Array.isArray(trace.textfont.color) && trace.textfont.color[index] === undefined); if(wouldFallBackToLayoutFont) { defaultFont = { color: Color.contrast(barColor), family: defaultFont.family, size: defaultFont.size }; } return getFontValue( attributeInsideTextFont, trace.insidetextfont, index, defaultFont); } function getOutsideTextFont(trace, index, layoutFont) { var defaultFont = getTextFont(trace, index, layoutFont); return getFontValue( attributeOutsideTextFont, trace.outsidetextfont, index, defaultFont); } function getFontValue(attributeDefinition, attributeValue, index, defaultValue) { attributeValue = attributeValue || {}; var familyValue = helpers.getValue(attributeValue.family, index); var sizeValue = helpers.getValue(attributeValue.size, index); var colorValue = helpers.getValue(attributeValue.color, index); return { family: helpers.coerceString( attributeDefinition.family, familyValue, defaultValue.family), size: helpers.coerceNumber( attributeDefinition.size, sizeValue, defaultValue.size), color: helpers.coerceColor( attributeDefinition.color, colorValue, defaultValue.color) }; } function getBarColor(cd, trace) { if(trace.type === 'waterfall') { return trace[cd.dir].marker.color; } return cd.mc || trace.marker.color; } module.exports = { style: style, styleTextPoints: styleTextPoints, styleOnSelect: styleOnSelect, getInsideTextFont: getInsideTextFont, getOutsideTextFont: getOutsideTextFont, getBarColor: getBarColor, resizeText: resizeText }; /***/ }), /***/ "2e22": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sankeyCircular", function() { return sankeyCircular; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sankeyCenter", function() { return center; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sankeyLeft", function() { return left; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sankeyRight", function() { return right; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sankeyJustify", function() { return justify; }); /* harmony import */ var d3_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("bc17"); /* harmony import */ var d3_collection__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("6f04"); /* harmony import */ var d3_shape__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("1a88"); /* harmony import */ var elementary_circuits_directed_graph__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("7e55"); /* harmony import */ var elementary_circuits_directed_graph__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(elementary_circuits_directed_graph__WEBPACK_IMPORTED_MODULE_3__); // For a given link, return the target node's depth function targetDepth(d) { return d.target.depth; } // The depth of a node when the nodeAlign (align) is set to 'left' function left(node) { return node.depth; } // The depth of a node when the nodeAlign (align) is set to 'right' function right(node, n) { return n - 1 - node.height; } // The depth of a node when the nodeAlign (align) is set to 'justify' function justify(node, n) { return node.sourceLinks.length ? node.depth : n - 1; } // The depth of a node when the nodeAlign (align) is set to 'center' function center(node) { return node.targetLinks.length ? node.depth : node.sourceLinks.length ? Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* min */ "d"])(node.sourceLinks, targetDepth) - 1 : 0; } // returns a function, using the parameter given to the sankey setting function constant(x) { return function () { return x; }; } var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /// https://github.com/tomshanley/d3-sankeyCircular-circular // sort links' breadth (ie top to bottom in a column), based on their source nodes' breadths function ascendingSourceBreadth(a, b) { return ascendingBreadth(a.source, b.source) || a.index - b.index; } // sort links' breadth (ie top to bottom in a column), based on their target nodes' breadths function ascendingTargetBreadth(a, b) { return ascendingBreadth(a.target, b.target) || a.index - b.index; } // sort nodes' breadth (ie top to bottom in a column) // if both nodes have circular links, or both don't have circular links, then sort by the top (y0) of the node // else push nodes that have top circular links to the top, and nodes that have bottom circular links to the bottom function ascendingBreadth(a, b) { if (a.partOfCycle === b.partOfCycle) { return a.y0 - b.y0; } else { if (a.circularLinkType === 'top' || b.circularLinkType === 'bottom') { return -1; } else { return 1; } } } // return the value of a node or link function value(d) { return d.value; } // return the vertical center of a node function nodeCenter(node) { return (node.y0 + node.y1) / 2; } // return the vertical center of a link's source node function linkSourceCenter(link) { return nodeCenter(link.source); } // return the vertical center of a link's target node function linkTargetCenter(link) { return nodeCenter(link.target); } // Return the default value for ID for node, d.index function defaultId(d) { return d.index; } // Return the default object the graph's nodes, graph.nodes function defaultNodes(graph) { return graph.nodes; } // Return the default object the graph's nodes, graph.links function defaultLinks(graph) { return graph.links; } // Return the node from the collection that matches the provided ID, or throw an error if no match function find(nodeById, id) { var node = nodeById.get(id); if (!node) throw new Error('missing: ' + id); return node; } function getNodeID(node, id) { return id(node); } // The main sankeyCircular functions // Some constants for circular link calculations var verticalMargin = 25; var baseRadius = 10; var scale = 0.3; //Possibly let user control this, although anything over 0.5 starts to get too cramped function sankeyCircular () { // Set the default values var x0 = 0, y0 = 0, x1 = 1, y1 = 1, // extent dx = 24, // nodeWidth py, // nodePadding, for vertical postioning id = defaultId, align = justify, nodes = defaultNodes, links = defaultLinks, iterations = 32, circularLinkGap = 2, paddingRatio, sortNodes = null; function sankeyCircular() { var graph = { nodes: nodes.apply(null, arguments), links: links.apply(null, arguments) // Process the graph's nodes and links, setting their positions // 1. Associate the nodes with their respective links, and vice versa };computeNodeLinks(graph); // 2. Determine which links result in a circular path in the graph identifyCircles(graph, id, sortNodes); // 4. Calculate the nodes' values, based on the values of the incoming and outgoing links computeNodeValues(graph); // 5. Calculate the nodes' depth based on the incoming and outgoing links // Sets the nodes': // - depth: the depth in the graph // - column: the depth (0, 1, 2, etc), as is relates to visual position from left to right // - x0, x1: the x coordinates, as is relates to visual position from left to right computeNodeDepths(graph); // 3. Determine how the circular links will be drawn, // either travelling back above the main chart ("top") // or below the main chart ("bottom") selectCircularLinkTypes(graph, id); // 6. Calculate the nodes' and links' vertical position within their respective column // Also readjusts sankeyCircular size if circular links are needed, and node x's computeNodeBreadths(graph, iterations, id); computeLinkBreadths(graph); // 7. Sort links per node, based on the links' source/target nodes' breadths // 8. Adjust nodes that overlap links that span 2+ columns var linkSortingIterations = 4; //Possibly let user control this number, like the iterations over node placement for (var iteration = 0; iteration < linkSortingIterations; iteration++) { sortSourceLinks(graph, y1, id); sortTargetLinks(graph, y1, id); resolveNodeLinkOverlaps(graph, y0, y1, id); sortSourceLinks(graph, y1, id); sortTargetLinks(graph, y1, id); } // 8.1 Adjust node and link positions back to fill height of chart area if compressed fillHeight(graph, y0, y1); // 9. Calculate visually appealling path for the circular paths, and create the "d" string addCircularPathData(graph, circularLinkGap, y1, id); return graph; } // end of sankeyCircular function // Set the sankeyCircular parameters // nodeID, nodeAlign, nodeWidth, nodePadding, nodes, links, size, extent, iterations, nodePaddingRatio, circularLinkGap sankeyCircular.nodeId = function (_) { return arguments.length ? (id = typeof _ === 'function' ? _ : constant(_), sankeyCircular) : id; }; sankeyCircular.nodeAlign = function (_) { return arguments.length ? (align = typeof _ === 'function' ? _ : constant(_), sankeyCircular) : align; }; sankeyCircular.nodeWidth = function (_) { return arguments.length ? (dx = +_, sankeyCircular) : dx; }; sankeyCircular.nodePadding = function (_) { return arguments.length ? (py = +_, sankeyCircular) : py; }; sankeyCircular.nodes = function (_) { return arguments.length ? (nodes = typeof _ === 'function' ? _ : constant(_), sankeyCircular) : nodes; }; sankeyCircular.links = function (_) { return arguments.length ? (links = typeof _ === 'function' ? _ : constant(_), sankeyCircular) : links; }; sankeyCircular.size = function (_) { return arguments.length ? (x0 = y0 = 0, x1 = +_[0], y1 = +_[1], sankeyCircular) : [x1 - x0, y1 - y0]; }; sankeyCircular.extent = function (_) { return arguments.length ? (x0 = +_[0][0], x1 = +_[1][0], y0 = +_[0][1], y1 = +_[1][1], sankeyCircular) : [[x0, y0], [x1, y1]]; }; sankeyCircular.iterations = function (_) { return arguments.length ? (iterations = +_, sankeyCircular) : iterations; }; sankeyCircular.circularLinkGap = function (_) { return arguments.length ? (circularLinkGap = +_, sankeyCircular) : circularLinkGap; }; sankeyCircular.nodePaddingRatio = function (_) { return arguments.length ? (paddingRatio = +_, sankeyCircular) : paddingRatio; }; sankeyCircular.sortNodes = function (_) { return arguments.length ? (sortNodes = _, sankeyCircular) : sortNodes; }; sankeyCircular.update = function (graph) { // 5. Calculate the nodes' depth based on the incoming and outgoing links // Sets the nodes': // - depth: the depth in the graph // - column: the depth (0, 1, 2, etc), as is relates to visual position from left to right // - x0, x1: the x coordinates, as is relates to visual position from left to right // computeNodeDepths(graph) // 3. Determine how the circular links will be drawn, // either travelling back above the main chart ("top") // or below the main chart ("bottom") selectCircularLinkTypes(graph, id); // 6. Calculate the nodes' and links' vertical position within their respective column // Also readjusts sankeyCircular size if circular links are needed, and node x's // computeNodeBreadths(graph, iterations, id) computeLinkBreadths(graph); // Force position of circular link type based on position graph.links.forEach(function (link) { if (link.circular) { link.circularLinkType = link.y0 + link.y1 < y1 ? 'top' : 'bottom'; link.source.circularLinkType = link.circularLinkType; link.target.circularLinkType = link.circularLinkType; } }); sortSourceLinks(graph, y1, id, false); // Sort links but do not move nodes sortTargetLinks(graph, y1, id); // 7. Sort links per node, based on the links' source/target nodes' breadths // 8. Adjust nodes that overlap links that span 2+ columns // var linkSortingIterations = 4; //Possibly let user control this number, like the iterations over node placement // for (var iteration = 0; iteration < linkSortingIterations; iteration++) { // // sortSourceLinks(graph, y1, id) // sortTargetLinks(graph, y1, id) // resolveNodeLinkOverlaps(graph, y0, y1, id) // sortSourceLinks(graph, y1, id) // sortTargetLinks(graph, y1, id) // // } // 8.1 Adjust node and link positions back to fill height of chart area if compressed // fillHeight(graph, y0, y1) // 9. Calculate visually appealling path for the circular paths, and create the "d" string addCircularPathData(graph, circularLinkGap, y1, id); return graph; }; // Populate the sourceLinks and targetLinks for each node. // Also, if the source and target are not objects, assume they are indices. function computeNodeLinks(graph) { graph.nodes.forEach(function (node, i) { node.index = i; node.sourceLinks = []; node.targetLinks = []; }); var nodeById = Object(d3_collection__WEBPACK_IMPORTED_MODULE_1__[/* map */ "a"])(graph.nodes, id); graph.links.forEach(function (link, i) { link.index = i; var source = link.source; var target = link.target; if ((typeof source === "undefined" ? "undefined" : _typeof(source)) !== 'object') { source = link.source = find(nodeById, source); } if ((typeof target === "undefined" ? "undefined" : _typeof(target)) !== 'object') { target = link.target = find(nodeById, target); } source.sourceLinks.push(link); target.targetLinks.push(link); }); return graph; } // Compute the value (size) and cycleness of each node by summing the associated links. function computeNodeValues(graph) { graph.nodes.forEach(function (node) { node.partOfCycle = false; node.value = Math.max(Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* sum */ "e"])(node.sourceLinks, value), Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* sum */ "e"])(node.targetLinks, value)); node.sourceLinks.forEach(function (link) { if (link.circular) { node.partOfCycle = true; node.circularLinkType = link.circularLinkType; } }); node.targetLinks.forEach(function (link) { if (link.circular) { node.partOfCycle = true; node.circularLinkType = link.circularLinkType; } }); }); } function getCircleMargins(graph) { var totalTopLinksWidth = 0, totalBottomLinksWidth = 0, totalRightLinksWidth = 0, totalLeftLinksWidth = 0; var maxColumn = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* max */ "b"])(graph.nodes, function (node) { return node.column; }); graph.links.forEach(function (link) { if (link.circular) { if (link.circularLinkType == 'top') { totalTopLinksWidth = totalTopLinksWidth + link.width; } else { totalBottomLinksWidth = totalBottomLinksWidth + link.width; } if (link.target.column == 0) { totalLeftLinksWidth = totalLeftLinksWidth + link.width; } if (link.source.column == maxColumn) { totalRightLinksWidth = totalRightLinksWidth + link.width; } } }); //account for radius of curves and padding between links totalTopLinksWidth = totalTopLinksWidth > 0 ? totalTopLinksWidth + verticalMargin + baseRadius : totalTopLinksWidth; totalBottomLinksWidth = totalBottomLinksWidth > 0 ? totalBottomLinksWidth + verticalMargin + baseRadius : totalBottomLinksWidth; totalRightLinksWidth = totalRightLinksWidth > 0 ? totalRightLinksWidth + verticalMargin + baseRadius : totalRightLinksWidth; totalLeftLinksWidth = totalLeftLinksWidth > 0 ? totalLeftLinksWidth + verticalMargin + baseRadius : totalLeftLinksWidth; return { "top": totalTopLinksWidth, "bottom": totalBottomLinksWidth, "left": totalLeftLinksWidth, "right": totalRightLinksWidth }; } // Update the x0, y0, x1 and y1 for the sankeyCircular, to allow space for any circular links function scaleSankeySize(graph, margin) { var maxColumn = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* max */ "b"])(graph.nodes, function (node) { return node.column; }); var currentWidth = x1 - x0; var currentHeight = y1 - y0; var newWidth = currentWidth + margin.right + margin.left; var newHeight = currentHeight + margin.top + margin.bottom; var scaleX = currentWidth / newWidth; var scaleY = currentHeight / newHeight; x0 = x0 * scaleX + margin.left; x1 = margin.right == 0 ? x1 : x1 * scaleX; y0 = y0 * scaleY + margin.top; y1 = y1 * scaleY; graph.nodes.forEach(function (node) { node.x0 = x0 + node.column * ((x1 - x0 - dx) / maxColumn); node.x1 = node.x0 + dx; }); return scaleY; } // Iteratively assign the depth for each node. // Nodes are assigned the maximum depth of incoming neighbors plus one; // nodes with no incoming links are assigned depth zero, while // nodes with no outgoing links are assigned the maximum depth. function computeNodeDepths(graph) { var nodes, next, x; for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) { nodes.forEach(function (node) { node.depth = x; node.sourceLinks.forEach(function (link) { if (next.indexOf(link.target) < 0 && !link.circular) { next.push(link.target); } }); }); } for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) { nodes.forEach(function (node) { node.height = x; node.targetLinks.forEach(function (link) { if (next.indexOf(link.source) < 0 && !link.circular) { next.push(link.source); } }); }); } // assign column numbers, and get max value graph.nodes.forEach(function (node) { node.column = Math.floor(align.call(null, node, x)); }); } // Assign nodes' breadths, and then shift nodes that overlap (resolveCollisions) function computeNodeBreadths(graph, iterations, id) { var columns = Object(d3_collection__WEBPACK_IMPORTED_MODULE_1__[/* nest */ "b"])().key(function (d) { return d.column; }).sortKeys(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* ascending */ "a"]).entries(graph.nodes).map(function (d) { return d.values; }); initializeNodeBreadth(id); resolveCollisions(); for (var alpha = 1, n = iterations; n > 0; --n) { relaxLeftAndRight(alpha *= 0.99, id); resolveCollisions(); } function initializeNodeBreadth(id) { //override py if nodePadding has been set if (paddingRatio) { var padding = Infinity; columns.forEach(function (nodes) { var thisPadding = y1 * paddingRatio / (nodes.length + 1); padding = thisPadding < padding ? thisPadding : padding; }); py = padding; } var ky = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* min */ "d"])(columns, function (nodes) { return (y1 - y0 - (nodes.length - 1) * py) / Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* sum */ "e"])(nodes, value); }); //calculate the widths of the links ky = ky * scale; graph.links.forEach(function (link) { link.width = link.value * ky; }); //determine how much to scale down the chart, based on circular links var margin = getCircleMargins(graph); var ratio = scaleSankeySize(graph, margin); //re-calculate widths ky = ky * ratio; graph.links.forEach(function (link) { link.width = link.value * ky; }); columns.forEach(function (nodes) { var nodesLength = nodes.length; nodes.forEach(function (node, i) { if (node.depth == columns.length - 1 && nodesLength == 1) { node.y0 = y1 / 2 - node.value * ky; node.y1 = node.y0 + node.value * ky; } else if (node.depth == 0 && nodesLength == 1) { node.y0 = y1 / 2 - node.value * ky; node.y1 = node.y0 + node.value * ky; } else if (node.partOfCycle) { if (numberOfNonSelfLinkingCycles(node, id) == 0) { node.y0 = y1 / 2 + i; node.y1 = node.y0 + node.value * ky; } else if (node.circularLinkType == 'top') { node.y0 = y0 + i; node.y1 = node.y0 + node.value * ky; } else { node.y0 = y1 - node.value * ky - i; node.y1 = node.y0 + node.value * ky; } } else { if (margin.top == 0 || margin.bottom == 0) { node.y0 = (y1 - y0) / nodesLength * i; node.y1 = node.y0 + node.value * ky; } else { node.y0 = (y1 - y0) / 2 - nodesLength / 2 + i; node.y1 = node.y0 + node.value * ky; } } }); }); } // For each node in each column, check the node's vertical position in relation to its targets and sources vertical position // and shift up/down to be closer to the vertical middle of those targets and sources function relaxLeftAndRight(alpha, id) { var columnsLength = columns.length; columns.forEach(function (nodes) { var n = nodes.length; var depth = nodes[0].depth; nodes.forEach(function (node) { // check the node is not an orphan var nodeHeight; if (node.sourceLinks.length || node.targetLinks.length) { if (node.partOfCycle && numberOfNonSelfLinkingCycles(node, id) > 0) ; else if (depth == 0 && n == 1) { nodeHeight = node.y1 - node.y0; node.y0 = y1 / 2 - nodeHeight / 2; node.y1 = y1 / 2 + nodeHeight / 2; } else if (depth == columnsLength - 1 && n == 1) { nodeHeight = node.y1 - node.y0; node.y0 = y1 / 2 - nodeHeight / 2; node.y1 = y1 / 2 + nodeHeight / 2; } else { var avg = 0; var avgTargetY = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* mean */ "c"])(node.sourceLinks, linkTargetCenter); var avgSourceY = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* mean */ "c"])(node.targetLinks, linkSourceCenter); if (avgTargetY && avgSourceY) { avg = (avgTargetY + avgSourceY) / 2; } else { avg = avgTargetY || avgSourceY; } var dy = (avg - nodeCenter(node)) * alpha; // positive if it node needs to move down node.y0 += dy; node.y1 += dy; } } }); }); } // For each column, check if nodes are overlapping, and if so, shift up/down function resolveCollisions() { columns.forEach(function (nodes) { var node, dy, y = y0, n = nodes.length, i; // Push any overlapping nodes down. nodes.sort(ascendingBreadth); for (i = 0; i < n; ++i) { node = nodes[i]; dy = y - node.y0; if (dy > 0) { node.y0 += dy; node.y1 += dy; } y = node.y1 + py; } // If the bottommost node goes outside the bounds, push it back up. dy = y - py - y1; if (dy > 0) { y = node.y0 -= dy, node.y1 -= dy; // Push any overlapping nodes back up. for (i = n - 2; i >= 0; --i) { node = nodes[i]; dy = node.y1 + py - y; if (dy > 0) node.y0 -= dy, node.y1 -= dy; y = node.y0; } } }); } } // Assign the links y0 and y1 based on source/target nodes position, // plus the link's relative position to other links to the same node function computeLinkBreadths(graph) { graph.nodes.forEach(function (node) { node.sourceLinks.sort(ascendingTargetBreadth); node.targetLinks.sort(ascendingSourceBreadth); }); graph.nodes.forEach(function (node) { var y0 = node.y0; var y1 = y0; // start from the bottom of the node for cycle links var y0cycle = node.y1; var y1cycle = y0cycle; node.sourceLinks.forEach(function (link) { if (link.circular) { link.y0 = y0cycle - link.width / 2; y0cycle = y0cycle - link.width; } else { link.y0 = y0 + link.width / 2; y0 += link.width; } }); node.targetLinks.forEach(function (link) { if (link.circular) { link.y1 = y1cycle - link.width / 2; y1cycle = y1cycle - link.width; } else { link.y1 = y1 + link.width / 2; y1 += link.width; } }); }); } return sankeyCircular; } /// ///////////////////////////////////////////////////////////////////////////////// // Cycle functions // portion of code to detect circular links based on Colin Fergus' bl.ock https://gist.github.com/cfergus/3956043 // Identify circles in the link objects function identifyCircles(graph, id, sortNodes) { var circularLinkID = 0; if (sortNodes === null) { // Building adjacency graph var adjList = []; for (var i = 0; i < graph.links.length; i++) { var link = graph.links[i]; var source = link.source.index; var target = link.target.index; if (!adjList[source]) adjList[source] = []; if (!adjList[target]) adjList[target] = []; // Add links if not already in set if (adjList[source].indexOf(target) === -1) adjList[source].push(target); } // Find all elementary circuits var cycles = elementary_circuits_directed_graph__WEBPACK_IMPORTED_MODULE_3___default()(adjList); // Sort by circuits length cycles.sort(function (a, b) { return a.length - b.length; }); var circularLinks = {}; for (i = 0; i < cycles.length; i++) { var cycle = cycles[i]; var last = cycle.slice(-2); if (!circularLinks[last[0]]) circularLinks[last[0]] = {}; circularLinks[last[0]][last[1]] = true; } graph.links.forEach(function (link) { var target = link.target.index; var source = link.source.index; // If self-linking or a back-edge if (target === source || circularLinks[source] && circularLinks[source][target]) { link.circular = true; link.circularLinkID = circularLinkID; circularLinkID = circularLinkID + 1; } else { link.circular = false; } }); } else { graph.links.forEach(function (link) { if (link.source[sortNodes] < link.target[sortNodes]) { link.circular = false; } else { link.circular = true; link.circularLinkID = circularLinkID; circularLinkID = circularLinkID + 1; } }); } } // Assign a circular link type (top or bottom), based on: // - if the source/target node already has circular links, then use the same type // - if not, choose the type with fewer links function selectCircularLinkTypes(graph, id) { var numberOfTops = 0; var numberOfBottoms = 0; graph.links.forEach(function (link) { if (link.circular) { // if either souce or target has type already use that if (link.source.circularLinkType || link.target.circularLinkType) { // default to source type if available link.circularLinkType = link.source.circularLinkType ? link.source.circularLinkType : link.target.circularLinkType; } else { link.circularLinkType = numberOfTops < numberOfBottoms ? 'top' : 'bottom'; } if (link.circularLinkType == 'top') { numberOfTops = numberOfTops + 1; } else { numberOfBottoms = numberOfBottoms + 1; } graph.nodes.forEach(function (node) { if (getNodeID(node, id) == getNodeID(link.source, id) || getNodeID(node, id) == getNodeID(link.target, id)) { node.circularLinkType = link.circularLinkType; } }); } }); //correct self-linking links to be same direction as node graph.links.forEach(function (link) { if (link.circular) { //if both source and target node are same type, then link should have same type if (link.source.circularLinkType == link.target.circularLinkType) { link.circularLinkType = link.source.circularLinkType; } //if link is selflinking, then link should have same type as node if (selfLinking(link, id)) { link.circularLinkType = link.source.circularLinkType; } } }); } // Return the angle between a straight line between the source and target of the link, and the vertical plane of the node function linkAngle(link) { var adjacent = Math.abs(link.y1 - link.y0); var opposite = Math.abs(link.target.x0 - link.source.x1); return Math.atan(opposite / adjacent); } // Check if two circular links potentially overlap function circularLinksCross(link1, link2) { if (link1.source.column < link2.target.column) { return false; } else if (link1.target.column > link2.source.column) { return false; } else { return true; } } // Return the number of circular links for node, not including self linking links function numberOfNonSelfLinkingCycles(node, id) { var sourceCount = 0; node.sourceLinks.forEach(function (l) { sourceCount = l.circular && !selfLinking(l, id) ? sourceCount + 1 : sourceCount; }); var targetCount = 0; node.targetLinks.forEach(function (l) { targetCount = l.circular && !selfLinking(l, id) ? targetCount + 1 : targetCount; }); return sourceCount + targetCount; } // Check if a circular link is the only circular link for both its source and target node function onlyCircularLink(link) { var nodeSourceLinks = link.source.sourceLinks; var sourceCount = 0; nodeSourceLinks.forEach(function (l) { sourceCount = l.circular ? sourceCount + 1 : sourceCount; }); var nodeTargetLinks = link.target.targetLinks; var targetCount = 0; nodeTargetLinks.forEach(function (l) { targetCount = l.circular ? targetCount + 1 : targetCount; }); if (sourceCount > 1 || targetCount > 1) { return false; } else { return true; } } // creates vertical buffer values per set of top/bottom links function calcVerticalBuffer(links, circularLinkGap, id) { links.sort(sortLinkColumnAscending); links.forEach(function (link, i) { var buffer = 0; if (selfLinking(link, id) && onlyCircularLink(link)) { link.circularPathData.verticalBuffer = buffer + link.width / 2; } else { var j = 0; for (j; j < i; j++) { if (circularLinksCross(links[i], links[j])) { var bufferOverThisLink = links[j].circularPathData.verticalBuffer + links[j].width / 2 + circularLinkGap; buffer = bufferOverThisLink > buffer ? bufferOverThisLink : buffer; } } link.circularPathData.verticalBuffer = buffer + link.width / 2; } }); return links; } // calculate the optimum path for a link to reduce overlaps function addCircularPathData(graph, circularLinkGap, y1, id) { //var baseRadius = 10 var buffer = 5; //var verticalMargin = 25 var minY = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* min */ "d"])(graph.links, function (link) { return link.source.y0; }); // create object for circular Path Data graph.links.forEach(function (link) { if (link.circular) { link.circularPathData = {}; } }); // calc vertical offsets per top/bottom links var topLinks = graph.links.filter(function (l) { return l.circularLinkType == 'top'; }); /* topLinks = */calcVerticalBuffer(topLinks, circularLinkGap, id); var bottomLinks = graph.links.filter(function (l) { return l.circularLinkType == 'bottom'; }); /* bottomLinks = */calcVerticalBuffer(bottomLinks, circularLinkGap, id); // add the base data for each link graph.links.forEach(function (link) { if (link.circular) { link.circularPathData.arcRadius = link.width + baseRadius; link.circularPathData.leftNodeBuffer = buffer; link.circularPathData.rightNodeBuffer = buffer; link.circularPathData.sourceWidth = link.source.x1 - link.source.x0; link.circularPathData.sourceX = link.source.x0 + link.circularPathData.sourceWidth; link.circularPathData.targetX = link.target.x0; link.circularPathData.sourceY = link.y0; link.circularPathData.targetY = link.y1; // for self linking paths, and that the only circular link in/out of that node if (selfLinking(link, id) && onlyCircularLink(link)) { link.circularPathData.leftSmallArcRadius = baseRadius + link.width / 2; link.circularPathData.leftLargeArcRadius = baseRadius + link.width / 2; link.circularPathData.rightSmallArcRadius = baseRadius + link.width / 2; link.circularPathData.rightLargeArcRadius = baseRadius + link.width / 2; if (link.circularLinkType == 'bottom') { link.circularPathData.verticalFullExtent = link.source.y1 + verticalMargin + link.circularPathData.verticalBuffer; link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.leftLargeArcRadius; link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.rightLargeArcRadius; } else { // top links link.circularPathData.verticalFullExtent = link.source.y0 - verticalMargin - link.circularPathData.verticalBuffer; link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.leftLargeArcRadius; link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.rightLargeArcRadius; } } else { // else calculate normally // add left extent coordinates, based on links with same source column and circularLink type var thisColumn = link.source.column; var thisCircularLinkType = link.circularLinkType; var sameColumnLinks = graph.links.filter(function (l) { return l.source.column == thisColumn && l.circularLinkType == thisCircularLinkType; }); if (link.circularLinkType == 'bottom') { sameColumnLinks.sort(sortLinkSourceYDescending); } else { sameColumnLinks.sort(sortLinkSourceYAscending); } var radiusOffset = 0; sameColumnLinks.forEach(function (l, i) { if (l.circularLinkID == link.circularLinkID) { link.circularPathData.leftSmallArcRadius = baseRadius + link.width / 2 + radiusOffset; link.circularPathData.leftLargeArcRadius = baseRadius + link.width / 2 + i * circularLinkGap + radiusOffset; } radiusOffset = radiusOffset + l.width; }); // add right extent coordinates, based on links with same target column and circularLink type thisColumn = link.target.column; sameColumnLinks = graph.links.filter(function (l) { return l.target.column == thisColumn && l.circularLinkType == thisCircularLinkType; }); if (link.circularLinkType == 'bottom') { sameColumnLinks.sort(sortLinkTargetYDescending); } else { sameColumnLinks.sort(sortLinkTargetYAscending); } radiusOffset = 0; sameColumnLinks.forEach(function (l, i) { if (l.circularLinkID == link.circularLinkID) { link.circularPathData.rightSmallArcRadius = baseRadius + link.width / 2 + radiusOffset; link.circularPathData.rightLargeArcRadius = baseRadius + link.width / 2 + i * circularLinkGap + radiusOffset; } radiusOffset = radiusOffset + l.width; }); // bottom links if (link.circularLinkType == 'bottom') { link.circularPathData.verticalFullExtent = Math.max(y1, link.source.y1, link.target.y1) + verticalMargin + link.circularPathData.verticalBuffer; link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.leftLargeArcRadius; link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.rightLargeArcRadius; } else { // top links link.circularPathData.verticalFullExtent = minY - verticalMargin - link.circularPathData.verticalBuffer; link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.leftLargeArcRadius; link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.rightLargeArcRadius; } } // all links link.circularPathData.leftInnerExtent = link.circularPathData.sourceX + link.circularPathData.leftNodeBuffer; link.circularPathData.rightInnerExtent = link.circularPathData.targetX - link.circularPathData.rightNodeBuffer; link.circularPathData.leftFullExtent = link.circularPathData.sourceX + link.circularPathData.leftLargeArcRadius + link.circularPathData.leftNodeBuffer; link.circularPathData.rightFullExtent = link.circularPathData.targetX - link.circularPathData.rightLargeArcRadius - link.circularPathData.rightNodeBuffer; } if (link.circular) { link.path = createCircularPathString(link); } else { var normalPath = Object(d3_shape__WEBPACK_IMPORTED_MODULE_2__[/* linkHorizontal */ "a"])().source(function (d) { var x = d.source.x0 + (d.source.x1 - d.source.x0); var y = d.y0; return [x, y]; }).target(function (d) { var x = d.target.x0; var y = d.y1; return [x, y]; }); link.path = normalPath(link); } }); } // create a d path using the addCircularPathData function createCircularPathString(link) { var pathString = ''; // 'pathData' is assigned a value but never used // var pathData = {} if (link.circularLinkType == 'top') { pathString = // start at the right of the source node 'M' + link.circularPathData.sourceX + ' ' + link.circularPathData.sourceY + ' ' + // line right to buffer point 'L' + link.circularPathData.leftInnerExtent + ' ' + link.circularPathData.sourceY + ' ' + // Arc around: Centre of arc X and //Centre of arc Y 'A' + link.circularPathData.leftLargeArcRadius + ' ' + link.circularPathData.leftSmallArcRadius + ' 0 0 0 ' + // End of arc X //End of arc Y link.circularPathData.leftFullExtent + ' ' + (link.circularPathData.sourceY - link.circularPathData.leftSmallArcRadius) + ' ' + // End of arc X // line up to buffer point 'L' + link.circularPathData.leftFullExtent + ' ' + link.circularPathData.verticalLeftInnerExtent + ' ' + // Arc around: Centre of arc X and //Centre of arc Y 'A' + link.circularPathData.leftLargeArcRadius + ' ' + link.circularPathData.leftLargeArcRadius + ' 0 0 0 ' + // End of arc X //End of arc Y link.circularPathData.leftInnerExtent + ' ' + link.circularPathData.verticalFullExtent + ' ' + // End of arc X // line left to buffer point 'L' + link.circularPathData.rightInnerExtent + ' ' + link.circularPathData.verticalFullExtent + ' ' + // Arc around: Centre of arc X and //Centre of arc Y 'A' + link.circularPathData.rightLargeArcRadius + ' ' + link.circularPathData.rightLargeArcRadius + ' 0 0 0 ' + // End of arc X //End of arc Y link.circularPathData.rightFullExtent + ' ' + link.circularPathData.verticalRightInnerExtent + ' ' + // End of arc X // line down 'L' + link.circularPathData.rightFullExtent + ' ' + (link.circularPathData.targetY - link.circularPathData.rightSmallArcRadius) + ' ' + // Arc around: Centre of arc X and //Centre of arc Y 'A' + link.circularPathData.rightLargeArcRadius + ' ' + link.circularPathData.rightSmallArcRadius + ' 0 0 0 ' + // End of arc X //End of arc Y link.circularPathData.rightInnerExtent + ' ' + link.circularPathData.targetY + ' ' + // End of arc X // line to end 'L' + link.circularPathData.targetX + ' ' + link.circularPathData.targetY; } else { // bottom path pathString = // start at the right of the source node 'M' + link.circularPathData.sourceX + ' ' + link.circularPathData.sourceY + ' ' + // line right to buffer point 'L' + link.circularPathData.leftInnerExtent + ' ' + link.circularPathData.sourceY + ' ' + // Arc around: Centre of arc X and //Centre of arc Y 'A' + link.circularPathData.leftLargeArcRadius + ' ' + link.circularPathData.leftSmallArcRadius + ' 0 0 1 ' + // End of arc X //End of arc Y link.circularPathData.leftFullExtent + ' ' + (link.circularPathData.sourceY + link.circularPathData.leftSmallArcRadius) + ' ' + // End of arc X // line down to buffer point 'L' + link.circularPathData.leftFullExtent + ' ' + link.circularPathData.verticalLeftInnerExtent + ' ' + // Arc around: Centre of arc X and //Centre of arc Y 'A' + link.circularPathData.leftLargeArcRadius + ' ' + link.circularPathData.leftLargeArcRadius + ' 0 0 1 ' + // End of arc X //End of arc Y link.circularPathData.leftInnerExtent + ' ' + link.circularPathData.verticalFullExtent + ' ' + // End of arc X // line left to buffer point 'L' + link.circularPathData.rightInnerExtent + ' ' + link.circularPathData.verticalFullExtent + ' ' + // Arc around: Centre of arc X and //Centre of arc Y 'A' + link.circularPathData.rightLargeArcRadius + ' ' + link.circularPathData.rightLargeArcRadius + ' 0 0 1 ' + // End of arc X //End of arc Y link.circularPathData.rightFullExtent + ' ' + link.circularPathData.verticalRightInnerExtent + ' ' + // End of arc X // line up 'L' + link.circularPathData.rightFullExtent + ' ' + (link.circularPathData.targetY + link.circularPathData.rightSmallArcRadius) + ' ' + // Arc around: Centre of arc X and //Centre of arc Y 'A' + link.circularPathData.rightLargeArcRadius + ' ' + link.circularPathData.rightSmallArcRadius + ' 0 0 1 ' + // End of arc X //End of arc Y link.circularPathData.rightInnerExtent + ' ' + link.circularPathData.targetY + ' ' + // End of arc X // line to end 'L' + link.circularPathData.targetX + ' ' + link.circularPathData.targetY; } return pathString; } // sort links based on the distance between the source and tartget node columns // if the same, then use Y position of the source node function sortLinkColumnAscending(link1, link2) { if (linkColumnDistance(link1) == linkColumnDistance(link2)) { return link1.circularLinkType == 'bottom' ? sortLinkSourceYDescending(link1, link2) : sortLinkSourceYAscending(link1, link2); } else { return linkColumnDistance(link2) - linkColumnDistance(link1); } } // sort ascending links by their source vertical position, y0 function sortLinkSourceYAscending(link1, link2) { return link1.y0 - link2.y0; } // sort descending links by their source vertical position, y0 function sortLinkSourceYDescending(link1, link2) { return link2.y0 - link1.y0; } // sort ascending links by their target vertical position, y1 function sortLinkTargetYAscending(link1, link2) { return link1.y1 - link2.y1; } // sort descending links by their target vertical position, y1 function sortLinkTargetYDescending(link1, link2) { return link2.y1 - link1.y1; } // return the distance between the link's target and source node, in terms of the nodes' column function linkColumnDistance(link) { return link.target.column - link.source.column; } // return the distance between the link's target and source node, in terms of the nodes' X coordinate function linkXLength(link) { return link.target.x0 - link.source.x1; } // Return the Y coordinate on the longerLink path * which is perpendicular shorterLink's source. // * approx, based on a straight line from target to source, when in fact the path is a bezier function linkPerpendicularYToLinkSource(longerLink, shorterLink) { // get the angle for the longer link var angle = linkAngle(longerLink); // get the adjacent length to the other link's x position var heightFromY1ToPependicular = linkXLength(shorterLink) / Math.tan(angle); // add or subtract from longer link1's original y1, depending on the slope var yPerpendicular = incline(longerLink) == 'up' ? longerLink.y1 + heightFromY1ToPependicular : longerLink.y1 - heightFromY1ToPependicular; return yPerpendicular; } // Return the Y coordinate on the longerLink path * which is perpendicular shorterLink's source. // * approx, based on a straight line from target to source, when in fact the path is a bezier function linkPerpendicularYToLinkTarget(longerLink, shorterLink) { // get the angle for the longer link var angle = linkAngle(longerLink); // get the adjacent length to the other link's x position var heightFromY1ToPependicular = linkXLength(shorterLink) / Math.tan(angle); // add or subtract from longer link's original y1, depending on the slope var yPerpendicular = incline(longerLink) == 'up' ? longerLink.y1 - heightFromY1ToPependicular : longerLink.y1 + heightFromY1ToPependicular; return yPerpendicular; } // Move any nodes that overlap links which span 2+ columns function resolveNodeLinkOverlaps(graph, y0, y1, id) { graph.links.forEach(function (link) { if (link.circular) { return; } if (link.target.column - link.source.column > 1) { var columnToTest = link.source.column + 1; var maxColumnToTest = link.target.column - 1; var i = 1; var numberOfColumnsToTest = maxColumnToTest - columnToTest + 1; for (i = 1; columnToTest <= maxColumnToTest; columnToTest++, i++) { graph.nodes.forEach(function (node) { if (node.column == columnToTest) { var t = i / (numberOfColumnsToTest + 1); // Find all the points of a cubic bezier curve in javascript // https://stackoverflow.com/questions/15397596/find-all-the-points-of-a-cubic-bezier-curve-in-javascript var B0_t = Math.pow(1 - t, 3); var B1_t = 3 * t * Math.pow(1 - t, 2); var B2_t = 3 * Math.pow(t, 2) * (1 - t); var B3_t = Math.pow(t, 3); var py_t = B0_t * link.y0 + B1_t * link.y0 + B2_t * link.y1 + B3_t * link.y1; var linkY0AtColumn = py_t - link.width / 2; var linkY1AtColumn = py_t + link.width / 2; var dy; // If top of link overlaps node, push node up if (linkY0AtColumn > node.y0 && linkY0AtColumn < node.y1) { dy = node.y1 - linkY0AtColumn + 10; dy = node.circularLinkType == 'bottom' ? dy : -dy; node = adjustNodeHeight(node, dy, y0, y1); // check if other nodes need to move up too graph.nodes.forEach(function (otherNode) { // don't need to check itself or nodes at different columns if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) { return; } if (nodesOverlap(node, otherNode)) { adjustNodeHeight(otherNode, dy, y0, y1); } }); } else if (linkY1AtColumn > node.y0 && linkY1AtColumn < node.y1) { // If bottom of link overlaps node, push node down dy = linkY1AtColumn - node.y0 + 10; node = adjustNodeHeight(node, dy, y0, y1); // check if other nodes need to move down too graph.nodes.forEach(function (otherNode) { // don't need to check itself or nodes at different columns if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) { return; } if (otherNode.y0 < node.y1 && otherNode.y1 > node.y1) { adjustNodeHeight(otherNode, dy, y0, y1); } }); } else if (linkY0AtColumn < node.y0 && linkY1AtColumn > node.y1) { // if link completely overlaps node dy = linkY1AtColumn - node.y0 + 10; node = adjustNodeHeight(node, dy, y0, y1); graph.nodes.forEach(function (otherNode) { // don't need to check itself or nodes at different columns if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) { return; } if (otherNode.y0 < node.y1 && otherNode.y1 > node.y1) { adjustNodeHeight(otherNode, dy, y0, y1); } }); } } }); } } }); } // check if two nodes overlap function nodesOverlap(nodeA, nodeB) { // test if nodeA top partially overlaps nodeB if (nodeA.y0 > nodeB.y0 && nodeA.y0 < nodeB.y1) { return true; } else if (nodeA.y1 > nodeB.y0 && nodeA.y1 < nodeB.y1) { // test if nodeA bottom partially overlaps nodeB return true; } else if (nodeA.y0 < nodeB.y0 && nodeA.y1 > nodeB.y1) { // test if nodeA covers nodeB return true; } else { return false; } } // update a node, and its associated links, vertical positions (y0, y1) function adjustNodeHeight(node, dy, sankeyY0, sankeyY1) { if (node.y0 + dy >= sankeyY0 && node.y1 + dy <= sankeyY1) { node.y0 = node.y0 + dy; node.y1 = node.y1 + dy; node.targetLinks.forEach(function (l) { l.y1 = l.y1 + dy; }); node.sourceLinks.forEach(function (l) { l.y0 = l.y0 + dy; }); } return node; } // sort and set the links' y0 for each node function sortSourceLinks(graph, y1, id, moveNodes) { graph.nodes.forEach(function (node) { // move any nodes up which are off the bottom if (moveNodes && node.y + (node.y1 - node.y0) > y1) { node.y = node.y - (node.y + (node.y1 - node.y0) - y1); } var nodesSourceLinks = graph.links.filter(function (l) { return getNodeID(l.source, id) == getNodeID(node, id); }); var nodeSourceLinksLength = nodesSourceLinks.length; // if more than 1 link then sort if (nodeSourceLinksLength > 1) { nodesSourceLinks.sort(function (link1, link2) { // if both are not circular... if (!link1.circular && !link2.circular) { // if the target nodes are the same column, then sort by the link's target y if (link1.target.column == link2.target.column) { return link1.y1 - link2.y1; } else if (!sameInclines(link1, link2)) { // if the links slope in different directions, then sort by the link's target y return link1.y1 - link2.y1; // if the links slope in same directions, then sort by any overlap } else { if (link1.target.column > link2.target.column) { var link2Adj = linkPerpendicularYToLinkTarget(link2, link1); return link1.y1 - link2Adj; } if (link2.target.column > link1.target.column) { var link1Adj = linkPerpendicularYToLinkTarget(link1, link2); return link1Adj - link2.y1; } } } // if only one is circular, the move top links up, or bottom links down if (link1.circular && !link2.circular) { return link1.circularLinkType == 'top' ? -1 : 1; } else if (link2.circular && !link1.circular) { return link2.circularLinkType == 'top' ? 1 : -1; } // if both links are circular... if (link1.circular && link2.circular) { // ...and they both loop the same way (both top) if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == 'top') { // ...and they both connect to a target with same column, then sort by the target's y if (link1.target.column === link2.target.column) { return link1.target.y1 - link2.target.y1; } else { // ...and they connect to different column targets, then sort by how far back they return link2.target.column - link1.target.column; } } else if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == 'bottom') { // ...and they both loop the same way (both bottom) // ...and they both connect to a target with same column, then sort by the target's y if (link1.target.column === link2.target.column) { return link2.target.y1 - link1.target.y1; } else { // ...and they connect to different column targets, then sort by how far back they return link1.target.column - link2.target.column; } } else { // ...and they loop around different ways, the move top up and bottom down return link1.circularLinkType == 'top' ? -1 : 1; } } }); } // update y0 for links var ySourceOffset = node.y0; nodesSourceLinks.forEach(function (link) { link.y0 = ySourceOffset + link.width / 2; ySourceOffset = ySourceOffset + link.width; }); // correct any circular bottom links so they are at the bottom of the node nodesSourceLinks.forEach(function (link, i) { if (link.circularLinkType == 'bottom') { var j = i + 1; var offsetFromBottom = 0; // sum the widths of any links that are below this link for (j; j < nodeSourceLinksLength; j++) { offsetFromBottom = offsetFromBottom + nodesSourceLinks[j].width; } link.y0 = node.y1 - offsetFromBottom - link.width / 2; } }); }); } // sort and set the links' y1 for each node function sortTargetLinks(graph, y1, id) { graph.nodes.forEach(function (node) { var nodesTargetLinks = graph.links.filter(function (l) { return getNodeID(l.target, id) == getNodeID(node, id); }); var nodesTargetLinksLength = nodesTargetLinks.length; if (nodesTargetLinksLength > 1) { nodesTargetLinks.sort(function (link1, link2) { // if both are not circular, the base on the source y position if (!link1.circular && !link2.circular) { if (link1.source.column == link2.source.column) { return link1.y0 - link2.y0; } else if (!sameInclines(link1, link2)) { return link1.y0 - link2.y0; } else { // get the angle of the link to the further source node (ie the smaller column) if (link2.source.column < link1.source.column) { var link2Adj = linkPerpendicularYToLinkSource(link2, link1); return link1.y0 - link2Adj; } if (link1.source.column < link2.source.column) { var link1Adj = linkPerpendicularYToLinkSource(link1, link2); return link1Adj - link2.y0; } } } // if only one is circular, the move top links up, or bottom links down if (link1.circular && !link2.circular) { return link1.circularLinkType == 'top' ? -1 : 1; } else if (link2.circular && !link1.circular) { return link2.circularLinkType == 'top' ? 1 : -1; } // if both links are circular... if (link1.circular && link2.circular) { // ...and they both loop the same way (both top) if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == 'top') { // ...and they both connect to a target with same column, then sort by the target's y if (link1.source.column === link2.source.column) { return link1.source.y1 - link2.source.y1; } else { // ...and they connect to different column targets, then sort by how far back they return link1.source.column - link2.source.column; } } else if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == 'bottom') { // ...and they both loop the same way (both bottom) // ...and they both connect to a target with same column, then sort by the target's y if (link1.source.column === link2.source.column) { return link1.source.y1 - link2.source.y1; } else { // ...and they connect to different column targets, then sort by how far back they return link2.source.column - link1.source.column; } } else { // ...and they loop around different ways, the move top up and bottom down return link1.circularLinkType == 'top' ? -1 : 1; } } }); } // update y1 for links var yTargetOffset = node.y0; nodesTargetLinks.forEach(function (link) { link.y1 = yTargetOffset + link.width / 2; yTargetOffset = yTargetOffset + link.width; }); // correct any circular bottom links so they are at the bottom of the node nodesTargetLinks.forEach(function (link, i) { if (link.circularLinkType == 'bottom') { var j = i + 1; var offsetFromBottom = 0; // sum the widths of any links that are below this link for (j; j < nodesTargetLinksLength; j++) { offsetFromBottom = offsetFromBottom + nodesTargetLinks[j].width; } link.y1 = node.y1 - offsetFromBottom - link.width / 2; } }); }); } // test if links both slope up, or both slope down function sameInclines(link1, link2) { return incline(link1) == incline(link2); } // returns the slope of a link, from source to target // up => slopes up from source to target // down => slopes down from source to target function incline(link) { return link.y0 - link.y1 > 0 ? 'up' : 'down'; } // check if link is self linking, ie links a node to the same node function selfLinking(link, id) { return getNodeID(link.source, id) == getNodeID(link.target, id); } function fillHeight(graph, y0, y1) { var nodes = graph.nodes; var links = graph.links; var top = false; var bottom = false; links.forEach(function (link) { if (link.circularLinkType == "top") { top = true; } else if (link.circularLinkType == "bottom") { bottom = true; } }); if (top == false || bottom == false) { var minY0 = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* min */ "d"])(nodes, function (node) { return node.y0; }); var maxY1 = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* max */ "b"])(nodes, function (node) { return node.y1; }); var currentHeight = maxY1 - minY0; var chartHeight = y1 - y0; var ratio = chartHeight / currentHeight; nodes.forEach(function (node) { var nodeHeight = (node.y1 - node.y0) * ratio; node.y0 = (node.y0 - minY0) * ratio; node.y1 = node.y0 + nodeHeight; }); links.forEach(function (link) { link.y0 = (link.y0 - minY0) * ratio; link.y1 = (link.y1 - minY0) * ratio; link.width = link.width * ratio; }); } } /***/ }), /***/ "2e3d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // 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; }; /***/ }), /***/ "2e46": /***/ (function(module, exports, __webpack_require__) { "use strict"; function compileSearch(funcName, predicate, reversed, extraArgs, useNdarray, earlyOut) { var code = [ "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), ";while(l<=h){\ var m=(l+h)>>>1,x=a", useNdarray ? ".get(m)" : "[m]"] if(earlyOut) { if(predicate.indexOf("c") < 0) { code.push(";if(x===y){return m}else if(x<=y){") } else { code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){") } } else { code.push(";if(", predicate, "){i=m;") } if(reversed) { code.push("l=m+1}else{h=m-1}") } else { code.push("h=m-1}else{l=m+1}") } code.push("}") if(earlyOut) { code.push("return -1};") } else { code.push("return i};") } return code.join("") } function compileBoundsSearch(predicate, reversed, suffix, earlyOut) { var result = new Function([ compileSearch("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut), compileSearch("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut), compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut), compileSearch("Q", "c(x,y)" + predicate + "0", reversed, ["y", "c"], true, earlyOut), "function dispatchBsearch", suffix, "(a,y,c,l,h){\ if(a.shape){\ if(typeof(c)==='function'){\ return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)\ }else{\ return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)\ }}else{\ if(typeof(c)==='function'){\ return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)\ }else{\ return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)\ }}}\ return dispatchBsearch", suffix].join("")) return result() } module.exports = { ge: compileBoundsSearch(">=", false, "GE"), gt: compileBoundsSearch(">", false, "GT"), lt: compileBoundsSearch("<", true, "LT"), le: compileBoundsSearch("<=", true, "LE"), eq: compileBoundsSearch("-", true, "EQ", true) } /***/ }), /***/ "2ee6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isTypedArray = __webpack_require__("fc26").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); }; /***/ }), /***/ "2f03": /***/ (function(module, exports) { // Copyright (C) 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Install a leaky WeakMap emulation on platforms that * don't provide a built-in one. * *

Assumes that an ES5 platform where, if {@code WeakMap} is * already present, then it conforms to the anticipated ES6 * specification. To run this file on an ES5 or almost ES5 * implementation where the {@code WeakMap} specification does not * quite conform, run repairES5.js first. * *

Even though WeakMapModule is not global, the linter thinks it * is, which is why it is in the overrides list below. * *

NOTE: Before using this WeakMap emulation in a non-SES * environment, see the note below about hiddenRecord. * * @author Mark S. Miller * @requires crypto, ArrayBuffer, Uint8Array, navigator, console * @overrides WeakMap, ses, Proxy * @overrides WeakMapModule */ /** * This {@code WeakMap} emulation is observably equivalent to the * ES-Harmony WeakMap, but with leakier garbage collection properties. * *

As with true WeakMaps, in this emulation, a key does not * retain maps indexed by that key and (crucially) a map does not * retain the keys it indexes. A map by itself also does not retain * the values associated with that map. * *

However, the values associated with a key in some map are * retained so long as that key is retained and those associations are * not overridden. For example, when used to support membranes, all * values exported from a given membrane will live for the lifetime * they would have had in the absence of an interposed membrane. Even * when the membrane is revoked, all objects that would have been * reachable in the absence of revocation will still be reachable, as * far as the GC can tell, even though they will no longer be relevant * to ongoing computation. * *

The API implemented here is approximately the API as implemented * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman, * rather than the offially approved proposal page. TODO(erights): * upgrade the ecmascript WeakMap proposal page to explain this API * change and present to EcmaScript committee for their approval. * *

The first difference between the emulation here and that in * FF6.0a1 is the presence of non enumerable {@code get___, has___, * set___, and delete___} methods on WeakMap instances to represent * what would be the hidden internal properties of a primitive * implementation. Whereas the FF6.0a1 WeakMap.prototype methods * require their {@code this} to be a genuine WeakMap instance (i.e., * an object of {@code [[Class]]} "WeakMap}), since there is nothing * unforgeable about the pseudo-internal method names used here, * nothing prevents these emulated prototype methods from being * applied to non-WeakMaps with pseudo-internal methods of the same * names. * *

Another difference is that our emulated {@code * WeakMap.prototype} is not itself a WeakMap. A problem with the * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap * providing ambient mutability and an ambient communications * channel. Thus, if a WeakMap is already present and has this * problem, repairES5.js wraps it in a safe wrappper in order to * prevent access to this channel. (See * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js). */ /** * If this is a full secureable ES5 platform and the ES-Harmony {@code WeakMap} is * absent, install an approximate emulation. * *

If WeakMap is present but cannot store some objects, use our approximate * emulation as a wrapper. * *

If this is almost a secureable ES5 platform, then WeakMap.js * should be run after repairES5.js. * *

See {@code WeakMap} for documentation of the garbage collection * properties of this WeakMap emulation. */ (function WeakMapModule() { "use strict"; if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) { // already too broken, so give up return; } /** * In some cases (current Firefox), we must make a choice betweeen a * WeakMap which is capable of using all varieties of host objects as * keys and one which is capable of safely using proxies as keys. See * comments below about HostWeakMap and DoubleWeakMap for details. * * This function (which is a global, not exposed to guests) marks a * WeakMap as permitted to do what is necessary to index all host * objects, at the cost of making it unsafe for proxies. * * Do not apply this function to anything which is not a genuine * fresh WeakMap. */ function weakMapPermitHostObjects(map) { // identity of function used as a secret -- good enough and cheap if (map.permitHostObjects___) { map.permitHostObjects___(weakMapPermitHostObjects); } } if (typeof ses !== 'undefined') { ses.weakMapPermitHostObjects = weakMapPermitHostObjects; } // IE 11 has no Proxy but has a broken WeakMap such that we need to patch // it using DoubleWeakMap; this flag tells DoubleWeakMap so. var doubleWeakMapCheckSilentFailure = false; // Check if there is already a good-enough WeakMap implementation, and if so // exit without replacing it. if (typeof WeakMap === 'function') { var HostWeakMap = WeakMap; // There is a WeakMap -- is it good enough? if (typeof navigator !== 'undefined' && /Firefox/.test(navigator.userAgent)) { // We're now *assuming not*, because as of this writing (2013-05-06) // Firefox's WeakMaps have a miscellany of objects they won't accept, and // we don't want to make an exhaustive list, and testing for just one // will be a problem if that one is fixed alone (as they did for Event). // If there is a platform that we *can* reliably test on, here's how to // do it: // var problematic = ... ; // var testHostMap = new HostWeakMap(); // try { // testHostMap.set(problematic, 1); // Firefox 20 will throw here // if (testHostMap.get(problematic) === 1) { // return; // } // } catch (e) {} } else { // IE 11 bug: WeakMaps silently fail to store frozen objects. var testMap = new HostWeakMap(); var testObject = Object.freeze({}); testMap.set(testObject, 1); if (testMap.get(testObject) !== 1) { doubleWeakMapCheckSilentFailure = true; // Fall through to installing our WeakMap. } else { module.exports = WeakMap; return; } } } var hop = Object.prototype.hasOwnProperty; var gopn = Object.getOwnPropertyNames; var defProp = Object.defineProperty; var isExtensible = Object.isExtensible; /** * Security depends on HIDDEN_NAME being both unguessable and * undiscoverable by untrusted code. * *

Given the known weaknesses of Math.random() on existing * browsers, it does not generate unguessability we can be confident * of. * *

It is the monkey patching logic in this file that is intended * to ensure undiscoverability. The basic idea is that there are * three fundamental means of discovering properties of an object: * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(), * as well as some proposed ES6 extensions that appear on our * whitelist. The first two only discover enumerable properties, and * we only use HIDDEN_NAME to name a non-enumerable property, so the * only remaining threat should be getOwnPropertyNames and some * proposed ES6 extensions that appear on our whitelist. We monkey * patch them to remove HIDDEN_NAME from the list of properties they * returns. * *

TODO(erights): On a platform with built-in Proxies, proxies * could be used to trap and thereby discover the HIDDEN_NAME, so we * need to monkey patch Proxy.create, Proxy.createFunction, etc, in * order to wrap the provided handler with the real handler which * filters out all traps using HIDDEN_NAME. * *

TODO(erights): Revisit Mike Stay's suggestion that we use an * encapsulated function at a not-necessarily-secret name, which * uses the Stiegler shared-state rights amplification pattern to * reveal the associated value only to the WeakMap in which this key * is associated with that value. Since only the key retains the * function, the function can also remember the key without causing * leakage of the key, so this doesn't violate our general gc * goals. In addition, because the name need not be a guarded * secret, we could efficiently handle cross-frame frozen keys. */ var HIDDEN_NAME_PREFIX = 'weakmap:'; var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___'; if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function' && typeof ArrayBuffer === 'function' && typeof Uint8Array === 'function') { var ab = new ArrayBuffer(25); var u8s = new Uint8Array(ab); crypto.getRandomValues(u8s); HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' + Array.prototype.map.call(u8s, function(u8) { return (u8 % 36).toString(36); }).join('') + '___'; } function isNotHiddenName(name) { return !( name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && name.substr(name.length - 3) === '___'); } /** * Monkey patch getOwnPropertyNames to avoid revealing the * HIDDEN_NAME. * *

The ES5.1 spec requires each name to appear only once, but as * of this writing, this requirement is controversial for ES6, so we * made this code robust against this case. If the resulting extra * search turns out to be expensive, we can probably relax this once * ES6 is adequately supported on all major browsers, iff no browser * versions we support at that time have relaxed this constraint * without providing built-in ES6 WeakMaps. */ defProp(Object, 'getOwnPropertyNames', { value: function fakeGetOwnPropertyNames(obj) { return gopn(obj).filter(isNotHiddenName); } }); /** * getPropertyNames is not in ES5 but it is proposed for ES6 and * does appear in our whitelist, so we need to clean it too. */ if ('getPropertyNames' in Object) { var originalGetPropertyNames = Object.getPropertyNames; defProp(Object, 'getPropertyNames', { value: function fakeGetPropertyNames(obj) { return originalGetPropertyNames(obj).filter(isNotHiddenName); } }); } /** *

To treat objects as identity-keys with reasonable efficiency * on ES5 by itself (i.e., without any object-keyed collections), we * need to add a hidden property to such key objects when we * can. This raises several issues: *

    *
  • Arranging to add this property to objects before we lose the * chance, and *
  • Hiding the existence of this new property from most * JavaScript code. *
  • Preventing certification theft, where one object is * created falsely claiming to be the key of an association * actually keyed by another object. *
  • Preventing value theft, where untrusted code with * access to a key object but not a weak map nevertheless * obtains access to the value associated with that key in that * weak map. *
* We do so by *
    *
  • Making the name of the hidden property unguessable, so "[]" * indexing, which we cannot intercept, cannot be used to access * a property without knowing the name. *
  • Making the hidden property non-enumerable, so we need not * worry about for-in loops or {@code Object.keys}, *
  • monkey patching those reflective methods that would * prevent extensions, to add this hidden property first, *
  • monkey patching those methods that would reveal this * hidden property. *
* Unfortunately, because of same-origin iframes, we cannot reliably * add this hidden property before an object becomes * non-extensible. Instead, if we encounter a non-extensible object * without a hidden record that we can detect (whether or not it has * a hidden record stored under a name secret to us), then we just * use the key object itself to represent its identity in a brute * force leaky map stored in the weak map, losing all the advantages * of weakness for these. */ function getHiddenRecord(key) { if (key !== Object(key)) { throw new TypeError('Not an object: ' + key); } var hiddenRecord = key[HIDDEN_NAME]; if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; } if (!isExtensible(key)) { // Weak map must brute force, as explained in doc-comment above. return void 0; } // The hiddenRecord and the key point directly at each other, via // the "key" and HIDDEN_NAME properties respectively. The key // field is for quickly verifying that this hidden record is an // own property, not a hidden record from up the prototype chain. // // NOTE: Because this WeakMap emulation is meant only for systems like // SES where Object.prototype is frozen without any numeric // properties, it is ok to use an object literal for the hiddenRecord. // This has two advantages: // * It is much faster in a performance critical place // * It avoids relying on Object.create(null), which had been // problematic on Chrome 28.0.1480.0. See // https://code.google.com/p/google-caja/issues/detail?id=1687 hiddenRecord = { key: key }; // When using this WeakMap emulation on platforms where // Object.prototype might not be frozen and Object.create(null) is // reliable, use the following two commented out lines instead. // hiddenRecord = Object.create(null); // hiddenRecord.key = key; // Please contact us if you need this to work on platforms where // Object.prototype might not be frozen and // Object.create(null) might not be reliable. try { defProp(key, HIDDEN_NAME, { value: hiddenRecord, writable: false, enumerable: false, configurable: false }); return hiddenRecord; } catch (error) { // Under some circumstances, isExtensible seems to misreport whether // the HIDDEN_NAME can be defined. // The circumstances have not been isolated, but at least affect // Node.js v0.10.26 on TravisCI / Linux, but not the same version of // Node.js on OS X. return void 0; } } /** * Monkey patch operations that would make their argument * non-extensible. * *

The monkey patched versions throw a TypeError if their * argument is not an object, so it should only be done to functions * that should throw a TypeError anyway if their argument is not an * object. */ (function(){ var oldFreeze = Object.freeze; defProp(Object, 'freeze', { value: function identifyingFreeze(obj) { getHiddenRecord(obj); return oldFreeze(obj); } }); var oldSeal = Object.seal; defProp(Object, 'seal', { value: function identifyingSeal(obj) { getHiddenRecord(obj); return oldSeal(obj); } }); var oldPreventExtensions = Object.preventExtensions; defProp(Object, 'preventExtensions', { value: function identifyingPreventExtensions(obj) { getHiddenRecord(obj); return oldPreventExtensions(obj); } }); })(); function constFunc(func) { func.prototype = null; return Object.freeze(func); } var calledAsFunctionWarningDone = false; function calledAsFunctionWarning() { // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap() // but we used to permit it and do it ourselves, so warn only. if (!calledAsFunctionWarningDone && typeof console !== 'undefined') { calledAsFunctionWarningDone = true; console.warn('WeakMap should be invoked as new WeakMap(), not ' + 'WeakMap(). This will be an error in the future.'); } } var nextId = 0; var OurWeakMap = function() { if (!(this instanceof OurWeakMap)) { // approximate test for new ...() calledAsFunctionWarning(); } // We are currently (12/25/2012) never encountering any prematurely // non-extensible keys. var keys = []; // brute force for prematurely non-extensible keys. var values = []; // brute force for corresponding values. var id = nextId++; function get___(key, opt_default) { var index; var hiddenRecord = getHiddenRecord(key); if (hiddenRecord) { return id in hiddenRecord ? hiddenRecord[id] : opt_default; } else { index = keys.indexOf(key); return index >= 0 ? values[index] : opt_default; } } function has___(key) { var hiddenRecord = getHiddenRecord(key); if (hiddenRecord) { return id in hiddenRecord; } else { return keys.indexOf(key) >= 0; } } function set___(key, value) { var index; var hiddenRecord = getHiddenRecord(key); if (hiddenRecord) { hiddenRecord[id] = value; } else { index = keys.indexOf(key); if (index >= 0) { values[index] = value; } else { // Since some browsers preemptively terminate slow turns but // then continue computing with presumably corrupted heap // state, we here defensively get keys.length first and then // use it to update both the values and keys arrays, keeping // them in sync. index = keys.length; values[index] = value; // If we crash here, values will be one longer than keys. keys[index] = key; } } return this; } function delete___(key) { var hiddenRecord = getHiddenRecord(key); var index, lastIndex; if (hiddenRecord) { return id in hiddenRecord && delete hiddenRecord[id]; } else { index = keys.indexOf(key); if (index < 0) { return false; } // Since some browsers preemptively terminate slow turns but // then continue computing with potentially corrupted heap // state, we here defensively get keys.length first and then use // it to update both the keys and the values array, keeping // them in sync. We update the two with an order of assignments, // such that any prefix of these assignments will preserve the // key/value correspondence, either before or after the delete. // Note that this needs to work correctly when index === lastIndex. lastIndex = keys.length - 1; keys[index] = void 0; // If we crash here, there's a void 0 in the keys array, but // no operation will cause a "keys.indexOf(void 0)", since // getHiddenRecord(void 0) will always throw an error first. values[index] = values[lastIndex]; // If we crash here, values[index] cannot be found here, // because keys[index] is void 0. keys[index] = keys[lastIndex]; // If index === lastIndex and we crash here, then keys[index] // is still void 0, since the aliasing killed the previous key. keys.length = lastIndex; // If we crash here, keys will be one shorter than values. values.length = lastIndex; return true; } } return Object.create(OurWeakMap.prototype, { get___: { value: constFunc(get___) }, has___: { value: constFunc(has___) }, set___: { value: constFunc(set___) }, delete___: { value: constFunc(delete___) } }); }; OurWeakMap.prototype = Object.create(Object.prototype, { get: { /** * Return the value most recently associated with key, or * opt_default if none. */ value: function get(key, opt_default) { return this.get___(key, opt_default); }, writable: true, configurable: true }, has: { /** * Is there a value associated with key in this WeakMap? */ value: function has(key) { return this.has___(key); }, writable: true, configurable: true }, set: { /** * Associate value with key in this WeakMap, overwriting any * previous association if present. */ value: function set(key, value) { return this.set___(key, value); }, writable: true, configurable: true }, 'delete': { /** * Remove any association for key in this WeakMap, returning * whether there was one. * *

Note that the boolean return here does not work like the * {@code delete} operator. The {@code delete} operator returns * whether the deletion succeeds at bringing about a state in * which the deleted property is absent. The {@code delete} * operator therefore returns true if the property was already * absent, whereas this {@code delete} method returns false if * the association was already absent. */ value: function remove(key) { return this.delete___(key); }, writable: true, configurable: true } }); if (typeof HostWeakMap === 'function') { (function() { // If we got here, then the platform has a WeakMap but we are concerned // that it may refuse to store some key types. Therefore, make a map // implementation which makes use of both as possible. // In this mode we are always using double maps, so we are not proxy-safe. // This combination does not occur in any known browser, but we had best // be safe. if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') { Proxy = undefined; } function DoubleWeakMap() { if (!(this instanceof OurWeakMap)) { // approximate test for new ...() calledAsFunctionWarning(); } // Preferable, truly weak map. var hmap = new HostWeakMap(); // Our hidden-property-based pseudo-weak-map. Lazily initialized in the // 'set' implementation; thus we can avoid performing extra lookups if // we know all entries actually stored are entered in 'hmap'. var omap = undefined; // Hidden-property maps are not compatible with proxies because proxies // can observe the hidden name and either accidentally expose it or fail // to allow the hidden property to be set. Therefore, we do not allow // arbitrary WeakMaps to switch to using hidden properties, but only // those which need the ability, and unprivileged code is not allowed // to set the flag. // // (Except in doubleWeakMapCheckSilentFailure mode in which case we // disable proxies.) var enableSwitching = false; function dget(key, opt_default) { if (omap) { return hmap.has(key) ? hmap.get(key) : omap.get___(key, opt_default); } else { return hmap.get(key, opt_default); } } function dhas(key) { return hmap.has(key) || (omap ? omap.has___(key) : false); } var dset; if (doubleWeakMapCheckSilentFailure) { dset = function(key, value) { hmap.set(key, value); if (!hmap.has(key)) { if (!omap) { omap = new OurWeakMap(); } omap.set(key, value); } return this; }; } else { dset = function(key, value) { if (enableSwitching) { try { hmap.set(key, value); } catch (e) { if (!omap) { omap = new OurWeakMap(); } omap.set___(key, value); } } else { hmap.set(key, value); } return this; }; } function ddelete(key) { var result = !!hmap['delete'](key); if (omap) { return omap.delete___(key) || result; } return result; } return Object.create(OurWeakMap.prototype, { get___: { value: constFunc(dget) }, has___: { value: constFunc(dhas) }, set___: { value: constFunc(dset) }, delete___: { value: constFunc(ddelete) }, permitHostObjects___: { value: constFunc(function(token) { if (token === weakMapPermitHostObjects) { enableSwitching = true; } else { throw new Error('bogus call to permitHostObjects___'); } })} }); } DoubleWeakMap.prototype = OurWeakMap.prototype; module.exports = DoubleWeakMap; // define .constructor to hide OurWeakMap ctor Object.defineProperty(WeakMap.prototype, 'constructor', { value: WeakMap, enumerable: false, // as default .constructor is configurable: true, writable: true }); })(); } else { // There is no host WeakMap, so we must use the emulation. // Emulated WeakMaps are incompatible with native proxies (because proxies // can observe the hidden name), so we must disable Proxy usage (in // ArrayLike and Domado, currently). if (typeof Proxy !== 'undefined') { Proxy = undefined; } module.exports = OurWeakMap; } })(); /***/ }), /***/ "2f68": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("f1c3"); /***/ }), /***/ "2ff0": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var colorscaleDefaults = __webpack_require__("4183"); var attributes = __webpack_require__("02ea"); module.exports = 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 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'} ); // 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 mapLegacy(traceIn, oldAttr, newAttr) { if(oldAttr in traceIn && !(newAttr in traceIn)) { traceIn[newAttr] = traceIn[oldAttr]; } } /***/ }), /***/ "3022": /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(obj) { var keys = Object.keys(obj); var descriptors = {}; for (var i = 0; i < keys.length; i++) { descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); } return descriptors; }; var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { if (typeof process !== 'undefined' && process.noDeprecation === true) { return fn; } // Allow for deprecating things in the process of starting up. if (typeof process === 'undefined') { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = Object({"NODE_ENV":"production","BASE_URL":""}).NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__("d60a"); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__("28a0"); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; exports.promisify = function promisify(original) { if (typeof original !== 'function') throw new TypeError('The "original" argument must be of type Function'); if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { var fn = original[kCustomPromisifiedSymbol]; if (typeof fn !== 'function') { throw new TypeError('The "util.promisify.custom" argument must be of type Function'); } Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return fn; } function fn() { var promiseResolve, promiseReject; var promise = new Promise(function (resolve, reject) { promiseResolve = resolve; promiseReject = reject; }); var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } args.push(function (err, value) { if (err) { promiseReject(err); } else { promiseResolve(value); } }); try { original.apply(this, args); } catch (err) { promiseReject(err); } return promise; } Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return Object.defineProperties( fn, getOwnPropertyDescriptors(original) ); } exports.promisify.custom = kCustomPromisifiedSymbol function callbackifyOnRejected(reason, cb) { // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). // Because `null` is a special error value in callbacks which means "no error // occurred", we error-wrap so the callback consumer can distinguish between // "the promise rejected with null" or "the promise fulfilled with undefined". if (!reason) { var newReason = new Error('Promise was rejected with a falsy value'); newReason.reason = reason; reason = newReason; } return cb(reason); } function callbackify(original) { if (typeof original !== 'function') { throw new TypeError('The "original" argument must be of type Function'); } // We DO NOT return the promise as it gives the user a false sense that // the promise is actually somehow related to the callback's execution // and that the callback throwing will reject the promise. function callbackified() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== 'function') { throw new TypeError('The last argument must be of type Function'); } var self = this; var cb = function() { return maybeCb.apply(self, arguments); }; // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) original.apply(this, args) .then(function(ret) { process.nextTick(cb, null, ret) }, function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) }); } Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); return callbackified; } exports.callbackify = callbackify; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("4362"))) /***/ }), /***/ "3029": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = solveIntersection var ratMul = __webpack_require__("3bd6") var ratDiv = __webpack_require__("18a2") var ratSub = __webpack_require__("9c7c") var ratSign = __webpack_require__("3dac") var rvSub = __webpack_require__("66ac") var rvAdd = __webpack_require__("e56e") var rvMuls = __webpack_require__("093d") function ratPerp (a, b) { return ratSub(ratMul(a[0], b[1]), ratMul(a[1], b[0])) } // Solve for intersection // x = a + t (b-a) // (x - c) ^ (d-c) = 0 // (t * (b-a) + (a-c) ) ^ (d-c) = 0 // t * (b-a)^(d-c) = (d-c)^(a-c) // t = (d-c)^(a-c) / (b-a)^(d-c) function solveIntersection (a, b, c, d) { var ba = rvSub(b, a) var dc = rvSub(d, c) var baXdc = ratPerp(ba, dc) if (ratSign(baXdc) === 0) { return null } var ac = rvSub(a, c) var dcXac = ratPerp(dc, ac) var t = ratDiv(dcXac, baXdc) var s = rvMuls(ba, t) var r = rvAdd(a, s) return r } /***/ }), /***/ "3044": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var heatmapAttrs = __webpack_require__("0435"); var contourAttrs = __webpack_require__("43ef"); var colorScaleAttrs = __webpack_require__("f4e9"); var extendFlat = __webpack_require__("9092").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' }, transforms: undefined }, colorScaleAttrs('', { cLetter: 'z', autoColorDflt: false }) ); /***/ }), /***/ "3068": /***/ (function(module, exports) { var reg = /[\'\"]/ module.exports = function unquote(str) { if (!str) { return '' } if (reg.test(str.charAt(0))) { str = str.substr(1) } if (reg.test(str.charAt(str.length - 1))) { str = str.substr(0, str.length - 1) } return str } /***/ }), /***/ "306c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Simple helper functions // none of these need any external deps module.exports = function identity(d) { return d; }; /***/ }), /***/ "3122": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = compareAngle var orient = __webpack_require__("92ba") var sgn = __webpack_require__("79d9") var twoSum = __webpack_require__("d1bd") var robustProduct = __webpack_require__("91e1") var robustSum = __webpack_require__("a026") function testInterior(a, b, c) { var x0 = twoSum(a[0], -b[0]) var y0 = twoSum(a[1], -b[1]) var x1 = twoSum(c[0], -b[0]) var y1 = twoSum(c[1], -b[1]) var d = robustSum( robustProduct(x0, x1), robustProduct(y0, y1)) return d[d.length-1] >= 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 } } } } /***/ }), /***/ "3146": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createBackgroundCube var createBuffer = __webpack_require__("efce") var createVAO = __webpack_require__("b205") var createShader = __webpack_require__("c185").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) } /***/ }), /***/ "320c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }), /***/ "3273": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var drawModule = __webpack_require__("236d"); module.exports = { moduleType: 'component', name: 'shapes', layoutAttributes: __webpack_require__("a5cc"), supplyLayoutDefaults: __webpack_require__("567e"), includeBasePlot: __webpack_require__("37d1")('shapes'), calcAutorange: __webpack_require__("cef0"), draw: drawModule.draw, drawOne: drawModule.drawOne }; /***/ }), /***/ "3350": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); /** 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 */ module.exports = { circle: { n: 0, f: function(r) { var rs = d3.round(r, 2); return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z'; } }, square: { n: 1, f: function(r) { var rs = d3.round(r, 2); return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; } }, diamond: { n: 2, f: function(r) { var rd = d3.round(r * 1.3, 2); return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z'; } }, cross: { n: 3, f: function(r) { var rc = d3.round(r * 0.4, 2); var rc2 = d3.round(r * 1.2, 2); return '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) { var rx = d3.round(r * 0.8 / Math.sqrt(2), 2); var ne = 'l' + rx + ',' + rx; var se = 'l' + rx + ',-' + rx; var sw = 'l-' + rx + ',-' + rx; var nw = 'l-' + rx + ',' + rx; return 'M0,' + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + 'Z'; } }, 'triangle-up': { n: 5, f: function(r) { var rt = d3.round(r * 2 / Math.sqrt(3), 2); var r2 = d3.round(r / 2, 2); var rs = d3.round(r, 2); return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z'; } }, 'triangle-down': { n: 6, f: function(r) { var rt = d3.round(r * 2 / Math.sqrt(3), 2); var r2 = d3.round(r / 2, 2); var rs = d3.round(r, 2); return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z'; } }, 'triangle-left': { n: 7, f: function(r) { var rt = d3.round(r * 2 / Math.sqrt(3), 2); var r2 = d3.round(r / 2, 2); var rs = d3.round(r, 2); return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z'; } }, 'triangle-right': { n: 8, f: function(r) { var rt = d3.round(r * 2 / Math.sqrt(3), 2); var r2 = d3.round(r / 2, 2); var rs = d3.round(r, 2); return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z'; } }, 'triangle-ne': { n: 9, f: function(r) { var r1 = d3.round(r * 0.6, 2); var r2 = d3.round(r * 1.2, 2); return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z'; } }, 'triangle-se': { n: 10, f: function(r) { var r1 = d3.round(r * 0.6, 2); var r2 = d3.round(r * 1.2, 2); return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z'; } }, 'triangle-sw': { n: 11, f: function(r) { var r1 = d3.round(r * 0.6, 2); var r2 = d3.round(r * 1.2, 2); return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z'; } }, 'triangle-nw': { n: 12, f: function(r) { var r1 = d3.round(r * 0.6, 2); var r2 = d3.round(r * 1.2, 2); return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z'; } }, pentagon: { n: 13, f: function(r) { var x1 = d3.round(r * 0.951, 2); var x2 = d3.round(r * 0.588, 2); var y0 = d3.round(-r, 2); var y1 = d3.round(r * -0.309, 2); var y2 = d3.round(r * 0.809, 2); return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 + 'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z'; } }, hexagon: { n: 14, f: function(r) { var y0 = d3.round(r, 2); var y1 = d3.round(r / 2, 2); var x = d3.round(r * Math.sqrt(3) / 2, 2); return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 + 'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z'; } }, hexagon2: { n: 15, f: function(r) { var x0 = d3.round(r, 2); var x1 = d3.round(r / 2, 2); var y = d3.round(r * Math.sqrt(3) / 2, 2); return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 + ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z'; } }, octagon: { n: 16, f: function(r) { var a = d3.round(r * 0.924, 2); var b = d3.round(r * 0.383, 2); return '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) { var rs = r * 1.4; var x1 = d3.round(rs * 0.225, 2); var x2 = d3.round(rs * 0.951, 2); var x3 = d3.round(rs * 0.363, 2); var x4 = d3.round(rs * 0.588, 2); var y0 = d3.round(-rs, 2); var y1 = d3.round(rs * -0.309, 2); var y3 = d3.round(rs * 0.118, 2); var y4 = d3.round(rs * 0.809, 2); var y5 = d3.round(rs * 0.382, 2); return '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) { var y = d3.round(r * 0.66, 2); var x1 = d3.round(r * 0.38, 2); var x2 = d3.round(r * 0.76, 2); return '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) { var x = d3.round(r * Math.sqrt(3) * 0.8, 2); var y1 = d3.round(r * 0.8, 2); var y2 = d3.round(r * 1.6, 2); var rc = d3.round(r * 4, 2); var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 + aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z'; } }, 'star-triangle-down': { n: 20, f: function(r) { var x = d3.round(r * Math.sqrt(3) * 0.8, 2); var y1 = d3.round(r * 0.8, 2); var y2 = d3.round(r * 1.6, 2); var rc = d3.round(r * 4, 2); var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 + aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z'; } }, 'star-square': { n: 21, f: function(r) { var rp = d3.round(r * 1.1, 2); var rc = d3.round(r * 2, 2); var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp + aPart + rp + ',' + rp + aPart + rp + ',-' + rp + aPart + '-' + rp + ',-' + rp + 'Z'; } }, 'star-diamond': { n: 22, f: function(r) { var rp = d3.round(r * 1.4, 2); var rc = d3.round(r * 1.9, 2); var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + rp + ',0' + aPart + '0,' + rp + aPart + rp + ',0' + aPart + '0,-' + rp + aPart + '-' + rp + ',0' + 'Z'; } }, 'diamond-tall': { n: 23, f: function(r) { var x = d3.round(r * 0.7, 2); var y = d3.round(r * 1.4, 2); return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z'; } }, 'diamond-wide': { n: 24, f: function(r) { var x = d3.round(r * 1.4, 2); var y = d3.round(r * 0.7, 2); return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z'; } }, hourglass: { n: 25, f: function(r) { var rs = d3.round(r, 2); return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z'; }, noDot: true }, bowtie: { n: 26, f: function(r) { var rs = d3.round(r, 2); return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z'; }, noDot: true }, 'circle-cross': { n: 27, f: function(r) { var rs = d3.round(r, 2); return '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) { var rs = d3.round(r, 2); var rc = d3.round(r / Math.sqrt(2), 2); return '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) { var rs = d3.round(r, 2); return '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) { var rs = d3.round(r, 2); return '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) { var rd = d3.round(r * 1.3, 2); return '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) { var rd = d3.round(r * 1.3, 2); var r2 = d3.round(r * 0.65, 2); return '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) { var rc = d3.round(r * 1.4, 2); return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc; }, needLine: true, noDot: true, noFill: true }, 'x-thin': { n: 34, f: function(r) { var rx = d3.round(r, 2); return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx + 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; }, needLine: true, noDot: true, noFill: true }, asterisk: { n: 35, f: function(r) { var rc = d3.round(r * 1.2, 2); var rs = d3.round(r * 0.85, 2); return '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) { var r1 = d3.round(r / 2, 2); var r2 = d3.round(r, 2); return 'M' + r1 + ',' + r2 + 'V-' + r2 + 'm-' + r2 + ',0V' + r2 + 'M' + r2 + ',' + r1 + 'H-' + r2 + 'm0,-' + r2 + 'H' + r2; }, needLine: true, noFill: true }, 'y-up': { n: 37, f: function(r) { var x = d3.round(r * 1.2, 2); var y0 = d3.round(r * 1.6, 2); var y1 = d3.round(r * 0.8, 2); return '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) { var x = d3.round(r * 1.2, 2); var y0 = d3.round(r * 1.6, 2); var y1 = d3.round(r * 0.8, 2); return '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) { var y = d3.round(r * 1.2, 2); var x0 = d3.round(r * 1.6, 2); var x1 = d3.round(r * 0.8, 2); return '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) { var y = d3.round(r * 1.2, 2); var x0 = d3.round(r * 1.6, 2); var x1 = d3.round(r * 0.8, 2); return '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) { var rc = d3.round(r * 1.4, 2); return 'M' + rc + ',0H-' + rc; }, needLine: true, noDot: true, noFill: true }, 'line-ns': { n: 42, f: function(r) { var rc = d3.round(r * 1.4, 2); return 'M0,' + rc + 'V-' + rc; }, needLine: true, noDot: true, noFill: true }, 'line-ne': { n: 43, f: function(r) { var rx = d3.round(r, 2); return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; }, needLine: true, noDot: true, noFill: true }, 'line-nw': { n: 44, f: function(r) { var rx = d3.round(r, 2); return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx; }, needLine: true, noDot: true, noFill: true } }; /***/ }), /***/ "33ae": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var str2RGBArray = __webpack_require__("f977"); 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; /***/ }), /***/ "342f": /***/ (function(module, exports, __webpack_require__) { var getBuiltIn = __webpack_require__("d066"); module.exports = getBuiltIn('navigator', 'userAgent') || ''; /***/ }), /***/ "3473": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isIterable = __webpack_require__("91e3"); module.exports = function (value) { if (!isIterable(value)) throw new TypeError(value + " is not iterable"); return value; }; /***/ }), /***/ "348d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var histogram2dAttrs = __webpack_require__("1590"); var contourAttrs = __webpack_require__("43ef"); var colorScaleAttrs = __webpack_require__("f4e9"); var extendFlat = __webpack_require__("9092").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' }, zhoverformat: histogram2dAttrs.zhoverformat, hovertemplate: histogram2dAttrs.hovertemplate }, colorScaleAttrs('', { cLetter: 'z', editTypeOverride: 'calc' }) ); /***/ }), /***/ "34cc": /***/ (function(module, exports) { // (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc // MIT License // Project Home: https://github.com/voidqk/polybooljs // // convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) // var GeoJSON = { // convert a GeoJSON object to a PolyBool polygon toPolygon: function(PolyBool, geojson){ // converts list of LineString's to segments function GeoPoly(coords){ // check for empty coords if (coords.length <= 0) return PolyBool.segments({ inverted: false, regions: [] }); // convert LineString to segments function LineString(ls){ // remove tail which should be the same as head var reg = ls.slice(0, ls.length - 1); return PolyBool.segments({ inverted: false, regions: [reg] }); } // the first LineString is considered the outside var out = LineString(coords[0]); // the rest of the LineStrings are considered interior holes, so subtract them from the // current result for (var i = 1; i < coords.length; i++) out = PolyBool.selectDifference(PolyBool.combine(out, LineString(coords[i]))); return out; } if (geojson.type === 'Polygon'){ // single polygon, so just convert it and we're done return PolyBool.polygon(GeoPoly(geojson.coordinates)); } else if (geojson.type === 'MultiPolygon'){ // multiple polygons, so union all the polygons together var out = PolyBool.segments({ inverted: false, regions: [] }); for (var i = 0; i < geojson.coordinates.length; i++) out = PolyBool.selectUnion(PolyBool.combine(out, GeoPoly(geojson.coordinates[i]))); return PolyBool.polygon(out); } throw new Error('PolyBool: Cannot convert GeoJSON object to PolyBool polygon'); }, // convert a PolyBool polygon to a GeoJSON object fromPolygon: function(PolyBool, eps, poly){ // make sure out polygon is clean poly = PolyBool.polygon(PolyBool.segments(poly)); // test if r1 is inside r2 function regionInsideRegion(r1, r2){ // we're guaranteed no lines intersect (because the polygon is clean), but a vertex // could be on the edge -- so we just average pt[0] and pt[1] to produce a point on the // edge of the first line, which cannot be on an edge return eps.pointInsideRegion([ (r1[0][0] + r1[1][0]) * 0.5, (r1[0][1] + r1[1][1]) * 0.5 ], r2); } // calculate inside heirarchy // // _____________________ _______ roots -> A -> F // | A | | F | | | // | _______ _______ | | ___ | +-- B +-- G // | | B | | C | | | | | | | | // | | ___ | | ___ | | | | | | | +-- D // | | | D | | | | E | | | | | G | | | // | | |___| | | |___| | | | | | | +-- C // | |_______| |_______| | | |___| | | // |_____________________| |_______| +-- E function newNode(region){ return { region: region, children: [] }; } var roots = newNode(null); function addChild(root, region){ // first check if we're inside any children for (var i = 0; i < root.children.length; i++){ var child = root.children[i]; if (regionInsideRegion(region, child.region)){ // we are, so insert inside them instead addChild(child, region); return; } } // not inside any children, so check to see if any children are inside us var node = newNode(region); for (var i = 0; i < root.children.length; i++){ var child = root.children[i]; if (regionInsideRegion(child.region, region)){ // oops... move the child beneath us, and remove them from root node.children.push(child); root.children.splice(i, 1); i--; } } // now we can add ourselves root.children.push(node); } // add all regions to the root for (var i = 0; i < poly.regions.length; i++){ var region = poly.regions[i]; if (region.length < 3) // regions must have at least 3 points (sanity check) continue; addChild(roots, region); } // with our heirarchy, we can distinguish between exterior borders, and interior holes // the root nodes are exterior, children are interior, children's children are exterior, // children's children's children are interior, etc // while we're at it, exteriors are counter-clockwise, and interiors are clockwise function forceWinding(region, clockwise){ // first, see if we're clockwise or counter-clockwise // https://en.wikipedia.org/wiki/Shoelace_formula var winding = 0; var last_x = region[region.length - 1][0]; var last_y = region[region.length - 1][1]; var copy = []; for (var i = 0; i < region.length; i++){ var curr_x = region[i][0]; var curr_y = region[i][1]; copy.push([curr_x, curr_y]); // create a copy while we're at it winding += curr_y * last_x - curr_x * last_y; last_x = curr_x; last_y = curr_y; } // this assumes Cartesian coordinates (Y is positive going up) var isclockwise = winding < 0; if (isclockwise !== clockwise) copy.reverse(); // while we're here, the last point must be the first point... copy.push([copy[0][0], copy[0][1]]); return copy; } var geopolys = []; function addExterior(node){ var poly = [forceWinding(node.region, false)]; geopolys.push(poly); // children of exteriors are interior for (var i = 0; i < node.children.length; i++) poly.push(getInterior(node.children[i])); } function getInterior(node){ // children of interiors are exterior for (var i = 0; i < node.children.length; i++) addExterior(node.children[i]); // return the clockwise interior return forceWinding(node.region, true); } // root nodes are exterior for (var i = 0; i < roots.children.length; i++) addExterior(roots.children[i]); // lastly, construct the approrpriate GeoJSON object if (geopolys.length <= 0) // empty GeoJSON Polygon return { type: 'Polygon', coordinates: [] }; if (geopolys.length == 1) // use a GeoJSON Polygon return { type: 'Polygon', coordinates: geopolys[0] }; return { // otherwise, use a GeoJSON MultiPolygon type: 'MultiPolygon', coordinates: geopolys }; } }; module.exports = GeoJSON; /***/ }), /***/ "34d8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var Drawing = __webpack_require__("83d1"); var barPlot = __webpack_require__("c791"); var clearMinTextSize = __webpack_require__("93a6").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[3] !== undefined && y[3] !== undefined) { 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'; } } 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]; } /***/ }), /***/ "34f9": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); var arrayEditor = __webpack_require__("a651").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 v2 function clickData2r(d, ax) { return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d); } /***/ }), /***/ "3511": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var constraintMapping = __webpack_require__("11ab"); var endPlus = __webpack_require__("bc6b"); 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; }; /***/ }), /***/ "351b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var toLogRange = __webpack_require__("f6b0"); /* * 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 v2.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); } }; /***/ }), /***/ "3560": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = boxIntersectIter var pool = __webpack_require__("cea5") var bits = __webpack_require__("a48a") var bruteForce = __webpack_require__("b83d") var bruteForcePartial = bruteForce.partial var bruteForceFull = bruteForce.full var sweep = __webpack_require__("97e2") var findMedian = __webpack_require__("158b") var genPartition = __webpack_require__("8e58") //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)', ['p0', 'p1']) var partitionStartEqual = genPartition( 'lo===p0', ['p0']) var partitionStartLessThan = genPartition( 'lo 0) { 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) < SCAN_COMPLETE_CUTOFF) { retval = sweep.scanComplete( d, axis, visit, redStart, redEnd, red, redIndex, blueStart, blueEnd, blue, blueIndex) if(retval !== void 0) { return retval } continue } } else { if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) { //If input small, then use brute force retval = bruteForcePartial( d, axis, visit, flip, redStart, redEnd, red, redIndex, blueStart, blueEnd, blue, blueIndex) if(retval !== void 0) { return retval } continue } else if(d * redCount * blueCount < SCAN_CUTOFF) { //If input medium sized, then use sweep and prune retval = sweep.scanBipartite( d, axis, visit, flip, redStart, redEnd, red, redIndex, blueStart, blueEnd, blue, blueIndex) if(retval !== void 0) { return retval } continue } } //First, find all red intervals whose interior contains (lo,hi) var red0 = partitionInteriorContainsInterval( d, axis, redStart, redEnd, red, redIndex, lo, hi) //Lower dimensional case if(redStart < red0) { if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) { //Special case for small inputs: use brute force retval = bruteForceFull( d, axis+1, visit, redStart, red0, red, redIndex, blueStart, blueEnd, blue, blueIndex) if(retval !== void 0) { return retval } } else if(axis === d-2) { if(flip) { retval = sweep.sweepBipartite( d, visit, blueStart, blueEnd, blue, blueIndex, redStart, red0, red, redIndex) } else { retval = sweep.sweepBipartite( d, visit, redStart, red0, red, redIndex, blueStart, blueEnd, blue, blueIndex) } if(retval !== void 0) { return retval } } else { iterPush(top++, axis+1, redStart, red0, blueStart, blueEnd, flip, -Infinity, Infinity) iterPush(top++, axis+1, blueStart, blueEnd, redStart, red0, flip^1, -Infinity, Infinity) } } //Divide and conquer phase if(red0 < redEnd) { //Cut blue into 3 parts: // // Points < mid point // Points = mid point // Points > 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(blue1 < blueEnd) { iterPush(top++, axis, red0, redEnd, blue1, blueEnd, (flip|4) + (full ? 16 : 0), mid, hi) } //Left case if(blueStart < blue0) { iterPush(top++, axis, red0, redEnd, blueStart, blue0, (flip|2) + (full ? 16 : 0), lo, mid) } //Center case (the hard part) if(blue0 + 1 === blue1) { //Optimization: Range with exactly 1 point, use a brute force scan if(full) { retval = onePointFull( d, axis, visit, red0, redEnd, red, redIndex, blue0, blue, blueIndex[blue0]) } else { retval = onePointPartial( d, axis, visit, flip, red0, redEnd, red, redIndex, blue0, blue, blueIndex[blue0]) } if(retval !== void 0) { return retval } } else if(blue0 < blue1) { var red1 if(full) { //If full intersection, need to handle special case red1 = partitionContainsPoint( d, axis, red0, redEnd, red, redIndex, mid) if(red0 < red1) { var redX = partitionStartEqual( d, axis, red0, red1, red, redIndex, mid) if(axis === d-2) { //Degenerate sweep intersection: // [red0, redX] with [blue0, blue1] if(red0 < redX) { retval = sweep.sweepComplete( d, visit, red0, redX, red, redIndex, blue0, blue1, blue, blueIndex) if(retval !== void 0) { return retval } } //Normal sweep intersection: // [redX, red1] with [blue0, blue1] if(redX < red1) { retval = sweep.sweepBipartite( d, visit, redX, red1, red, redIndex, blue0, blue1, blue, blueIndex) if(retval !== void 0) { return retval } } } else { if(red0 < redX) { iterPush(top++, axis+1, red0, redX, blue0, blue1, 16, -Infinity, Infinity) } if(redX < red1) { iterPush(top++, axis+1, redX, red1, blue0, blue1, 0, -Infinity, Infinity) iterPush(top++, axis+1, blue0, blue1, redX, red1, 1, -Infinity, Infinity) } } } } else { if(flip) { red1 = partitionContainsPointProper( d, axis, red0, redEnd, red, redIndex, mid) } else { red1 = partitionContainsPoint( d, axis, red0, redEnd, red, redIndex, mid) } if(red0 < red1) { if(axis === d-2) { if(flip) { retval = sweep.sweepBipartite( d, visit, blue0, blue1, blue, blueIndex, red0, red1, red, redIndex) } else { retval = sweep.sweepBipartite( d, visit, red0, red1, red, redIndex, blue0, blue1, blue, blueIndex) } } else { iterPush(top++, axis+1, red0, red1, blue0, blue1, flip, -Infinity, Infinity) iterPush(top++, axis+1, blue0, blue1, red0, red1, flip^1, -Infinity, Infinity) } } } } } } } /***/ }), /***/ "35b1": /***/ (function(module, exports, __webpack_require__) { "use strict"; var determinant = __webpack_require__("c2ef") var NUM_EXPAND = 6 function generateSolver(n) { var funcName = "robustLinearSolve" + n + "d" var code = ["function ", funcName, "(A,b){return ["] for(var i=0; i 0) { code.push(",") } code.push("[") for(var k=0; k 0) { code.push(",") } if(k === i) { code.push("+b[", j, "]") } else { code.push("+A[", j, "][", k, "]") } } code.push("]") } code.push("]),") } code.push("det(A)]}return ", funcName) var proc = new Function("det", code.join("")) if(n < 6) { return proc(determinant[n]) } return proc(determinant) } function robustLinearSolve0d() { return [ 0 ] } function robustLinearSolve1d(A, b) { return [ [ b[0] ], [ A[0][0] ] ] } var CACHE = [ robustLinearSolve0d, robustLinearSolve1d ] function generateDispatch() { while(CACHE.length < NUM_EXPAND) { CACHE.push(generateSolver(CACHE.length)) } var procArgs = [] var code = ["function dispatchLinearSolve(A,b){switch(A.length){"] for(var i=0; i>> 24 var g = (n & 0x00ff0000) >>> 16 var b = (n & 0x0000ff00) >>> 8 var a = n & 0x000000ff if (normalized === false) return [r, g, b, a] return [r/255, g/255, b/255, a/255] } /***/ }), /***/ "3642": /***/ (function(module, exports, __webpack_require__) { "use strict"; var toString = Object.prototype.toString; module.exports = function (x) { var prototype; return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); }; /***/ }), /***/ "36ea": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var Drawing = __webpack_require__("83d1"); var barPlot = __webpack_require__("c791"); var clearMinTextSize = __webpack_require__("93a6").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(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] !== undefined && y[2] !== undefined) { 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]; } /***/ }), /***/ "36fc": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var boxLayoutAttrs = __webpack_require__("60dc"); var extendFlat = __webpack_require__("fc26").extendFlat; module.exports = { violinmode: extendFlat({}, boxLayoutAttrs.boxmode, { }), violingap: extendFlat({}, boxLayoutAttrs.boxgap, { }), violingroupgap: extendFlat({}, boxLayoutAttrs.boxgroupgap, { }) }; /***/ }), /***/ "371e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Loggers = __webpack_require__("ae13"); var noop = __webpack_require__("b778"); var pushUnique = __webpack_require__("5a1b"); var isPlainObject = __webpack_require__("1385"); var addStyleRule = __webpack_require__("1b88").addStyleRule; var ExtendModule = __webpack_require__("9092"); var basePlotAttributes = __webpack_require__("a876"); var baseLayoutAttributes = __webpack_require__("a685"); 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 plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; var _module = exports.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { 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') && (typeof window !== undefined && 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; } /***/ }), /***/ "372f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("1735"); /***/ }), /***/ "375c": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = typeof navigator !== 'undefined' && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion)); /***/ }), /***/ "37bf": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isArray1D = __webpack_require__("fc26").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; }; /***/ }), /***/ "37cd": /***/ (function(module, exports, __webpack_require__) { /*eslint new-cap:0*/ var dtype = __webpack_require__("7831") module.exports = flattenVertexData function flattenVertexData (data, output, offset) { if (!data) throw new TypeError('must specify data as first parameter') offset = +(offset || 0) | 0 if (Array.isArray(data) && (data[0] && typeof data[0][0] === 'number')) { var dim = data[0].length var length = data.length * dim var i, j, k, l // no output specified, create a new typed array if (!output || typeof output === 'string') { output = new (dtype(output || 'float32'))(length + offset) } var dstLength = output.length - offset if (length !== dstLength) { throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' + ' does not match destination length ' + dstLength) } for (i = 0, k = offset; i < data.length; i++) { for (j = 0; j < dim; j++) { output[k++] = data[i][j] === null ? NaN : data[i][j] } } } else { if (!output || typeof output === 'string') { // no output, create a new one var Ctor = dtype(output || 'float32') // handle arrays separately due to possible nulls if (Array.isArray(data) || output === 'array') { output = new Ctor(data.length + offset) for (i = 0, k = offset, l = output.length; k < l; k++, i++) { output[k] = data[i] === null ? NaN : data[i] } } else { if (offset === 0) { output = new Ctor(data) } else { output = new Ctor(data.length + offset) output.set(data, offset) } } } else { // store output in existing array output.set(data, offset) } } return output } /***/ }), /***/ "37d1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); /** * 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; var xref = itemi.xref; var yref = itemi.yref; 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); } } } }; }; /***/ }), /***/ "37e3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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', } }; /***/ }), /***/ "37e8": /***/ (function(module, exports, __webpack_require__) { var DESCRIPTORS = __webpack_require__("83ab"); var definePropertyModule = __webpack_require__("9bf2"); var anObject = __webpack_require__("825a"); var objectKeys = __webpack_require__("df75"); // `Object.defineProperties` method // https://tc39.github.io/ecma262/#sec-object.defineproperties module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = objectKeys(Properties); var length = keys.length; var index = 0; var key; while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]); return O; }; /***/ }), /***/ "3802": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Color = __webpack_require__("d115"); var isArrayOrTypedArray = __webpack_require__("fc26").isArrayOrTypedArray; module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { 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; } } coerce('fillcolor', Color.addOpacity( (traceOut.line || {}).color || inheritColorFromMarker || defaultColor, 0.5 )); }; /***/ }), /***/ "388d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("feb0"); /***/ }), /***/ "38eb": /***/ (function(module, exports, __webpack_require__) { var glslify = __webpack_require__("e98f") 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'} ] } /***/ }), /***/ "391b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Fx = __webpack_require__("a5c4"); var Registry = __webpack_require__("371e"); var getTraceColor = __webpack_require__("feed"); var Color = __webpack_require__("d115"); 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; // look for points to hover on first, then take fills only if we // didn't find a point if(hoveron.indexOf('points') !== -1) { var dx = function(di) { // 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 rad = Math.max(3, di.mrc || 0); var kink = 1 - 1 / rad; var dxRaw = Math.abs(xa.c2p(di.x) - xpx); var d = (dxRaw < rad) ? (kink * dxRaw / rad) : (dxRaw - rad + kink); return d; }; var dy = function(di) { 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); }; var dxy = function(di) { // 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 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.x; var yLabelVal = (orientation === 'v') ? sizeVal : 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]; } } // even if hoveron is 'fills', only use it if we have polygons too if(hoveron.indexOf('fills') !== -1 && trace._polygons) { var polygons = trace._polygons; var polygonsIn = []; var inside = false; var xmin = Infinity; var xmax = -Infinity; var ymin = Infinity; var ymax = -Infinity; var i, j, polygon, pts, xCross, x0, x1, y0, y1; for(i = 0; i < polygons.length; i++) { polygon = polygons[i]; // TODO: this is not going to work right for curved edges, it will // act as though they're straight. That's probably going to need // the elements themselves to capture the events. Worth it? if(polygon.contains(pt)) { inside = !inside; // TODO: need better than just the overall bounding box polygonsIn.push(polygon); ymin = Math.min(ymin, polygon.ymin); ymax = Math.max(ymax, polygon.ymax); } } if(inside) { // 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); // 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 yAvg = (ymin + ymax) / 2; 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 > yAvg) !== (y1 >= yAvg)) { x0 = pts[j - 1][0]; x1 = pts[j][0]; if(y1 - y0) { xCross = x0 + (x1 - x0) * (yAvg - y0) / (y1 - y0); xmin = Math.min(xmin, xCross); xmax = Math.max(xmax, xCross); } } } } // constrain xmin/max to the visible plot now too xmin = Math.max(xmin, 0); xmax = Math.min(xmax, xa._length); // 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: xmin, x1: xmax, y0: yAvg, y1: yAvg, color: color, hovertemplate: false }); delete pointData.index; if(trace.text && !Array.isArray(trace.text)) { pointData.text = String(trace.text); } else pointData.text = trace.name; return [pointData]; } } }; /***/ }), /***/ "3936": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var pieCalc = __webpack_require__("86b8"); function calc(gd, trace) { return pieCalc.calc(gd, trace); } function crossTraceCalc(gd) { pieCalc.crossTraceCalc(gd, { type: 'funnelarea' }); } module.exports = { calc: calc, crossTraceCalc: crossTraceCalc }; /***/ }), /***/ "399f": /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(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 { Buffer = __webpack_require__(1).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++; } if (base === 16) { this._parseHex(number, start); } else { this._parseBase(number, base, start); } if (number[0] === '-') { this.negative = 1; } this.strip(); if (endian !== 'le') return; this._initArray(this.toArray(), base, endian); }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this.strip(); }; function parseHex (str, start, end) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r <<= 4; // 'a' - 'f' if (c >= 49 && c <= 54) { r |= c - 49 + 0xa; // 'A' - 'F' } else if (c >= 17 && c <= 22) { r |= c - 17 + 0xa; // '0' - '9' } else { r |= c & 0xf; } } return r; } BN.prototype._parseHex = function _parseHex (number, start) { // 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 < this.length; i++) { this.words[i] = 0; } var j, w; // Scan 24-bit chunks and add them to the number var off = 0; for (i = number.length - 6, j = 0; i >= start; i -= 6) { w = parseHex(number, i, i + 6); this.words[j] |= (w << off) & 0x3ffffff; // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; off += 24; if (off >= 26) { off -= 26; j++; } } if (i + 6 !== start) { w = parseHex(number, start, i + 6); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 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; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype.strip = function strip () { while (this.length > 1 && 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 < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (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 < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 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 < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> 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; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.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; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.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; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.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; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { 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 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > 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 < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 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 (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.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 < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 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 < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 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 < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 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 < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 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 < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 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 < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (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 < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 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) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; 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 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 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) << r); this.words[this.length - 1] &= mask; } return this.strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 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 < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this.strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 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 < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 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] & num; }; // 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 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 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 ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `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 < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { 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 = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { 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 < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 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 < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 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 < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; 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 && current === 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); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("62e4")(module))) /***/ }), /***/ "3a04": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); // 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; }; /***/ }), /***/ "3a19": /***/ (function(module, exports) { module.exports = round /** * Math.round the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to round * @returns {vec3} out */ function round(out, a) { out[0] = Math.round(a[0]) out[1] = Math.round(a[1]) out[2] = Math.round(a[2]) return out } /***/ }), /***/ "3a55": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = findZeroCrossings var core = __webpack_require__("b530") function findZeroCrossings(array, level) { var cross = [] level = +level || 0.0 core(array.hi(array.shape[0]-1), cross, level) return cross } /***/ }), /***/ "3a99": /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var extendDeepAll = Lib.extendDeepAll; var MID_SHIFT = __webpack_require__("63dc").MID_SHIFT; var µ = module.exports = { version: '0.2.2' }; µ.Axis = function module() { var config = { data: [], layout: {} }, inputConfig = {}, liveConfig = {}; var svg, container, dispatch = d3.dispatch('hover'), radialScale, angularScale; var exports = {}; function render(_container) { container = _container || container; var data = config.data; var axisConfig = config.layout; if (typeof container == 'string' || container.nodeName) container = d3.select(container); container.datum(data).each(function(_data, _index) { var dataOriginal = _data.slice(); liveConfig = { data: µ.util.cloneJson(dataOriginal), layout: µ.util.cloneJson(axisConfig) }; var colorIndex = 0; dataOriginal.forEach(function(d, i) { if (!d.color) { d.color = axisConfig.defaultColorRange[colorIndex]; colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length; } if (!d.strokeColor) { d.strokeColor = d.geometry === 'LinePlot' ? d.color : d3.rgb(d.color).darker().toString(); } liveConfig.data[i].color = d.color; liveConfig.data[i].strokeColor = d.strokeColor; liveConfig.data[i].strokeDash = d.strokeDash; liveConfig.data[i].strokeSize = d.strokeSize; }); var data = dataOriginal.filter(function(d, i) { var visible = d.visible; return typeof visible === 'undefined' || visible === true; }); var isStacked = false; var dataWithGroupId = data.map(function(d, i) { isStacked = isStacked || typeof d.groupId !== 'undefined'; return d; }); if (isStacked) { var grouped = d3.nest().key(function(d, i) { return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked'; }).entries(dataWithGroupId); var dataYStack = []; var stacked = grouped.map(function(d, i) { if (d.key === 'unstacked') return d.values; else { var prevArray = d.values[0].r.map(function(d, i) { return 0; }); d.values.forEach(function(d, i, a) { d.yStack = [ prevArray ]; dataYStack.push(prevArray); prevArray = µ.util.sumArrays(d.r, prevArray); }); return d.values; } }); data = d3.merge(stacked); } data.forEach(function(d, i) { d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ]; d.r = Array.isArray(d.r[0]) ? d.r : [ d.r ]; }); var radius = Math.min(axisConfig.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2; radius = Math.max(10, radius); var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ]; var extent; if (isStacked) { var highestStackedValue = d3.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack))); extent = [ 0, highestStackedValue ]; } else extent = d3.extent(µ.util.flattenArray(data.map(function(d, i) { return d.r; }))); if (axisConfig.radialAxis.domain != µ.DATAEXTENT) extent[0] = 0; radialScale = d3.scale.linear().domain(axisConfig.radialAxis.domain != µ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]); liveConfig.layout.radialAxis.domain = radialScale.domain(); var angularDataMerged = µ.util.flattenArray(data.map(function(d, i) { return d.t; })); var isOrdinal = typeof angularDataMerged[0] === 'string'; var ticks; if (isOrdinal) { angularDataMerged = µ.util.deduplicate(angularDataMerged); ticks = angularDataMerged.slice(); angularDataMerged = d3.range(angularDataMerged.length); data = data.map(function(d, i) { var result = d; d.t = [ angularDataMerged ]; if (isStacked) result.yStack = d.yStack; return result; }); } var hasOnlyLineOrDotPlot = data.filter(function(d, i) { return d.geometry === 'LinePlot' || d.geometry === 'DotPlot'; }).length === data.length; var needsEndSpacing = axisConfig.needsEndSpacing === null ? isOrdinal || !hasOnlyLineOrDotPlot : axisConfig.needsEndSpacing; var useProvidedDomain = axisConfig.angularAxis.domain && axisConfig.angularAxis.domain != µ.DATAEXTENT && !isOrdinal && axisConfig.angularAxis.domain[0] >= 0; var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : d3.extent(angularDataMerged); var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]); if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0; var angularDomainWithPadding = angularDomain.slice(); if (needsEndSpacing && isOrdinal) angularDomainWithPadding[1] += angularDomainStep; var tickCount = axisConfig.angularAxis.ticksCount || 4; if (tickCount > 8) tickCount = tickCount / (tickCount / 8) + tickCount % 8; if (axisConfig.angularAxis.ticksStep) { tickCount = (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / tickCount; } var angularTicksStep = axisConfig.angularAxis.ticksStep || (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / (tickCount * (axisConfig.minorTicks + 1)); if (ticks) angularTicksStep = Math.max(Math.round(angularTicksStep), 1); if (!angularDomainWithPadding[2]) angularDomainWithPadding[2] = angularTicksStep; var angularAxisRange = d3.range.apply(this, angularDomainWithPadding); angularAxisRange = angularAxisRange.map(function(d, i) { return parseFloat(d.toPrecision(12)); }); angularScale = d3.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]); liveConfig.layout.angularAxis.domain = angularScale.domain(); liveConfig.layout.angularAxis.endPadding = needsEndSpacing ? angularDomainStep : 0; svg = d3.select(this).select('svg.chart-root'); if (typeof svg === 'undefined' || svg.empty()) { var skeleton = "' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '"; var doc = new DOMParser().parseFromString(skeleton, 'application/xml'); var newSvg = this.appendChild(this.ownerDocument.importNode(doc.documentElement, true)); svg = d3.select(newSvg); } svg.select('.guides-group').style({ 'pointer-events': 'none' }); svg.select('.angular.axis-group').style({ 'pointer-events': 'none' }); svg.select('.radial.axis-group').style({ 'pointer-events': 'none' }); var chartGroup = svg.select('.chart-group'); var lineStyle = { fill: 'none', stroke: axisConfig.tickColor }; var fontStyle = { 'font-size': axisConfig.font.size, 'font-family': axisConfig.font.family, fill: axisConfig.font.color, 'text-shadow': [ '-1px 0px', '1px -1px', '-1px 1px', '1px 1px' ].map(function(d, i) { return ' ' + d + ' 0 ' + axisConfig.font.outlineColor; }).join(',') }; var legendContainer; if (axisConfig.showLegend) { legendContainer = svg.select('.legend-group').attr({ transform: 'translate(' + [ radius, axisConfig.margin.top ] + ')' }).style({ display: 'block' }); var elements = data.map(function(d, i) { var datumClone = µ.util.cloneJson(d); datumClone.symbol = d.geometry === 'DotPlot' ? d.dotType || 'circle' : d.geometry != 'LinePlot' ? 'square' : 'line'; datumClone.visibleInLegend = typeof d.visibleInLegend === 'undefined' || d.visibleInLegend; datumClone.color = d.geometry === 'LinePlot' ? d.strokeColor : d.color; return datumClone; }); µ.Legend().config({ data: data.map(function(d, i) { return d.name || 'Element' + i; }), legendConfig: extendDeepAll({}, µ.Legend.defaultConfig().legendConfig, { container: legendContainer, elements: elements, reverseOrder: axisConfig.legend.reverseOrder } ) })(); var legendBBox = legendContainer.node().getBBox(); radius = Math.min(axisConfig.width - legendBBox.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2; radius = Math.max(10, radius); chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ]; radialScale.range([ 0, radius ]); liveConfig.layout.radialAxis.domain = radialScale.domain(); legendContainer.attr('transform', 'translate(' + [ chartCenter[0] + radius, chartCenter[1] - radius ] + ')'); } else { legendContainer = svg.select('.legend-group').style({ display: 'none' }); } svg.attr({ width: axisConfig.width, height: axisConfig.height }).style({ opacity: axisConfig.opacity }); chartGroup.attr('transform', 'translate(' + chartCenter + ')').style({ cursor: 'crosshair' }); var centeringOffset = [ (axisConfig.width - (axisConfig.margin.left + axisConfig.margin.right + radius * 2 + (legendBBox ? legendBBox.width : 0))) / 2, (axisConfig.height - (axisConfig.margin.top + axisConfig.margin.bottom + radius * 2)) / 2 ]; centeringOffset[0] = Math.max(0, centeringOffset[0]); centeringOffset[1] = Math.max(0, centeringOffset[1]); svg.select('.outer-group').attr('transform', 'translate(' + centeringOffset + ')'); if (axisConfig.title && axisConfig.title.text) { var title = svg.select('g.title-group text').style(fontStyle).text(axisConfig.title.text); var titleBBox = title.node().getBBox(); title.attr({ x: chartCenter[0] - titleBBox.width / 2, y: chartCenter[1] - radius - 20 }); } var radialAxis = svg.select('.radial.axis-group'); if (axisConfig.radialAxis.gridLinesVisible) { var gridCircles = radialAxis.selectAll('circle.grid-circle').data(radialScale.ticks(5)); gridCircles.enter().append('circle').attr({ 'class': 'grid-circle' }).style(lineStyle); gridCircles.attr('r', radialScale); gridCircles.exit().remove(); } radialAxis.select('circle.outside-circle').attr({ r: radius }).style(lineStyle); var backgroundCircle = svg.select('circle.background-circle').attr({ r: radius }).style({ fill: axisConfig.backgroundColor, stroke: axisConfig.stroke }); function currentAngle(d, i) { return angularScale(d) % 360 + axisConfig.orientation; } if (axisConfig.radialAxis.visible) { var axis = d3.svg.axis().scale(radialScale).ticks(5).tickSize(5); radialAxis.call(axis).attr({ transform: 'rotate(' + axisConfig.radialAxis.orientation + ')' }); radialAxis.selectAll('.domain').style(lineStyle); radialAxis.selectAll('g>text').text(function(d, i) { return this.textContent + axisConfig.radialAxis.ticksSuffix; }).style(fontStyle).style({ 'text-anchor': 'start' }).attr({ x: 0, y: 0, dx: 0, dy: 0, transform: function(d, i) { if (axisConfig.radialAxis.tickOrientation === 'horizontal') { return 'rotate(' + -axisConfig.radialAxis.orientation + ') translate(' + [ 0, fontStyle['font-size'] ] + ')'; } else return 'translate(' + [ 0, fontStyle['font-size'] ] + ')'; } }); radialAxis.selectAll('g>line').style({ stroke: 'black' }); } var angularAxis = svg.select('.angular.axis-group').selectAll('g.angular-tick').data(angularAxisRange); var angularAxisEnter = angularAxis.enter().append('g').classed('angular-tick', true); angularAxis.attr({ transform: function(d, i) { return 'rotate(' + currentAngle(d, i) + ')'; } }).style({ display: axisConfig.angularAxis.visible ? 'block' : 'none' }); angularAxis.exit().remove(); angularAxisEnter.append('line').classed('grid-line', true).classed('major', function(d, i) { return i % (axisConfig.minorTicks + 1) == 0; }).classed('minor', function(d, i) { return !(i % (axisConfig.minorTicks + 1) == 0); }).style(lineStyle); angularAxisEnter.selectAll('.minor').style({ stroke: axisConfig.minorTickColor }); angularAxis.select('line.grid-line').attr({ x1: axisConfig.tickLength ? radius - axisConfig.tickLength : 0, x2: radius }).style({ display: axisConfig.angularAxis.gridLinesVisible ? 'block' : 'none' }); angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle); var ticksText = angularAxis.select('text.axis-text').attr({ x: radius + axisConfig.labelOffset, dy: MID_SHIFT + 'em', transform: function(d, i) { var angle = currentAngle(d, i); var rad = radius + axisConfig.labelOffset; var orient = axisConfig.angularAxis.tickOrientation; if (orient == 'horizontal') return 'rotate(' + -angle + ' ' + rad + ' 0)'; else if (orient == 'radial') return angle < 270 && angle > 90 ? 'rotate(180 ' + rad + ' 0)' : null; else return 'rotate(' + (angle <= 180 && angle > 0 ? -90 : 90) + ' ' + rad + ' 0)'; } }).style({ 'text-anchor': 'middle', display: axisConfig.angularAxis.labelsVisible ? 'block' : 'none' }).text(function(d, i) { if (i % (axisConfig.minorTicks + 1) != 0) return ''; if (ticks) { return ticks[d] + axisConfig.angularAxis.ticksSuffix; } else return d + axisConfig.angularAxis.ticksSuffix; }).style(fontStyle); if (axisConfig.angularAxis.rewriteTicks) ticksText.text(function(d, i) { if (i % (axisConfig.minorTicks + 1) != 0) return ''; return axisConfig.angularAxis.rewriteTicks(this.textContent, i); }); var rightmostTickEndX = d3.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) { return d.getCTM().e + d.getBBox().width; })); legendContainer.attr({ transform: 'translate(' + [ radius + rightmostTickEndX, axisConfig.margin.top ] + ')' }); var hasGeometry = svg.select('g.geometry-group').selectAll('g').size() > 0; var geometryContainer = svg.select('g.geometry-group').selectAll('g.geometry').data(data); geometryContainer.enter().append('g').attr({ 'class': function(d, i) { return 'geometry geometry' + i; } }); geometryContainer.exit().remove(); if (data[0] || hasGeometry) { var geometryConfigs = []; data.forEach(function(d, i) { var geometryConfig = {}; geometryConfig.radialScale = radialScale; geometryConfig.angularScale = angularScale; geometryConfig.container = geometryContainer.filter(function(dB, iB) { return iB == i; }); geometryConfig.geometry = d.geometry; geometryConfig.orientation = axisConfig.orientation; geometryConfig.direction = axisConfig.direction; geometryConfig.index = i; geometryConfigs.push({ data: d, geometryConfig: geometryConfig }); }); var geometryConfigsGrouped = d3.nest().key(function(d, i) { return typeof d.data.groupId != 'undefined' || 'unstacked'; }).entries(geometryConfigs); var geometryConfigsGrouped2 = []; geometryConfigsGrouped.forEach(function(d, i) { if (d.key === 'unstacked') geometryConfigsGrouped2 = geometryConfigsGrouped2.concat(d.values.map(function(d, i) { return [ d ]; })); else geometryConfigsGrouped2.push(d.values); }); geometryConfigsGrouped2.forEach(function(d, i) { var geometry; if (Array.isArray(d)) geometry = d[0].geometryConfig.geometry; else geometry = d.geometryConfig.geometry; var finalGeometryConfig = d.map(function(dB, iB) { return extendDeepAll(µ[geometry].defaultConfig(), dB); }); µ[geometry]().config(finalGeometryConfig)(); }); } var guides = svg.select('.guides-group'); var tooltipContainer = svg.select('.tooltips-group'); var angularTooltip = µ.tooltipPanel().config({ container: tooltipContainer, fontSize: 8 })(); var radialTooltip = µ.tooltipPanel().config({ container: tooltipContainer, fontSize: 8 })(); var geometryTooltip = µ.tooltipPanel().config({ container: tooltipContainer, hasTick: true })(); var angularValue, radialValue; if (!isOrdinal) { var angularGuideLine = guides.select('line').attr({ x1: 0, y1: 0, y2: 0 }).style({ stroke: 'grey', 'pointer-events': 'none' }); chartGroup.on('mousemove.angular-guide', function(d, i) { var mouseAngle = µ.util.getMousePos(backgroundCircle).angle; angularGuideLine.attr({ x2: -radius, transform: 'rotate(' + mouseAngle + ')' }).style({ opacity: .5 }); var angleWithOriginOffset = (mouseAngle + 180 + 360 - axisConfig.orientation) % 360; angularValue = angularScale.invert(angleWithOriginOffset); var pos = µ.util.convertToCartesian(radius + 12, mouseAngle + 180); angularTooltip.text(µ.util.round(angularValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]); }).on('mouseout.angular-guide', function(d, i) { guides.select('line').style({ opacity: 0 }); }); } var angularGuideCircle = guides.select('circle').style({ stroke: 'grey', fill: 'none' }); chartGroup.on('mousemove.radial-guide', function(d, i) { var r = µ.util.getMousePos(backgroundCircle).radius; angularGuideCircle.attr({ r: r }).style({ opacity: .5 }); radialValue = radialScale.invert(µ.util.getMousePos(backgroundCircle).radius); var pos = µ.util.convertToCartesian(r, axisConfig.radialAxis.orientation); radialTooltip.text(µ.util.round(radialValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]); }).on('mouseout.radial-guide', function(d, i) { angularGuideCircle.style({ opacity: 0 }); geometryTooltip.hide(); angularTooltip.hide(); radialTooltip.hide(); }); svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) { var el = d3.select(this); var color = this.style.fill; var newColor = 'black'; var opacity = this.style.opacity || 1; el.attr({ 'data-opacity': opacity }); if (color && color !== 'none') { el.attr({ 'data-fill': color }); newColor = d3.hsl(color).darker().toString(); el.style({ fill: newColor, opacity: 1 }); var textData = { t: µ.util.round(d[0]), r: µ.util.round(d[1]) }; if (isOrdinal) textData.t = ticks[d[0]]; var text = 't: ' + textData.t + ', r: ' + textData.r; var bbox = this.getBoundingClientRect(); var svgBBox = svg.node().getBoundingClientRect(); var pos = [ bbox.left + bbox.width / 2 - centeringOffset[0] - svgBBox.left, bbox.top + bbox.height / 2 - centeringOffset[1] - svgBBox.top ]; geometryTooltip.config({ color: newColor }).text(text); geometryTooltip.move(pos); } else { color = this.style.stroke || 'black'; el.attr({ 'data-stroke': color }); newColor = d3.hsl(color).darker().toString(); el.style({ stroke: newColor, opacity: 1 }); } }).on('mousemove.tooltip', function(d, i) { if (d3.event.which != 0) return false; if (d3.select(this).attr('data-fill')) geometryTooltip.show(); }).on('mouseout.tooltip', function(d, i) { geometryTooltip.hide(); var el = d3.select(this); var fillColor = el.attr('data-fill'); if (fillColor) el.style({ fill: fillColor, opacity: el.attr('data-opacity') }); else el.style({ stroke: el.attr('data-stroke'), opacity: el.attr('data-opacity') }); }); }); return exports; } exports.render = function(_container) { render(_container); return this; }; exports.config = function(_x) { if (!arguments.length) return config; var xClone = µ.util.cloneJson(_x); xClone.data.forEach(function(d, i) { if (!config.data[i]) config.data[i] = {}; extendDeepAll(config.data[i], µ.Axis.defaultConfig().data[0]); extendDeepAll(config.data[i], d); }); extendDeepAll(config.layout, µ.Axis.defaultConfig().layout); extendDeepAll(config.layout, xClone.layout); return this; }; exports.getLiveConfig = function() { return liveConfig; }; exports.getinputConfig = function() { return inputConfig; }; exports.radialScale = function(_x) { return radialScale; }; exports.angularScale = function(_x) { return angularScale; }; exports.svg = function() { return svg; }; d3.rebind(exports, dispatch, 'on'); return exports; }; µ.Axis.defaultConfig = function(d, i) { var config = { data: [ { t: [ 1, 2, 3, 4 ], r: [ 10, 11, 12, 13 ], name: 'Line1', geometry: 'LinePlot', color: null, strokeDash: 'solid', strokeColor: null, strokeSize: '1', visibleInLegend: true, opacity: 1 } ], layout: { defaultColorRange: d3.scale.category10().range(), title: null, height: 450, width: 500, margin: { top: 40, right: 40, bottom: 40, left: 40 }, font: { size: 12, color: 'gray', outlineColor: 'white', family: 'Tahoma, sans-serif' }, direction: 'clockwise', orientation: 0, labelOffset: 10, radialAxis: { domain: null, orientation: -45, ticksSuffix: '', visible: true, gridLinesVisible: true, tickOrientation: 'horizontal', rewriteTicks: null }, angularAxis: { domain: [ 0, 360 ], ticksSuffix: '', visible: true, gridLinesVisible: true, labelsVisible: true, tickOrientation: 'horizontal', rewriteTicks: null, ticksCount: null, ticksStep: null }, minorTicks: 0, tickLength: null, tickColor: 'silver', minorTickColor: '#eee', backgroundColor: 'none', needsEndSpacing: null, showLegend: true, legend: { reverseOrder: false }, opacity: 1 } }; return config; }; µ.util = {}; µ.DATAEXTENT = 'dataExtent'; µ.AREA = 'AreaChart'; µ.LINE = 'LinePlot'; µ.DOT = 'DotPlot'; µ.BAR = 'BarChart'; µ.util._override = function(_objA, _objB) { for (var x in _objA) if (x in _objB) _objB[x] = _objA[x]; }; µ.util._extend = function(_objA, _objB) { for (var x in _objA) _objB[x] = _objA[x]; }; µ.util._rndSnd = function() { return Math.random() * 2 - 1 + (Math.random() * 2 - 1) + (Math.random() * 2 - 1); }; µ.util.dataFromEquation2 = function(_equation, _step) { var step = _step || 6; var data = d3.range(0, 360 + step, step).map(function(deg, index) { var theta = deg * Math.PI / 180; var radius = _equation(theta); return [ deg, radius ]; }); return data; }; µ.util.dataFromEquation = function(_equation, _step, _name) { var step = _step || 6; var t = [], r = []; d3.range(0, 360 + step, step).forEach(function(deg, index) { var theta = deg * Math.PI / 180; var radius = _equation(theta); t.push(deg); r.push(radius); }); var result = { t: t, r: r }; if (_name) result.name = _name; return result; }; µ.util.ensureArray = function(_val, _count) { if (typeof _val === 'undefined') return null; var arr = [].concat(_val); return d3.range(_count).map(function(d, i) { return arr[i] || arr[0]; }); }; µ.util.fillArrays = function(_obj, _valueNames, _count) { _valueNames.forEach(function(d, i) { _obj[d] = µ.util.ensureArray(_obj[d], _count); }); return _obj; }; µ.util.cloneJson = function(json) { return JSON.parse(JSON.stringify(json)); }; µ.util.validateKeys = function(obj, keys) { if (typeof keys === 'string') keys = keys.split('.'); var next = keys.shift(); return obj[next] && (!keys.length || objHasKeys(obj[next], keys)); }; µ.util.sumArrays = function(a, b) { return d3.zip(a, b).map(function(d, i) { return d3.sum(d); }); }; µ.util.arrayLast = function(a) { return a[a.length - 1]; }; µ.util.arrayEqual = function(a, b) { var i = Math.max(a.length, b.length, 1); while (i-- >= 0 && a[i] === b[i]) ; return i === -2; }; µ.util.flattenArray = function(arr) { var r = []; while (!µ.util.arrayEqual(r, arr)) { r = arr; arr = [].concat.apply([], arr); } return arr; }; µ.util.deduplicate = function(arr) { return arr.filter(function(v, i, a) { return a.indexOf(v) == i; }); }; µ.util.convertToCartesian = function(radius, theta) { var thetaRadians = theta * Math.PI / 180; var x = radius * Math.cos(thetaRadians); var y = radius * Math.sin(thetaRadians); return [ x, y ]; }; µ.util.round = function(_value, _digits) { var digits = _digits || 2; var mult = Math.pow(10, digits); return Math.round(_value * mult) / mult; }; µ.util.getMousePos = function(_referenceElement) { var mousePos = d3.mouse(_referenceElement.node()); var mouseX = mousePos[0]; var mouseY = mousePos[1]; var mouse = {}; mouse.x = mouseX; mouse.y = mouseY; mouse.pos = mousePos; mouse.angle = (Math.atan2(mouseY, mouseX) + Math.PI) * 180 / Math.PI; mouse.radius = Math.sqrt(mouseX * mouseX + mouseY * mouseY); return mouse; }; µ.util.duplicatesCount = function(arr) { var uniques = {}, val; var dups = {}; for (var i = 0, len = arr.length; i < len; i++) { val = arr[i]; if (val in uniques) { uniques[val]++; dups[val] = uniques[val]; } else { uniques[val] = 1; } } return dups; }; µ.util.duplicates = function(arr) { return Object.keys(µ.util.duplicatesCount(arr)); }; µ.util.translator = function(obj, sourceBranch, targetBranch, reverse) { if (reverse) { var targetBranchCopy = targetBranch.slice(); targetBranch = sourceBranch; sourceBranch = targetBranchCopy; } var value = sourceBranch.reduce(function(previousValue, currentValue) { if (typeof previousValue != 'undefined') return previousValue[currentValue]; }, obj); if (typeof value === 'undefined') return; sourceBranch.reduce(function(previousValue, currentValue, index) { if (typeof previousValue == 'undefined') return; if (index === sourceBranch.length - 1) delete previousValue[currentValue]; return previousValue[currentValue]; }, obj); targetBranch.reduce(function(previousValue, currentValue, index) { if (typeof previousValue[currentValue] === 'undefined') previousValue[currentValue] = {}; if (index === targetBranch.length - 1) previousValue[currentValue] = value; return previousValue[currentValue]; }, obj); }; µ.PolyChart = function module() { var config = [ µ.PolyChart.defaultConfig() ]; var dispatch = d3.dispatch('hover'); var dashArray = { solid: 'none', dash: [ 5, 2 ], dot: [ 2, 5 ] }; var colorScale; function exports() { var geometryConfig = config[0].geometryConfig; var container = geometryConfig.container; if (typeof container == 'string') container = d3.select(container); container.datum(config).each(function(_config, _index) { var isStack = !!_config[0].data.yStack; var data = _config.map(function(d, i) { if (isStack) return d3.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return d3.zip(d.data.t[0], d.data.r[0]); }); var angularScale = geometryConfig.angularScale; var domainMin = geometryConfig.radialScale.domain()[0]; var generator = {}; generator.bar = function(d, i, pI) { var dataConfig = _config[pI].data; var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0); var stackTop = geometryConfig.radialScale(d[2] || 0); var w = dataConfig.barWidth; d3.select(this).attr({ 'class': 'mark bar', d: 'M' + [ [ h + stackTop, -w / 2 ], [ h + stackTop, w / 2 ], [ stackTop, w / 2 ], [ stackTop, -w / 2 ] ].join('L') + 'Z', transform: function(d, i) { return 'rotate(' + (geometryConfig.orientation + angularScale(d[0])) + ')'; } }); }; generator.dot = function(d, i, pI) { var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d; var symbol = d3.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i); d3.select(this).attr({ 'class': 'mark dot', d: symbol, transform: function(d, i) { var coord = convertToCartesian(getPolarCoordinates(stackedData)); return 'translate(' + [ coord.x, coord.y ] + ')'; } }); }; var line = d3.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) { return geometryConfig.radialScale(d[1]); }).angle(function(d) { return geometryConfig.angularScale(d[0]) * Math.PI / 180; }); generator.line = function(d, i, pI) { var lineData = d[2] ? data[pI].map(function(d, i) { return [ d[0], d[1] + d[2] ]; }) : data[pI]; d3.select(this).each(generator['dot']).style({ opacity: function(dB, iB) { return +_config[pI].data.dotVisible; }, fill: markStyle.stroke(d, i, pI) }).attr({ 'class': 'mark dot' }); if (i > 0) return; var lineSelection = d3.select(this.parentNode).selectAll('path.line').data([ 0 ]); lineSelection.enter().insert('path'); lineSelection.attr({ 'class': 'line', d: line(lineData), transform: function(dB, iB) { return 'rotate(' + (geometryConfig.orientation + 90) + ')'; }, 'pointer-events': 'none' }).style({ fill: function(dB, iB) { return markStyle.fill(d, i, pI); }, 'fill-opacity': 0, stroke: function(dB, iB) { return markStyle.stroke(d, i, pI); }, 'stroke-width': function(dB, iB) { return markStyle['stroke-width'](d, i, pI); }, 'stroke-dasharray': function(dB, iB) { return markStyle['stroke-dasharray'](d, i, pI); }, opacity: function(dB, iB) { return markStyle.opacity(d, i, pI); }, display: function(dB, iB) { return markStyle.display(d, i, pI); } }); }; var angularRange = geometryConfig.angularScale.range(); var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180; var arc = d3.svg.arc().startAngle(function(d) { return -triangleAngle / 2; }).endAngle(function(d) { return triangleAngle / 2; }).innerRadius(function(d) { return geometryConfig.radialScale(domainMin + (d[2] || 0)); }).outerRadius(function(d) { return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]); }); generator.arc = function(d, i, pI) { d3.select(this).attr({ 'class': 'mark arc', d: arc, transform: function(d, i) { return 'rotate(' + (geometryConfig.orientation + angularScale(d[0]) + 90) + ')'; } }); }; var markStyle = { fill: function(d, i, pI) { return _config[pI].data.color; }, stroke: function(d, i, pI) { return _config[pI].data.strokeColor; }, 'stroke-width': function(d, i, pI) { return _config[pI].data.strokeSize + 'px'; }, 'stroke-dasharray': function(d, i, pI) { return dashArray[_config[pI].data.strokeDash]; }, opacity: function(d, i, pI) { return _config[pI].data.opacity; }, display: function(d, i, pI) { return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none'; } }; var geometryLayer = d3.select(this).selectAll('g.layer').data(data); geometryLayer.enter().append('g').attr({ 'class': 'layer' }); var geometry = geometryLayer.selectAll('path.mark').data(function(d, i) { return d; }); geometry.enter().append('path').attr({ 'class': 'mark' }); geometry.style(markStyle).each(generator[geometryConfig.geometryType]); geometry.exit().remove(); geometryLayer.exit().remove(); function getPolarCoordinates(d, i) { var r = geometryConfig.radialScale(d[1]); var t = (geometryConfig.angularScale(d[0]) + geometryConfig.orientation) * Math.PI / 180; return { r: r, t: t }; } function convertToCartesian(polarCoordinates) { var x = polarCoordinates.r * Math.cos(polarCoordinates.t); var y = polarCoordinates.r * Math.sin(polarCoordinates.t); return { x: x, y: y }; } }); } exports.config = function(_x) { if (!arguments.length) return config; _x.forEach(function(d, i) { if (!config[i]) config[i] = {}; extendDeepAll(config[i], µ.PolyChart.defaultConfig()); extendDeepAll(config[i], d); }); return this; }; exports.getColorScale = function() { return colorScale; }; d3.rebind(exports, dispatch, 'on'); return exports; }; µ.PolyChart.defaultConfig = function() { var config = { data: { name: 'geom1', t: [ [ 1, 2, 3, 4 ] ], r: [ [ 1, 2, 3, 4 ] ], dotType: 'circle', dotSize: 64, dotVisible: false, barWidth: 20, color: '#ffa500', strokeSize: 1, strokeColor: 'silver', strokeDash: 'solid', opacity: 1, index: 0, visible: true, visibleInLegend: true }, geometryConfig: { geometry: 'LinePlot', geometryType: 'arc', direction: 'clockwise', orientation: 0, container: 'body', radialScale: null, angularScale: null, colorScale: d3.scale.category20() } }; return config; }; µ.BarChart = function module() { return µ.PolyChart(); }; µ.BarChart.defaultConfig = function() { var config = { geometryConfig: { geometryType: 'bar' } }; return config; }; µ.AreaChart = function module() { return µ.PolyChart(); }; µ.AreaChart.defaultConfig = function() { var config = { geometryConfig: { geometryType: 'arc' } }; return config; }; µ.DotPlot = function module() { return µ.PolyChart(); }; µ.DotPlot.defaultConfig = function() { var config = { geometryConfig: { geometryType: 'dot', dotType: 'circle' } }; return config; }; µ.LinePlot = function module() { return µ.PolyChart(); }; µ.LinePlot.defaultConfig = function() { var config = { geometryConfig: { geometryType: 'line' } }; return config; }; µ.Legend = function module() { var config = µ.Legend.defaultConfig(); var dispatch = d3.dispatch('hover'); function exports() { var legendConfig = config.legendConfig; var flattenData = config.data.map(function(d, i) { return [].concat(d).map(function(dB, iB) { var element = extendDeepAll({}, legendConfig.elements[i]); element.name = dB; element.color = [].concat(legendConfig.elements[i].color)[iB]; return element; }); }); var data = d3.merge(flattenData); data = data.filter(function(d, i) { return legendConfig.elements[i] && (legendConfig.elements[i].visibleInLegend || typeof legendConfig.elements[i].visibleInLegend === 'undefined'); }); if (legendConfig.reverseOrder) data = data.reverse(); var container = legendConfig.container; if (typeof container == 'string' || container.nodeName) container = d3.select(container); var colors = data.map(function(d, i) { return d.color; }); var lineHeight = legendConfig.fontSize; var isContinuous = legendConfig.isContinuous == null ? typeof data[0] === 'number' : legendConfig.isContinuous; var height = isContinuous ? legendConfig.height : lineHeight * data.length; var legendContainerGroup = container.classed('legend-group', true); var svg = legendContainerGroup.selectAll('svg').data([ 0 ]); var svgEnter = svg.enter().append('svg').attr({ width: 300, height: height + lineHeight, xmlns: 'http://www.w3.org/2000/svg', 'xmlns:xlink': 'http://www.w3.org/1999/xlink', version: '1.1' }); svgEnter.append('g').classed('legend-axis', true); svgEnter.append('g').classed('legend-marks', true); var dataNumbered = d3.range(data.length); var colorScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors); var dataScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]); var shapeGenerator = function(_type, _size) { var squareSize = _size * 3; if (_type === 'line') { return 'M' + [ [ -_size / 2, -_size / 12 ], [ _size / 2, -_size / 12 ], [ _size / 2, _size / 12 ], [ -_size / 2, _size / 12 ] ] + 'Z'; } else if (d3.svg.symbolTypes.indexOf(_type) != -1) return d3.svg.symbol().type(_type).size(squareSize)(); else return d3.svg.symbol().type('square').size(squareSize)(); }; if (isContinuous) { var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({ id: 'grad1', x1: '0%', y1: '0%', x2: '0%', y2: '100%' }).selectAll('stop').data(colors); gradient.enter().append('stop'); gradient.attr({ offset: function(d, i) { return i / (colors.length - 1) * 100 + '%'; } }).style({ 'stop-color': function(d, i) { return d; } }); svg.append('rect').classed('legend-mark', true).attr({ height: legendConfig.height, width: legendConfig.colorBandWidth, fill: 'url(#grad1)' }); } else { var legendElement = svg.select('.legend-marks').selectAll('path.legend-mark').data(data); legendElement.enter().append('path').classed('legend-mark', true); legendElement.attr({ transform: function(d, i) { return 'translate(' + [ lineHeight / 2, dataScale(i) + lineHeight / 2 ] + ')'; }, d: function(d, i) { var symbolType = d.symbol; return shapeGenerator(symbolType, lineHeight); }, fill: function(d, i) { return colorScale(i); } }); legendElement.exit().remove(); } var legendAxis = d3.svg.axis().scale(dataScale).orient('right'); var axis = svg.select('g.legend-axis').attr({ transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')' }).call(legendAxis); axis.selectAll('.domain').style({ fill: 'none', stroke: 'none' }); axis.selectAll('line').style({ fill: 'none', stroke: isContinuous ? legendConfig.textColor : 'none' }); axis.selectAll('text').style({ fill: legendConfig.textColor, 'font-size': legendConfig.fontSize }).text(function(d, i) { return data[i].name; }); return exports; } exports.config = function(_x) { if (!arguments.length) return config; extendDeepAll(config, _x); return this; }; d3.rebind(exports, dispatch, 'on'); return exports; }; µ.Legend.defaultConfig = function(d, i) { var config = { data: [ 'a', 'b', 'c' ], legendConfig: { elements: [ { symbol: 'line', color: 'red' }, { symbol: 'square', color: 'yellow' }, { symbol: 'diamond', color: 'limegreen' } ], height: 150, colorBandWidth: 30, fontSize: 12, container: 'body', isContinuous: null, textColor: 'grey', reverseOrder: false } }; return config; }; µ.tooltipPanel = function() { var tooltipEl, tooltipTextEl, backgroundEl; var config = { container: null, hasTick: false, fontSize: 12, color: 'white', padding: 5 }; var id = 'tooltip-' + µ.tooltipPanel.uid++; var tickSize = 10; var exports = function() { tooltipEl = config.container.selectAll('g.' + id).data([ 0 ]); var tooltipEnter = tooltipEl.enter().append('g').classed(id, true).style({ 'pointer-events': 'none', display: 'none' }); backgroundEl = tooltipEnter.append('path').style({ fill: 'white', 'fill-opacity': .9 }).attr({ d: 'M0 0' }); tooltipTextEl = tooltipEnter.append('text').attr({ dx: config.padding + tickSize, dy: +config.fontSize * .3 }); return exports; }; exports.text = function(_text) { var l = d3.hsl(config.color).l; var strokeColor = l >= .5 ? '#aaa' : 'white'; var fillColor = l >= .5 ? 'black' : 'white'; var text = _text || ''; tooltipTextEl.style({ fill: fillColor, 'font-size': config.fontSize + 'px' }).text(text); var padding = config.padding; var bbox = tooltipTextEl.node().getBBox(); var boxStyle = { fill: config.color, stroke: strokeColor, 'stroke-width': '2px' }; var backGroundW = bbox.width + padding * 2 + tickSize; var backGroundH = bbox.height + padding * 2; backgroundEl.attr({ d: 'M' + [ [ tickSize, -backGroundH / 2 ], [ tickSize, -backGroundH / 4 ], [ config.hasTick ? 0 : tickSize, 0 ], [ tickSize, backGroundH / 4 ], [ tickSize, backGroundH / 2 ], [ backGroundW, backGroundH / 2 ], [ backGroundW, -backGroundH / 2 ] ].join('L') + 'Z' }).style(boxStyle); tooltipEl.attr({ transform: 'translate(' + [ tickSize, -backGroundH / 2 + padding * 2 ] + ')' }); tooltipEl.style({ display: 'block' }); return exports; }; exports.move = function(_pos) { if (!tooltipEl) return; tooltipEl.attr({ transform: 'translate(' + [ _pos[0], _pos[1] ] + ')' }).style({ display: 'block' }); return exports; }; exports.hide = function() { if (!tooltipEl) return; tooltipEl.style({ display: 'none' }); return exports; }; exports.show = function() { if (!tooltipEl) return; tooltipEl.style({ display: 'block' }); return exports; }; exports.config = function(_x) { extendDeepAll(config, _x); return exports; }; return exports; }; µ.tooltipPanel.uid = 1; µ.adapter = {}; µ.adapter.plotly = function module() { var exports = {}; exports.convert = function(_inputConfig, reverse) { var outputConfig = {}; if (_inputConfig.data) { outputConfig.data = _inputConfig.data.map(function(d, i) { var r = extendDeepAll({}, d); var toTranslate = [ [ r, [ 'marker', 'color' ], [ 'color' ] ], [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ], [ r, [ 'marker', 'line', 'color' ], [ 'strokeColor' ] ], [ r, [ 'marker', 'line', 'dash' ], [ 'strokeDash' ] ], [ r, [ 'marker', 'line', 'width' ], [ 'strokeSize' ] ], [ r, [ 'marker', 'symbol' ], [ 'dotType' ] ], [ r, [ 'marker', 'size' ], [ 'dotSize' ] ], [ r, [ 'marker', 'barWidth' ], [ 'barWidth' ] ], [ r, [ 'line', 'interpolation' ], [ 'lineInterpolation' ] ], [ r, [ 'showlegend' ], [ 'visibleInLegend' ] ] ]; toTranslate.forEach(function(d, i) { µ.util.translator.apply(null, d.concat(reverse)); }); if (!reverse) delete r.marker; if (reverse) delete r.groupId; if (!reverse) { if (r.type === 'scatter') { if (r.mode === 'lines') r.geometry = 'LinePlot'; else if (r.mode === 'markers') r.geometry = 'DotPlot'; else if (r.mode === 'lines+markers') { r.geometry = 'LinePlot'; r.dotVisible = true; } } else if (r.type === 'area') r.geometry = 'AreaChart'; else if (r.type === 'bar') r.geometry = 'BarChart'; delete r.mode; delete r.type; } else { if (r.geometry === 'LinePlot') { r.type = 'scatter'; if (r.dotVisible === true) { delete r.dotVisible; r.mode = 'lines+markers'; } else r.mode = 'lines'; } else if (r.geometry === 'DotPlot') { r.type = 'scatter'; r.mode = 'markers'; } else if (r.geometry === 'AreaChart') r.type = 'area'; else if (r.geometry === 'BarChart') r.type = 'bar'; delete r.geometry; } return r; }); if (!reverse && _inputConfig.layout && _inputConfig.layout.barmode === 'stack') { var duplicates = µ.util.duplicates(outputConfig.data.map(function(d, i) { return d.geometry; })); outputConfig.data.forEach(function(d, i) { var idx = duplicates.indexOf(d.geometry); if (idx != -1) outputConfig.data[i].groupId = idx; }); } } if (_inputConfig.layout) { var r = extendDeepAll({}, _inputConfig.layout); var toTranslate = [ [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ], [ r, [ 'showlegend' ], [ 'showLegend' ] ], [ r, [ 'radialaxis' ], [ 'radialAxis' ] ], [ r, [ 'angularaxis' ], [ 'angularAxis' ] ], [ r.angularaxis, [ 'showline' ], [ 'gridLinesVisible' ] ], [ r.angularaxis, [ 'showticklabels' ], [ 'labelsVisible' ] ], [ r.angularaxis, [ 'nticks' ], [ 'ticksCount' ] ], [ r.angularaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ], [ r.angularaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ], [ r.angularaxis, [ 'range' ], [ 'domain' ] ], [ r.angularaxis, [ 'endpadding' ], [ 'endPadding' ] ], [ r.radialaxis, [ 'showline' ], [ 'gridLinesVisible' ] ], [ r.radialaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ], [ r.radialaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ], [ r.radialaxis, [ 'range' ], [ 'domain' ] ], [ r.angularAxis, [ 'showline' ], [ 'gridLinesVisible' ] ], [ r.angularAxis, [ 'showticklabels' ], [ 'labelsVisible' ] ], [ r.angularAxis, [ 'nticks' ], [ 'ticksCount' ] ], [ r.angularAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ], [ r.angularAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ], [ r.angularAxis, [ 'range' ], [ 'domain' ] ], [ r.angularAxis, [ 'endpadding' ], [ 'endPadding' ] ], [ r.radialAxis, [ 'showline' ], [ 'gridLinesVisible' ] ], [ r.radialAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ], [ r.radialAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ], [ r.radialAxis, [ 'range' ], [ 'domain' ] ], [ r.font, [ 'outlinecolor' ], [ 'outlineColor' ] ], [ r.legend, [ 'traceorder' ], [ 'reverseOrder' ] ], [ r, [ 'labeloffset' ], [ 'labelOffset' ] ], [ r, [ 'defaultcolorrange' ], [ 'defaultColorRange' ] ] ]; toTranslate.forEach(function(d, i) { µ.util.translator.apply(null, d.concat(reverse)); }); if (!reverse) { if (r.angularAxis && typeof r.angularAxis.ticklen !== 'undefined') r.tickLength = r.angularAxis.ticklen; if (r.angularAxis && typeof r.angularAxis.tickcolor !== 'undefined') r.tickColor = r.angularAxis.tickcolor; } else { if (typeof r.tickLength !== 'undefined') { r.angularaxis.ticklen = r.tickLength; delete r.tickLength; } if (r.tickColor) { r.angularaxis.tickcolor = r.tickColor; delete r.tickColor; } } if (r.legend && typeof r.legend.reverseOrder != 'boolean') { r.legend.reverseOrder = r.legend.reverseOrder != 'normal'; } if (r.legend && typeof r.legend.traceorder == 'boolean') { r.legend.traceorder = r.legend.traceorder ? 'reversed' : 'normal'; delete r.legend.reverseOrder; } if (r.margin && typeof r.margin.t != 'undefined') { var source = [ 't', 'r', 'b', 'l', 'pad' ]; var target = [ 'top', 'right', 'bottom', 'left', 'pad' ]; var margin = {}; d3.entries(r.margin).forEach(function(dB, iB) { margin[target[source.indexOf(dB.key)]] = dB.value; }); r.margin = margin; } if (reverse) { delete r.needsEndSpacing; delete r.minorTickColor; delete r.minorTicks; delete r.angularaxis.ticksCount; delete r.angularaxis.ticksCount; delete r.angularaxis.ticksStep; delete r.angularaxis.rewriteTicks; delete r.angularaxis.nticks; delete r.radialaxis.ticksCount; delete r.radialaxis.ticksCount; delete r.radialaxis.ticksStep; delete r.radialaxis.rewriteTicks; delete r.radialaxis.nticks; } outputConfig.layout = r; } return outputConfig; }; return exports; }; /***/ }), /***/ "3a9c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var setGroupPositions = __webpack_require__("0cec").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; } } } }; /***/ }), /***/ "3aa8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var extractOpts = __webpack_require__("215c").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); } }; /***/ }), /***/ "3af0": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var glslify = __webpack_require__("e98f"); var vertexShaderSource = glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nattribute vec4 p01_04, p05_08, p09_12, p13_16,\n p17_20, p21_24, p25_28, p29_32,\n p33_36, p37_40, p41_44, p45_48,\n p49_52, p53_56, p57_60, colors;\n\nuniform mat4 dim0A, dim1A, dim0B, dim1B, dim0C, dim1C, dim0D, dim1D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution, viewBoxPos, viewBoxSize;\nuniform sampler2D mask, palette;\nuniform float maskHeight;\nuniform float drwLayer; // 0: context, 1: focus, 2: pick\nuniform vec4 contextColor;\n\nbool isPick = (drwLayer > 1.5);\nbool isContext = (drwLayer < 0.5);\n\nconst vec4 ZEROS = vec4(0.0, 0.0, 0.0, 0.0);\nconst vec4 UNITS = vec4(1.0, 1.0, 1.0, 1.0);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * UNITS, UNITS);\n}\n\nfloat axisY(float ratio, mat4 A, mat4 B, mat4 C, mat4 D) {\n float y1 = val(A, dim0A) + val(B, dim0B) + val(C, dim0C) + val(D, dim0D);\n float y2 = val(A, dim1A) + val(B, dim1B) + val(C, dim1C) + val(D, dim1D);\n return y1 * (1.0 - ratio) + y2 * ratio;\n}\n\nint iMod(int a, int b) {\n return a - b * (a / b);\n}\n\nbool fOutside(float p, float lo, float hi) {\n return (lo < hi) && (lo > p || p > hi);\n}\n\nbool vOutside(vec4 p, vec4 lo, vec4 hi) {\n return (\n fOutside(p[0], lo[0], hi[0]) ||\n fOutside(p[1], lo[1], hi[1]) ||\n fOutside(p[2], lo[2], hi[2]) ||\n fOutside(p[3], lo[3], hi[3])\n );\n}\n\nbool mOutside(mat4 p, mat4 lo, mat4 hi) {\n return (\n vOutside(p[0], lo[0], hi[0]) ||\n vOutside(p[1], lo[1], hi[1]) ||\n vOutside(p[2], lo[2], hi[2]) ||\n vOutside(p[3], lo[3], hi[3])\n );\n}\n\nbool outsideBoundingBox(mat4 A, mat4 B, mat4 C, mat4 D) {\n return mOutside(A, loA, hiA) ||\n mOutside(B, loB, hiB) ||\n mOutside(C, loC, hiC) ||\n mOutside(D, loD, hiD);\n}\n\nbool outsideRasterMask(mat4 A, mat4 B, mat4 C, mat4 D) {\n mat4 pnts[4];\n pnts[0] = A;\n pnts[1] = B;\n pnts[2] = C;\n pnts[3] = D;\n\n for(int i = 0; i < 4; ++i) {\n for(int j = 0; j < 4; ++j) {\n for(int k = 0; k < 4; ++k) {\n if(0 == iMod(\n int(255.0 * texture2D(mask,\n vec2(\n (float(i * 2 + j / 2) + 0.5) / 8.0,\n (pnts[i][j][k] * (maskHeight - 1.0) + 1.0) / maskHeight\n ))[3]\n ) / int(pow(2.0, float(iMod(j * 4 + k, 8)))),\n 2\n )) return true;\n }\n }\n }\n return false;\n}\n\nvec4 position(bool isContext, float v, mat4 A, mat4 B, mat4 C, mat4 D) {\n float x = 0.5 * sign(v) + 0.5;\n float y = axisY(x, A, B, C, D);\n float z = 1.0 - abs(v);\n\n z += isContext ? 0.0 : 2.0 * float(\n outsideBoundingBox(A, B, C, D) ||\n outsideRasterMask(A, B, C, D)\n );\n\n return vec4(\n 2.0 * (vec2(x, y) * viewBoxSize + viewBoxPos) / resolution - 1.0,\n z,\n 1.0\n );\n}\n\nvoid main() {\n mat4 A = mat4(p01_04, p05_08, p09_12, p13_16);\n mat4 B = mat4(p17_20, p21_24, p25_28, p29_32);\n mat4 C = mat4(p33_36, p37_40, p41_44, p45_48);\n mat4 D = mat4(p49_52, p53_56, p57_60, ZEROS);\n\n float v = colors[3];\n\n gl_Position = position(isContext, v, A, B, C, D);\n\n fragColor =\n isContext ? vec4(contextColor) :\n isPick ? vec4(colors.rgb, 1.0) : texture2D(palette, vec2(abs(v), 0.5));\n}\n"]); var fragmentShaderSource = glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}\n"]); var maxDim = __webpack_require__("f7a4").maxDimensionCount; var Lib = __webpack_require__("fc26"); // 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) { var dims = [[], []]; for(var k = 0; k < 64; k++) { dims[0][k] = (k === i0) ? 1 : 0; dims[1][k] = (k === i1) ? 1 : 0; } var overdrag = model.lines.canvasOverdrag; var domain = model.domain; var canvasWidth = model.canvasWidth; var canvasHeight = model.canvasHeight; var deselectedLinesColor = model.deselectedLines.color; 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, deselectedLinesColor[3] < 1 ? deselectedLinesColor[3] : Math.max(1 / 255, Math.pow(1 / model.lines.color.length, 1 / 3)) ], scissorX: (itemNumber === leftmost ? 0 : x + overdrag) + (model.pad.l - overdrag) + model.layoutWidth * domain.x[0], scissorWidth: (itemNumber === rightmost ? canvasWidth - x + overdrag : panelSizeX + 0.5) + (itemNumber === leftmost ? x + overdrag : 0), scissorY: y + model.pad.b + model.layoutHeight * domain.y[0], scissorHeight: panelSizeY, viewportX: model.pad.l - overdrag + model.layoutWidth * domain.x[0], viewportY: model.pad.b + model.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 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: 1, 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'), mask: 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; 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 ); 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 }; }; /***/ }), /***/ "3b74": /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var meta_1 = __webpack_require__("716c"); // Note: change RADIUS => earthRadius var RADIUS = 6378137; /** * Takes one or more features and returns their area in square meters. * * @name area * @param {GeoJSON} geojson input GeoJSON feature(s) * @returns {number} area in square meters * @example * var polygon = turf.polygon([[[125, -15], [113, -22], [154, -27], [144, -15], [125, -15]]]); * * var area = turf.area(polygon); * * //addToMap * var addToMap = [polygon] * polygon.properties.area = area */ function area(geojson) { return meta_1.geomReduce(geojson, function (value, geom) { return value + calculateArea(geom); }, 0); } exports.default = area; /** * Calculate Area * * @private * @param {Geometry} geom GeoJSON Geometries * @returns {number} area */ function calculateArea(geom) { var total = 0; var i; switch (geom.type) { case "Polygon": return polygonArea(geom.coordinates); case "MultiPolygon": for (i = 0; i < geom.coordinates.length; i++) { total += polygonArea(geom.coordinates[i]); } return total; case "Point": case "MultiPoint": case "LineString": case "MultiLineString": return 0; } return 0; } function polygonArea(coords) { var total = 0; if (coords && coords.length > 0) { total += Math.abs(ringArea(coords[0])); for (var i = 1; i < coords.length; i++) { total -= Math.abs(ringArea(coords[i])); } } return total; } /** * @private * Calculate the approximate area of the polygon were it projected onto the earth. * Note that this area will be positive if ring is oriented clockwise, otherwise it will be negative. * * Reference: * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for Polygons on a Sphere", * JPL Publication 07-03, Jet Propulsion * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409 * * @param {Array>} coords Ring Coordinates * @returns {number} The approximate signed geodesic area of the polygon in square meters. */ function ringArea(coords) { var p1; var p2; var p3; var lowerIndex; var middleIndex; var upperIndex; var i; var total = 0; var coordsLength = coords.length; if (coordsLength > 2) { for (i = 0; i < coordsLength; i++) { if (i === coordsLength - 2) { lowerIndex = coordsLength - 2; middleIndex = coordsLength - 1; upperIndex = 0; } else if (i === coordsLength - 1) { lowerIndex = coordsLength - 1; middleIndex = 0; upperIndex = 1; } else { lowerIndex = i; middleIndex = i + 1; upperIndex = i + 2; } p1 = coords[lowerIndex]; p2 = coords[middleIndex]; p3 = coords[upperIndex]; total += (rad(p3[0]) - rad(p1[0])) * Math.sin(rad(p2[1])); } total = total * RADIUS * RADIUS / 2; } return total; } function rad(num) { return num * Math.PI / 180; } /***/ }), /***/ "3b80": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("5aae"), supplyDefaults: __webpack_require__("2705"), colorbar: __webpack_require__("f3cf"), formatLabels: __webpack_require__("a2ee"), calc: __webpack_require__("fcb7"), plot: __webpack_require__("b8b2"), style: __webpack_require__("52e8").style, styleOnSelect: __webpack_require__("52e8").styleOnSelect, hoverPoints: __webpack_require__("e92c"), selectPoints: __webpack_require__("214c"), eventData: __webpack_require__("0271"), moduleType: 'trace', name: 'scattercarpet', basePlotModule: __webpack_require__("91cd"), categories: ['svg', 'carpet', 'symbols', 'showLegend', 'carpetDependent', 'zoomScale'], meta: { } }; /***/ }), /***/ "3bd6": /***/ (function(module, exports, __webpack_require__) { "use strict"; var rationalize = __webpack_require__("2195") module.exports = mul function mul(a, b) { return rationalize(a[0].mul(b[0]), a[1].mul(b[1])) } /***/ }), /***/ "3c1c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var constants = __webpack_require__("d301"); // 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.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; }; exports.cleanId = function cleanId(id, axLetter) { if(!id.match(constants.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); if(axNum === '1') axNum = ''; return id.charAt(0) + axNum; }; // 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; 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); }; 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; }; /***/ }), /***/ "3c31": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * 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)); }; } } /***/ }), /***/ "3c41": /***/ (function(module, exports) { module.exports = clone /** * Creates a new vec4 initialized with values from an existing vector * * @param {vec4} a vector to clone * @returns {vec4} a new 4D vector */ function clone (a) { var out = new Float32Array(4) out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[3] return out } /***/ }), /***/ "3cf3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var scatterFormatLabels = __webpack_require__("7e96"); 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); }; /***/ }), /***/ "3d2e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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: '▼' } }; /***/ }), /***/ "3d78": /***/ (function(module, exports, __webpack_require__) { "use strict"; var vectorizeText = __webpack_require__("b993") module.exports = getGlyph var GLYPH_CACHE = {} function getGlyph(symbol, font, pixelRatio) { var fontCache = GLYPH_CACHE[font] if(!fontCache) { fontCache = GLYPH_CACHE[font] = {} } if(symbol in fontCache) { return fontCache[symbol] } var config = { textAlign: "center", textBaseline: "middle", lineHeight: 1.0, font: font, 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 < triSymbol.positions.length; ++i){ for(j = 0; j < triSymbol.positions[i].length; ++j){ triSymbol.positions[i][j] /= pixelRatio; } } for(i = 0; i < lineSymbol.positions.length; ++i){ for(j = 0; j < lineSymbol.positions[i].length; ++j){ lineSymbol.positions[i][j] /= pixelRatio; } } } //Calculate bounding box var bounds = [[Infinity,Infinity], [-Infinity,-Infinity]] var n = lineSymbol.positions.length for(i = 0; i < n; ++i) { var p = lineSymbol.positions[i] for(j=0; j<2; ++j) { bounds[0][j] = Math.min(bounds[0][j], p[j]) bounds[1][j] = Math.max(bounds[1][j], p[j]) } } //Save cached symbol return fontCache[symbol] = [triSymbol, lineSymbol, bounds] } /***/ }), /***/ "3dac": /***/ (function(module, exports, __webpack_require__) { "use strict"; var bnsign = __webpack_require__("0fba") module.exports = sign function sign(x) { return bnsign(x[0]) * bnsign(x[1]) } /***/ }), /***/ "3de2": /***/ (function(module, exports, __webpack_require__) { "use strict"; var pick = __webpack_require__("b7d1") module.exports = parseRect function parseRect (arg) { var rect // direct arguments sequence if (arguments.length > 1) { arg = arguments } // svg viewbox if (typeof arg === 'string') { arg = arg.split(/\s/).map(parseFloat) } else if (typeof arg === 'number') { arg = [arg] } // 0, 0, 100, 100 - array-like if (arg.length && typeof arg[0] === 'number') { // [w, w] if (arg.length === 1) { rect = { width: arg[0], height: arg[0], x: 0, y: 0 } } // [w, h] else if (arg.length === 2) { rect = { width: arg[0], height: arg[1], x: 0, y: 0 } } // [l, t, r, b] else { rect = { x: arg[0], y: arg[1], width: (arg[2] - arg[0]) || 0, height: (arg[3] - arg[1]) || 0 } } } // {x, y, w, h} or {l, t, b, r} else if (arg) { arg = pick(arg, { left: 'x l left Left', top: 'y t top Top', width: 'w width W Width', height: 'h height W Width', bottom: 'b bottom Bottom', right: 'r right Right' }) rect = { x: arg.left || 0, y: arg.top || 0 } if (arg.width == null) { if (arg.right) rect.width = arg.right - rect.x else rect.width = 0 } else { rect.width = arg.width } if (arg.height == null) { if (arg.bottom) rect.height = arg.bottom - rect.y else rect.height = 0 } else { rect.height = arg.height } } return rect } /***/ }), /***/ "3e11": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var parcats = __webpack_require__("cf9f"); /** * 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 ); }; /***/ }), /***/ "3e43": /***/ (function(module, exports, __webpack_require__) { /* * World Calendars * https://github.com/alexcjohnson/world-calendars * * Batch-converted from kbwood/calendars * Many thanks to Keith Wood and all of the contributors to the original project! * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* http://keith-wood.name/calendars.html Islamic calendar for jQuery v2.0.2. Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009. Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ var main = __webpack_require__("0230"); var assign = __webpack_require__("320c"); /** Implementation of the Islamic or '16 civil' calendar. Based on code from http://www.iranchamber.com/calendar/converter/iranian_calendar_converter.php. See also http://en.wikipedia.org/wiki/Islamic_calendar. @class IslamicCalendar @param [language=''] {string} The language code (default English) for localisation. */ function IslamicCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } IslamicCalendar.prototype = new main.baseCalendar; assign(IslamicCalendar.prototype, { /** The calendar name. @memberof IslamicCalendar */ name: 'Islamic', /** Julian date of start of Islamic epoch: 16 July 622 CE. @memberof IslamicCalendar */ jdEpoch: 1948439.5, /** Days per month in a common year. @memberof IslamicCalendar */ daysPerMonth: [30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29], /** true if has a year zero, false if not. @memberof IslamicCalendar */ hasYearZero: false, /** The minimum month number. @memberof IslamicCalendar */ minMonth: 1, /** The first month in the year. @memberof IslamicCalendar */ firstMonth: 1, /** The minimum day number. @memberof IslamicCalendar */ minDay: 1, /** Localisations for the plugin. Entries are objects indexed by the language code ('' being the default US/English). Each object has the following attributes. @memberof IslamicCalendar @property name {string} The calendar name. @property epochs {string[]} The epoch names. @property monthNames {string[]} The long names of the months of the year. @property monthNamesShort {string[]} The short names of the months of the year. @property dayNames {string[]} The long names of the days of the week. @property dayNamesShort {string[]} The short names of the days of the week. @property dayNamesMin {string[]} The minimal names of the days of the week. @property dateFormat {string} The date format for this calendar. See the options on formatDate for details. @property firstDay {number} The number of the first day of the week, starting at 0. @property isRTL {number} true if this localisation reads right-to-left. */ regionalOptions: { // Localisations '': { name: 'Islamic', epochs: ['BH', 'AH'], monthNames: ['Muharram', 'Safar', 'Rabi\' al-awwal', 'Rabi\' al-thani', 'Jumada al-awwal', 'Jumada al-thani', 'Rajab', 'Sha\'aban', 'Ramadan', 'Shawwal', 'Dhu al-Qi\'dah', 'Dhu al-Hijjah'], monthNamesShort: ['Muh', 'Saf', 'Rab1', 'Rab2', 'Jum1', 'Jum2', 'Raj', 'Sha\'', 'Ram', 'Shaw', 'DhuQ', 'DhuH'], dayNames: ['Yawm al-ahad', 'Yawm al-ithnayn', 'Yawm ath-thulaathaa\'', 'Yawm al-arbi\'aa\'', 'Yawm al-khamīs', 'Yawm al-jum\'a', 'Yawm as-sabt'], dayNamesShort: ['Aha', 'Ith', 'Thu', 'Arb', 'Kha', 'Jum', 'Sab'], dayNamesMin: ['Ah','It','Th','Ar','Kh','Ju','Sa'], digits: null, dateFormat: 'yyyy/mm/dd', firstDay: 6, isRTL: false } }, /** Determine whether this date is in a leap year. @memberof IslamicCalendar @param year {CDate|number} The date to examine or the year to examine. @return {boolean} true if this is a leap year, false if not. @throws Error if an invalid year or a different calendar used. */ leapYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear); return (date.year() * 11 + 14) % 30 < 11; }, /** Determine the week of the year for a date. @memberof IslamicCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {number} The week of the year. @throws Error if an invalid date or a different calendar used. */ weekOfYear: function(year, month, day) { // Find Sunday of this week starting on Sunday var checkDate = this.newDate(year, month, day); checkDate.add(-checkDate.dayOfWeek(), 'd'); return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1; }, /** Retrieve the number of days in a year. @memberof IslamicCalendar @param year {CDate|number} The date to examine or the year to examine. @return {number} The number of days. @throws Error if an invalid year or a different calendar used. */ daysInYear: function(year) { return (this.leapYear(year) ? 355 : 354); }, /** Retrieve the number of days in a month. @memberof IslamicCalendar @param year {CDate|number} The date to examine or the year of the month. @param [month] {number} The month. @return {number} The number of days in this month. @throws Error if an invalid month/year or a different calendar used. */ daysInMonth: function(year, month) { var date = this._validate(year, month, this.minDay, main.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0); }, /** Determine whether this date is a week day. @memberof IslamicCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {boolean} true if a week day, false if not. @throws Error if an invalid date or a different calendar used. */ weekDay: function(year, month, day) { return this.dayOfWeek(year, month, day) !== 5; }, /** Retrieve the Julian date equivalent for this date, i.e. days since January 1, 4713 BCE Greenwich noon. @memberof IslamicCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(year, month, day) { var date = this._validate(year, month, day, main.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); year = (year <= 0 ? year + 1 : year); return day + Math.ceil(29.5 * (month - 1)) + (year - 1) * 354 + Math.floor((3 + (11 * year)) / 30) + this.jdEpoch - 1; }, /** Create a new date from a Julian date. @memberof IslamicCalendar @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { jd = Math.floor(jd) + 0.5; var year = Math.floor((30 * (jd - this.jdEpoch) + 10646) / 10631); year = (year <= 0 ? year - 1 : year); var month = Math.min(12, Math.ceil((jd - 29 - this.toJD(year, 1, 1)) / 29.5) + 1); var day = jd - this.toJD(year, month, 1) + 1; return this.newDate(year, month, day); } }); // Islamic (16 civil) calendar implementation main.calendars.islamic = IslamicCalendar; /***/ }), /***/ "3e8e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { treemapcolorway: { valType: 'colorlist', editType: 'calc', }, extendtreemapcolors: { valType: 'boolean', dflt: true, editType: 'calc', } }; /***/ }), /***/ "3e97": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; return out; }; /***/ }), /***/ "3eab": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("77ae"); /***/ }), /***/ "3ee9": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("6b50"), supplyDefaults: __webpack_require__("b6f7"), calc: __webpack_require__("6dea"), colorbar: { min: 'cmin', max: 'cmax' }, plot: __webpack_require__("54a9"), moduleType: 'trace', name: 'mesh3d', basePlotModule: __webpack_require__("134c"), categories: ['gl3d', 'showLegend'], meta: { } }; /***/ }), /***/ "3efe": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("a18b"); /***/ }), /***/ "3f57": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("e5c5") /***/ }), /***/ "3fb2": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Plots = __webpack_require__("bb71"); var PlotSchema = __webpack_require__("6921"); var dfltConfig = __webpack_require__("3ff5").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) { 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 isInfoArray = (nestedSchema || {}).valType === 'info_array'; var isColorscale = (nestedSchema || {}).valType === 'colorscale'; var items = (nestedSchema || {}).items; if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } else if(isPlainObject(valIn) && isPlainObject(valOut)) { 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; } /***/ }), /***/ "3fca": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var mapboxgl = __webpack_require__("e192"); var Fx = __webpack_require__("a5c4"); var Lib = __webpack_require__("fc26"); var geoUtils = __webpack_require__("0919"); var Registry = __webpack_require__("371e"); var Axes = __webpack_require__("0642"); var dragElement = __webpack_require__("4efe"); var prepSelect = __webpack_require__("1876").prepSelect; var selectOnClick = __webpack_require__("1876").selectOnClick; var constants = __webpack_require__("b5e4"); var createMapboxLayer = __webpack_require__("d0d2"); 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); // store access token associated with this map self.accessToken = opts.accesstoken; // 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, 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); if(self.styleObj.id !== styleObj.id) { 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(); // some hackery to get Fx.hover to work evt.clientX = evt.point.x + bb.left; evt.clientY = evt.point.y + bb.top; evt.target.getBoundingClientRect = function() { return bb; }; self.xaxis.p2c = function() { return evt.lngLat.lng; }; self.yaxis.p2c = function() { return evt.lngLat.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.clearSelect = function() { gd._fullLayout._zoomlayer.selectAll('.select-outline').remove(); }; /** * 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; if(dragMode === 'select') { fillRangeItems = function(eventData, poly) { var ranges = eventData.range = {}; ranges[self.id] = [ invert([poly.xmin, poly.ymin]), invert([poly.xmax, poly.ymax]) ]; }; } else { fillRangeItems = function(eventData, poly, pts) { var dataPts = eventData.lassoPoints = {}; dataPts[self.id] = pts.filtered.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 || {}, { element: self.div, gd: gd, plotinfo: { id: self.id, 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(dragMode === 'select' || dragMode === 'lasso') { map.dragPan.disable(); map.on('zoomstart', self.clearSelect); 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.clearSelect); self.div.onmousedown = null; // 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 center = { lon: mapCenter.lng, lat: mapCenter.lat }; var canvas = map.getCanvas(); var w = canvas.width; var h = canvas.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) { 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]; } 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; /***/ }), /***/ "3fe8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); 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; }; /***/ }), /***/ "3ff5": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * This will be transferred over to gd and overridden by * config args to Plotly.plot. * * 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, }, plotlyServerURL: { valType: 'string', dflt: 'https://plot.ly', }, 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, } }, 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 }; /***/ }), /***/ "3ff7": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { xaxis: { valType: 'subplotid', dflt: 'x', editType: 'calc+clearAxisTypes', }, yaxis: { valType: 'subplotid', dflt: 'y', editType: 'calc+clearAxisTypes', } }; /***/ }), /***/ "402e": /***/ (function(module, exports, __webpack_require__) { "use strict"; var createShader = __webpack_require__("28dd") var createBuffer = __webpack_require__("efce") var pool = __webpack_require__("cea5") var SHADERS = __webpack_require__("c9eb") 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 < pointCount; i++) { packedId[i] = i } } this.points = data this.offsetBuffer.update(packed) this.pickBuffer.update(packedId) if(!dataStraightThrough) { pool.free(packed) } if(!idStraightThrough) { pool.free(packedId) } this.pointCount = pointCount this.pickOffset = 0 } function count(points, dataBox) { var visiblePointCountEstimate = 0 var length = points.length >>> 1 var i for(i = 0; i < length; i++) { var x = points[i * 2] var y = points[i * 2 + 1] if(x >= 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 || 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 } /***/ }), /***/ "4051": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var helpers = __webpack_require__("2969f"); var calcHover = __webpack_require__("98e7").calcHover; function hoverPoints(pointData, xval, yval) { 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++) { 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(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 }; /***/ }), /***/ "409f": /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var meta_1 = __webpack_require__("716c"); /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @name bbox * @param {GeoJSON} geojson any GeoJSON object * @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order * @example * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]); * var bbox = turf.bbox(line); * var bboxPolygon = turf.bboxPolygon(bbox); * * //addToMap * var addToMap = [line, bboxPolygon] */ function bbox(geojson) { var result = [Infinity, Infinity, -Infinity, -Infinity]; meta_1.coordEach(geojson, function (coord) { if (result[0] > coord[0]) { result[0] = coord[0]; } if (result[1] > coord[1]) { result[1] = coord[1]; } if (result[2] < coord[0]) { result[2] = coord[0]; } if (result[3] < coord[1]) { result[3] = coord[1]; } }); return result; } exports.default = bbox; /***/ }), /***/ "40c0": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var barAttrs = __webpack_require__("fb5a"); var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var makeBinAttrs = __webpack_require__("4274"); var constants = __webpack_require__("8d0e"); var extendFlat = __webpack_require__("9092").extendFlat; module.exports = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', }, y: { valType: 'data_array', editType: 'calc+clearAxisTypes', }, 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 }), marker: barAttrs.marker, offsetgroup: barAttrs.offsetgroup, alignmentgroup: barAttrs.alignmentgroup, selected: barAttrs.selected, unselected: barAttrs.unselected, _deprecated: { bardir: barAttrs._deprecated.bardir } }; /***/ }), /***/ "40ce": /***/ (function(module, exports, __webpack_require__) { "use strict"; var createThunk = __webpack_require__("d37d") function Procedure() { this.argTypes = [] this.shimArgs = [] this.arrayArgs = [] this.arrayBlockIndices = [] this.scalarArgs = [] this.offsetArgs = [] this.offsetArgIndex = [] this.indexArgs = [] this.shapeArgs = [] this.funcName = "" this.pre = null this.body = null this.post = null this.debug = false } function compileCwise(user_args) { //Create procedure var proc = new Procedure() //Parse blocks proc.pre = user_args.pre proc.body = user_args.body proc.post = user_args.post //Parse arguments var proc_args = user_args.args.slice(0) proc.argTypes = proc_args for(var i=0; i0) { throw new Error("cwise: pre() block may not reference array args") } if(i < proc.post.args.length && proc.post.args[i].count>0) { throw new Error("cwise: post() block may not reference array args") } } else if(arg_type === "scalar") { proc.scalarArgs.push(i) proc.shimArgs.push("scalar" + i) } else if(arg_type === "index") { proc.indexArgs.push(i) if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { throw new Error("cwise: pre() block may not reference array index") } if(i < proc.body.args.length && proc.body.args[i].lvalue) { throw new Error("cwise: body() block may not write to array index") } if(i < proc.post.args.length && proc.post.args[i].count > 0) { throw new Error("cwise: post() block may not reference array index") } } else if(arg_type === "shape") { proc.shapeArgs.push(i) if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { throw new Error("cwise: pre() block may not write to array shape") } if(i < proc.body.args.length && proc.body.args[i].lvalue) { throw new Error("cwise: body() block may not write to array shape") } if(i < proc.post.args.length && proc.post.args[i].lvalue) { throw new Error("cwise: post() block may not write to array shape") } } else if(typeof arg_type === "object" && arg_type.offset) { proc.argTypes[i] = "offset" proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) proc.offsetArgIndex.push(i) } else { throw new Error("cwise: Unknown argument type " + proc_args[i]) } } //Make sure at least one array argument was specified if(proc.arrayArgs.length <= 0) { throw new Error("cwise: No array arguments specified") } //Make sure arguments are correct if(proc.pre.args.length > proc_args.length) { throw new Error("cwise: Too many arguments in pre() block") } if(proc.body.args.length > proc_args.length) { throw new Error("cwise: Too many arguments in body() block") } if(proc.post.args.length > proc_args.length) { throw new Error("cwise: Too many arguments in post() block") } //Check debug flag proc.debug = !!user_args.printCode || !!user_args.debug //Retrieve name proc.funcName = user_args.funcName || "cwise" //Read in block size proc.blockSize = user_args.blockSize || 64 return createThunk(proc) } module.exports = compileCwise /***/ }), /***/ "4136": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); module.exports = function calcSelection(cd, trace) { if(Lib.isArrayOrTypedArray(trace.selectedpoints)) { Lib.tagSelected(cd, trace); } }; /***/ }), /***/ "4160": /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__("23e7"); var forEach = __webpack_require__("17c2"); // `Array.prototype.forEach` method // https://tc39.github.io/ecma262/#sec-array.prototype.foreach $({ target: 'Array', proto: true, forced: [].forEach != forEach }, { forEach: forEach }); /***/ }), /***/ "4168": /***/ (function(module, exports, __webpack_require__) { "use strict"; var bsearch = __webpack_require__("7fcc") var m4interp = __webpack_require__("8b23") var invert44 = __webpack_require__("9343") var rotateX = __webpack_require__("e9e1") var rotateY = __webpack_require__("44fe") var rotateZ = __webpack_require__("fc11") var lookAt = __webpack_require__("e581") var translate = __webpack_require__("6f51") var scale = __webpack_require__("9ca2") var normalize = __webpack_require__("913b") var DEFAULT_CENTER = [0,0,0] module.exports = createMatrixCameraController function MatrixCameraController(initialMatrix) { this._components = initialMatrix.slice() this._time = [0] this.prevMatrix = initialMatrix.slice() this.nextMatrix = initialMatrix.slice() this.computedMatrix = initialMatrix.slice() this.computedInverse = initialMatrix.slice() this.computedEye = [0,0,0] this.computedUp = [0,0,0] this.computedCenter = [0,0,0] this.computedRadius = [0] this._limits = [-Infinity, Infinity] } var proto = MatrixCameraController.prototype proto.recalcMatrix = function(t) { var time = this._time var tidx = bsearch.le(time, t) var mat = this.computedMatrix if(tidx < 0) { return } var comps = this._components if(tidx === time.length-1) { var ptr = 16*tidx for(var i=0; i<16; ++i) { mat[i] = comps[ptr++] } } else { var dt = (time[tidx+1] - time[tidx]) var ptr = 16*tidx var prev = this.prevMatrix var allEqual = true for(var i=0; i<16; ++i) { prev[i] = comps[ptr++] } var next = this.nextMatrix for(var i=0; i<16; ++i) { next[i] = comps[ptr++] allEqual = allEqual && (prev[i] === next[i]) } if(dt < 1e-6 || allEqual) { for(var i=0; i<16; ++i) { mat[i] = prev[i] } } else { m4interp(mat, prev, next, (t - time[tidx])/dt) } } var up = this.computedUp up[0] = mat[1] up[1] = mat[5] up[2] = mat[9] normalize(up, up) var imat = this.computedInverse invert44(imat, mat) var eye = this.computedEye var w = imat[15] eye[0] = imat[12]/w eye[1] = imat[13]/w eye[2] = imat[14]/w var center = this.computedCenter var radius = Math.exp(this.computedRadius[0]) for(var i=0; i<3; ++i) { center[i] = eye[i] - mat[2+4*i] * radius } } proto.idle = function(t) { if(t < this.lastT()) { return } var mc = this._components var ptr = mc.length-16 for(var i=0; i<16; ++i) { mc.push(mc[ptr++]) } this._time.push(t) } proto.flush = function(t) { var idx = bsearch.gt(this._time, t) - 2 if(idx < 0) { return } this._time.splice(0, idx) this._components.splice(0, 16*idx) } proto.lastT = function() { return this._time[this._time.length-1] } proto.lookAt = function(t, eye, center, up) { this.recalcMatrix(t) eye = eye || this.computedEye center = center || DEFAULT_CENTER up = up || this.computedUp this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up)) var d2 = 0.0 for(var i=0; i<3; ++i) { d2 += Math.pow(center[i] - eye[i], 2) } d2 = Math.log(Math.sqrt(d2)) this.computedRadius[0] = d2 } proto.rotate = function(t, yaw, pitch, roll) { this.recalcMatrix(t) var mat = this.computedInverse if(yaw) rotateY(mat, mat, yaw) if(pitch) rotateX(mat, mat, pitch) if(roll) rotateZ(mat, mat, roll) this.setMatrix(t, invert44(this.computedMatrix, mat)) } var tvec = [0,0,0] proto.pan = function(t, dx, dy, dz) { tvec[0] = -(dx || 0.0) tvec[1] = -(dy || 0.0) tvec[2] = -(dz || 0.0) this.recalcMatrix(t) var mat = this.computedInverse translate(mat, mat, tvec) this.setMatrix(t, invert44(mat, mat)) } proto.translate = function(t, dx, dy, dz) { tvec[0] = dx || 0.0 tvec[1] = dy || 0.0 tvec[2] = dz || 0.0 this.recalcMatrix(t) var mat = this.computedMatrix translate(mat, mat, tvec) this.setMatrix(t, mat) } proto.setMatrix = function(t, mat) { if(t < this.lastT()) { return } this._time.push(t) for(var i=0; i<16; ++i) { this._components.push(mat[i]) } } proto.setDistance = function(t, d) { this.computedRadius[0] = d } proto.setDistanceLimits = function(a,b) { var lim = this._limits lim[0] = a lim[1] = b } proto.getDistanceLimits = function(out) { var lim = this._limits if(out) { out[0] = lim[0] out[1] = lim[1] return out } return lim } function createMatrixCameraController(options) { options = options || {} var matrix = options.matrix || [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] return new MatrixCameraController(matrix) } /***/ }), /***/ "4183": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var hasColorbar = __webpack_require__("7089"); var colorbarDefaults = __webpack_require__("8f2a"); var isValidScale = __webpack_require__("4852").isValid; var traceIs = __webpack_require__("371e").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); } } }; /***/ }), /***/ "4190": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var handleXYDefaults = __webpack_require__("37bf"); var handleABDefaults = __webpack_require__("8da3"); var attributes = __webpack_require__("e7bd"); var colorAttrs = __webpack_require__("dfb3"); 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'); 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'); } }; /***/ }), /***/ "41a1": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = cmp function cmp(a, b) { return a[0].mul(b[1]).cmp(b[0].mul(a[1])) } /***/ }), /***/ "41e0": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); 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(traceIn.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; } 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); } /***/ }), /***/ "41f8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorscaleDefaults = __webpack_require__("4183"); var handleLabelDefaults = __webpack_require__("6533"); 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); }; /***/ }), /***/ "422c": /***/ (function(module, exports) { module.exports = rotateX; /** * Rotate a 3D vector around the x-axis * @param {vec3} out The receiving vec3 * @param {vec3} a The vec3 point to rotate * @param {vec3} b The origin of the rotation * @param {Number} c The angle of rotation * @returns {vec3} out */ function rotateX(out, a, b, c){ var by = b[1] var bz = b[2] // Translate point to the origin var py = a[1] - by var pz = a[2] - bz var sc = Math.sin(c) var cc = Math.cos(c) // perform rotation and translate to correct position out[0] = a[0] out[1] = by + py * cc - pz * sc out[2] = bz + py * sc + pz * cc return out } /***/ }), /***/ "4248": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); 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() { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; if(!hasLegacyPolar) { Registry.getComponentMethod('colorbar', 'draw')(gd); } }; }; exports.encodeSVG = function(svg) { return 'data:image/svg+xml,' + encodeURIComponent(svg); }; var DOM_URL = window.URL || window.webkitURL; exports.createObjectURL = function(blob) { return DOM_URL.createObjectURL(blob); }; exports.revokeObjectURL = function(url) { return DOM_URL.revokeObjectURL(url); }; exports.createBlob = function(url, format) { if(format === 'svg') { return new window.Blob([url], {type: 'image/svg+xml;charset=utf-8'}); } else { var binary = fixBinary(window.atob(url)); return new window.Blob([binary], {type: 'image/' + format}); } }; exports.octetStream = function(s) { document.location.href = 'data:application/octet-stream' + s; }; // Taken from https://bl.ocks.org/nolanlawson/0eac306e4dac2114c752 function fixBinary(b) { var len = b.length; var buf = new ArrayBuffer(len); var arr = new Uint8Array(buf); for(var i = 0; i < len; i++) { arr[i] = b.charCodeAt(i); } return buf; } exports.IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/; exports.MSG_IE_BAD_FORMAT = 'Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'; /***/ }), /***/ "424b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); // 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'); } } }; /***/ }), /***/ "4274": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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' }; }; /***/ }), /***/ "428d": /***/ (function(module, exports, __webpack_require__) { !function(t,e){ true?module.exports=e(__webpack_require__("2ad6"),__webpack_require__("f7fe")):undefined}(this,function(t,e){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="/",e(0)}([function(t,e,n){var r,o,i;!function(s,u){o=[t,e,n(10),n(38),n(39),n(9),n(37)],r=u,i="function"==typeof r?r.apply(e,o):r,!(void 0!==i&&(t.exports=i))}(this,function(t,e,n,r,o){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function s(t){if(!t)return{delay:_,initial:!1};var e=t.initial,n=void 0!==e&&e,r=(0,h.default)(t).map(function(t){return parseInt(t)}).find(function(t){return!isNaN(t)});return r=r||_,{delay:r,initial:n}}function u(t,e){var n={root:document.documentElement},r=new IntersectionObserver(function(t,n){t.forEach(function(t){t.isIntersecting&&(e(),n.disconnect())})},n);return r.observe(t),r}function c(t,e){var n=e.value,r=e.arg,o=e.options,i=function(){return n(t)};switch(r){case"debounce":i=v(function(){return n(t)},o.delay);break;case"throttle":i=v(function(){return n(t)},o.delay,{leading:!0,trailing:!0,maxWait:o.delay})}var s=new l.default(t,i);return o.initial&&n(t),s}function a(t,e,n){var r=e.value,o=e.arg,i=e.modifiers,h=n.context;if(!r||"function"!=typeof r)return void console.warn("v-resize should received a function as value");var l=s(i);return h&&h.$el===t&&h.$once("hook:deactivated",function(){f(t),h.$once("hook:activated",function(){a(t,{value:r,arg:o,modifiers:i},{context:h})})}),t.offsetParent?void c(t,{value:r,arg:o,options:l}):(l.initial=!0,void(t.__visibility__listener__=u(t,function(){return c(t,{value:r,arg:o,options:l})})))}function f(t){t.__visibility__listener__&&t.__visibility__listener__.disconnect(),t.resizeSensor&&l.default.detach(t)}Object.defineProperty(e,"__esModule",{value:!0});var h=i(n),l=i(r),p=i(o),d=p.default.debounce,v=void 0===d?p.default:d,_=150;e.default={inserted:a,unbind:f},t.exports=e.default})},function(t,e){var n=t.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(t,e,n){t.exports=!n(3)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e,n){var r=n(23),o=n(6);t.exports=function(t){return r(o(t))}},function(t,e,n){var r,o,i;!function(n,s){o=[],r=s,i="function"==typeof r?r.apply(e,o):r,!(void 0!==i&&(t.exports=i))}(this,function(){"use strict";Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(t){if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),n=e.length>>>0;if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var r=arguments[1],o=0;of;)if(u=c[f++],u!=u)return!0}else for(;a>f;f++)if((t||f in c)&&c[f]===n)return t||f||0;return!t&&-1}}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){var r=n(12);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}}},function(t,e,n){var r=n(5),o=n(4).document,i=r(o)&&r(o.createElement);t.exports=function(t){return i?o.createElement(t):{}}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){var r=n(4),o=n(1),i=n(16),s=n(21),u="prototype",c=function(t,e,n){var a,f,h,l=t&c.F,p=t&c.G,d=t&c.S,v=t&c.P,_=t&c.B,y=t&c.W,g=p?o:o[e]||(o[e]={}),b=g[u],m=p?r:d?r[e]:(r[e]||{})[u];p&&(n=e);for(a in n)f=!l&&m&&void 0!==m[a],f&&a in g||(h=f?m[a]:n[a],g[a]=p&&"function"!=typeof m[a]?n[a]:_&&f?i(h,r):y&&m[a]==h?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e[u]=t[u],e}(h):v&&"function"==typeof h?i(Function.call,h):h,v&&((g.virtual||(g.virtual={}))[a]=h,t&c.R&&b&&!b[a]&&s(b,a,h)))};c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,t.exports=c},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(24),o=n(28);t.exports=n(2)?function(t,e,n){return r.f(t,e,o(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){t.exports=!n(2)&&!n(3)(function(){return 7!=Object.defineProperty(n(17)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(15);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e,n){var r=n(13),o=n(22),i=n(34),s=Object.defineProperty;e.f=n(2)?Object.defineProperty:function(t,e,n){if(r(t),e=i(e,!0),r(n),o)try{return s(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){var r=n(20),o=n(8),i=n(14)(!1),s=n(29)("IE_PROTO");t.exports=function(t,e){var n,u=o(t),c=0,a=[];for(n in u)n!=s&&r(u,n)&&a.push(n);for(;e.length>c;)r(u,n=e[c++])&&(~i(a,n)||a.push(n));return a}},function(t,e,n){var r=n(25),o=n(18);t.exports=Object.keys||function(t){return r(t,o)}},function(t,e,n){var r=n(19),o=n(1),i=n(3);t.exports=function(t,e){var n=(o.Object||{})[t]||Object[t],s={};s[t]=e(n),r(r.S+r.F*i(function(){n(1)}),"Object",s)}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var r=n(30)("keys"),o=n(35);t.exports=function(t){return r[t]||(r[t]=o(t))}},function(t,e,n){var r=n(4),o="__core-js_shared__",i=r[o]||(r[o]={});t.exports=function(t){return i[t]||(i[t]={})}},function(t,e,n){var r=n(7),o=Math.max,i=Math.min;t.exports=function(t,e){return t=r(t),t<0?o(t+e,0):i(t,e)}},function(t,e,n){var r=n(7),o=Math.min;t.exports=function(t){return t>0?o(r(t),9007199254740991):0}},function(t,e,n){var r=n(6);t.exports=function(t){return Object(r(t))}},function(t,e,n){var r=n(5);t.exports=function(t,e){if(!r(t))return t;var n,o;if(e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;if("function"==typeof(n=t.valueOf)&&!r(o=n.call(t)))return o;if(!e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e,n){var r=n(33),o=n(26);n(27)("keys",function(){return function(t){return o(r(t))}})},function(t,e){!function(t,e){"use strict";function n(t){this.time=t.time,this.target=t.target,this.rootBounds=t.rootBounds,this.boundingClientRect=t.boundingClientRect,this.intersectionRect=t.intersectionRect||f(),this.isIntersecting=!!t.intersectionRect;var e=this.boundingClientRect,n=e.width*e.height,r=this.intersectionRect,o=r.width*r.height;n?this.intersectionRatio=o/n:this.intersectionRatio=this.isIntersecting?1:0}function r(t,e){var n=e||{};if("function"!=typeof t)throw new Error("callback must be a function");if(n.root&&1!=n.root.nodeType)throw new Error("root must be an Element");this._checkForIntersections=i(this._checkForIntersections.bind(this),this.THROTTLE_TIMEOUT),this._callback=t,this._observationTargets=[],this._queuedEntries=[],this._rootMarginValues=this._parseRootMargin(n.rootMargin),this.thresholds=this._initThresholds(n.threshold),this.root=n.root||null,this.rootMargin=this._rootMarginValues.map(function(t){return t.value+t.unit}).join(" ")}function o(){return t.performance&&performance.now&&performance.now()}function i(t,e){var n=null;return function(){n||(n=setTimeout(function(){t(),n=null},e))}}function s(t,e,n,r){"function"==typeof t.addEventListener?t.addEventListener(e,n,r||!1):"function"==typeof t.attachEvent&&t.attachEvent("on"+e,n)}function u(t,e,n,r){"function"==typeof t.removeEventListener?t.removeEventListener(e,n,r||!1):"function"==typeof t.detatchEvent&&t.detatchEvent("on"+e,n)}function c(t,e){var n=Math.max(t.top,e.top),r=Math.min(t.bottom,e.bottom),o=Math.max(t.left,e.left),i=Math.min(t.right,e.right),s=i-o,u=r-n;return s>=0&&u>=0&&{top:n,bottom:r,left:o,right:i,width:s,height:u}}function a(t){var e;try{e=t.getBoundingClientRect()}catch(t){}return e?(e.width&&e.height||(e={top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.right-e.left,height:e.bottom-e.top}),e):f()}function f(){return{top:0,bottom:0,left:0,right:0,width:0,height:0}}function h(t,e){for(var n=e;n;){if(n==t)return!0;n=l(n)}return!1}function l(t){var e=t.parentNode;return e&&11==e.nodeType&&e.host?e.host:e}if("IntersectionObserver"in t&&"IntersectionObserverEntry"in t&&"intersectionRatio"in t.IntersectionObserverEntry.prototype)return void("isIntersecting"in t.IntersectionObserverEntry.prototype||Object.defineProperty(t.IntersectionObserverEntry.prototype,"isIntersecting",{get:function(){return this.intersectionRatio>0}}));var p=[];r.prototype.THROTTLE_TIMEOUT=100,r.prototype.POLL_INTERVAL=null,r.prototype.USE_MUTATION_OBSERVER=!0,r.prototype.observe=function(t){var e=this._observationTargets.some(function(e){return e.element==t});if(!e){if(!t||1!=t.nodeType)throw new Error("target must be an Element");this._registerInstance(),this._observationTargets.push({element:t,entry:null}),this._monitorIntersections(),this._checkForIntersections()}},r.prototype.unobserve=function(t){this._observationTargets=this._observationTargets.filter(function(e){return e.element!=t}),this._observationTargets.length||(this._unmonitorIntersections(),this._unregisterInstance())},r.prototype.disconnect=function(){this._observationTargets=[],this._unmonitorIntersections(),this._unregisterInstance()},r.prototype.takeRecords=function(){var t=this._queuedEntries.slice();return this._queuedEntries=[],t},r.prototype._initThresholds=function(t){var e=t||[0];return Array.isArray(e)||(e=[e]),e.sort().filter(function(t,e,n){if("number"!=typeof t||isNaN(t)||t<0||t>1)throw new Error("threshold must be a number between 0 and 1 inclusively");return t!==n[e-1]})},r.prototype._parseRootMargin=function(t){var e=t||"0px",n=e.split(/\s+/).map(function(t){var e=/^(-?\d*\.?\d+)(px|%)$/.exec(t);if(!e)throw new Error("rootMargin must be specified in pixels or percent");return{value:parseFloat(e[1]),unit:e[2]}});return n[1]=n[1]||n[0],n[2]=n[2]||n[0],n[3]=n[3]||n[1],n},r.prototype._monitorIntersections=function(){this._monitoringIntersections||(this._monitoringIntersections=!0,this.POLL_INTERVAL?this._monitoringInterval=setInterval(this._checkForIntersections,this.POLL_INTERVAL):(s(t,"resize",this._checkForIntersections,!0),s(e,"scroll",this._checkForIntersections,!0),this.USE_MUTATION_OBSERVER&&"MutationObserver"in t&&(this._domObserver=new MutationObserver(this._checkForIntersections),this._domObserver.observe(e,{attributes:!0,childList:!0,characterData:!0,subtree:!0}))))},r.prototype._unmonitorIntersections=function(){this._monitoringIntersections&&(this._monitoringIntersections=!1,clearInterval(this._monitoringInterval),this._monitoringInterval=null,u(t,"resize",this._checkForIntersections,!0),u(e,"scroll",this._checkForIntersections,!0),this._domObserver&&(this._domObserver.disconnect(),this._domObserver=null))},r.prototype._checkForIntersections=function(){var t=this._rootIsInDom(),e=t?this._getRootRect():f();this._observationTargets.forEach(function(r){var i=r.element,s=a(i),u=this._rootContainsTarget(i),c=r.entry,f=t&&u&&this._computeTargetAndRootIntersection(i,e),h=r.entry=new n({time:o(),target:i,boundingClientRect:s,rootBounds:e,intersectionRect:f});c?t&&u?this._hasCrossedThreshold(c,h)&&this._queuedEntries.push(h):c&&c.isIntersecting&&this._queuedEntries.push(h):this._queuedEntries.push(h)},this),this._queuedEntries.length&&this._callback(this.takeRecords(),this)},r.prototype._computeTargetAndRootIntersection=function(n,r){if("none"!=t.getComputedStyle(n).display){for(var o=a(n),i=o,s=l(n),u=!1;!u;){var f=null,h=1==s.nodeType?t.getComputedStyle(s):{};if("none"==h.display)return;if(s==this.root||s==e?(u=!0,f=r):s!=e.body&&s!=e.documentElement&&"visible"!=h.overflow&&(f=a(s)),f&&(i=c(f,i),!i))break;s=l(s)}return i}},r.prototype._getRootRect=function(){var t;if(this.root)t=a(this.root);else{var n=e.documentElement,r=e.body;t={top:0,left:0,right:n.clientWidth||r.clientWidth,width:n.clientWidth||r.clientWidth,bottom:n.clientHeight||r.clientHeight,height:n.clientHeight||r.clientHeight}}return this._expandRectByRootMargin(t)},r.prototype._expandRectByRootMargin=function(t){var e=this._rootMarginValues.map(function(e,n){return"px"==e.unit?e.value:e.value*(n%2?t.width:t.height)/100}),n={top:t.top-e[0],right:t.right+e[1],bottom:t.bottom+e[2],left:t.left-e[3]};return n.width=n.right-n.left,n.height=n.bottom-n.top,n},r.prototype._hasCrossedThreshold=function(t,e){var n=t&&t.isIntersecting?t.intersectionRatio||0:-1,r=e.isIntersecting?e.intersectionRatio||0:-1;if(n!==r)for(var o=0;o 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]); } /***/ }), /***/ "4358": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isArrayOrTypedArray = __webpack_require__("6af8").isArrayOrTypedArray; var isPlainObject = __webpack_require__("1385"); /** * 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]; } } }; /***/ }), /***/ "4362": /***/ (function(module, exports, __webpack_require__) { exports.nextTick = function nextTick(fn) { var args = Array.prototype.slice.call(arguments); args.shift(); setTimeout(function () { fn.apply(null, args); }, 0); }; exports.platform = exports.arch = exports.execPath = exports.title = 'browser'; exports.pid = 1; exports.browser = true; exports.env = {}; exports.argv = []; exports.binding = function (name) { throw new Error('No such module. (Possibly not yet loaded)') }; (function () { var cwd = '/'; var path; exports.cwd = function () { return cwd }; exports.chdir = function (dir) { if (!path) path = __webpack_require__("df7c"); cwd = path.resolve(dir, cwd); }; })(); exports.exit = exports.kill = exports.umask = exports.dlopen = exports.uptime = exports.memoryUsage = exports.uvCounters = function() {}; exports.features = {}; /***/ }), /***/ "4393": /***/ (function(module, exports, __webpack_require__) { "use strict"; var bounds = __webpack_require__("a671") var NOT_FOUND = 0 var SUCCESS = 1 var EMPTY = 2 module.exports = createWrapper function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { this.mid = mid this.left = left this.right = right this.leftPoints = leftPoints this.rightPoints = rightPoints this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length } var proto = IntervalTreeNode.prototype function copy(a, b) { a.mid = b.mid a.left = b.left a.right = b.right a.leftPoints = b.leftPoints a.rightPoints = b.rightPoints a.count = b.count } function rebuild(node, intervals) { var ntree = createIntervalTree(intervals) node.mid = ntree.mid node.left = ntree.left node.right = ntree.right node.leftPoints = ntree.leftPoints node.rightPoints = ntree.rightPoints node.count = ntree.count } function rebuildWithInterval(node, interval) { var intervals = node.intervals([]) intervals.push(interval) rebuild(node, intervals) } function rebuildWithoutInterval(node, interval) { var intervals = node.intervals([]) var idx = intervals.indexOf(interval) if(idx < 0) { return NOT_FOUND } intervals.splice(idx, 1) rebuild(node, intervals) return SUCCESS } proto.intervals = function(result) { result.push.apply(result, this.leftPoints) if(this.left) { this.left.intervals(result) } if(this.right) { this.right.intervals(result) } return result } proto.insert = function(interval) { var weight = this.count - this.leftPoints.length this.count += 1 if(interval[1] < this.mid) { if(this.left) { if(4*(this.left.count+1) > 3*(weight+1)) { rebuildWithInterval(this, interval) } else { this.left.insert(interval) } } else { this.left = createIntervalTree([interval]) } } else if(interval[0] > this.mid) { if(this.right) { if(4*(this.right.count+1) > 3*(weight+1)) { rebuildWithInterval(this, interval) } else { this.right.insert(interval) } } else { this.right = createIntervalTree([interval]) } } else { var l = bounds.ge(this.leftPoints, interval, compareBegin) var r = bounds.ge(this.rightPoints, interval, compareEnd) this.leftPoints.splice(l, 0, interval) this.rightPoints.splice(r, 0, interval) } } proto.remove = function(interval) { var weight = this.count - this.leftPoints if(interval[1] < this.mid) { if(!this.left) { return NOT_FOUND } var rw = this.right ? this.right.count : 0 if(4 * rw > 3 * (weight-1)) { return rebuildWithoutInterval(this, interval) } var r = this.left.remove(interval) if(r === EMPTY) { this.left = null this.count -= 1 return SUCCESS } else if(r === SUCCESS) { this.count -= 1 } return r } else if(interval[0] > this.mid) { if(!this.right) { return NOT_FOUND } var lw = this.left ? this.left.count : 0 if(4 * lw > 3 * (weight-1)) { return rebuildWithoutInterval(this, interval) } var r = this.right.remove(interval) if(r === EMPTY) { this.right = null this.count -= 1 return SUCCESS } else if(r === SUCCESS) { this.count -= 1 } return r } else { if(this.count === 1) { if(this.leftPoints[0] === interval) { return EMPTY } else { return NOT_FOUND } } if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) { if(this.left && this.right) { var p = this var n = this.left while(n.right) { p = n n = n.right } if(p === this) { n.right = this.right } else { var l = this.left var r = this.right p.count -= n.count p.right = n.left n.left = l n.right = r } copy(this, n) this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length } else if(this.left) { copy(this, this.left) } else { copy(this, this.right) } return SUCCESS } for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l=0 && arr[i][1] >= lo; --i) { var r = cb(arr[i]) if(r) { return r } } } function reportRange(arr, cb) { for(var i=0; i this.mid) { if(this.right) { var r = this.right.queryPoint(x, cb) if(r) { return r } } return reportRightRange(this.rightPoints, x, cb) } else { return reportRange(this.leftPoints, cb) } } proto.queryInterval = function(lo, hi, cb) { if(lo < this.mid && this.left) { var r = this.left.queryInterval(lo, hi, cb) if(r) { return r } } if(hi > this.mid && this.right) { var r = this.right.queryInterval(lo, hi, cb) if(r) { return r } } if(hi < this.mid) { return reportLeftRange(this.leftPoints, hi, cb) } else if(lo > this.mid) { return reportRightRange(this.rightPoints, lo, cb) } else { return reportRange(this.leftPoints, cb) } } function compareNumbers(a, b) { return a - b } function compareBegin(a, b) { var d = a[0] - b[0] if(d) { return d } return a[1] - b[1] } function compareEnd(a, b) { var d = a[1] - b[1] if(d) { return d } return a[0] - b[0] } function createIntervalTree(intervals) { if(intervals.length === 0) { return null } var pts = [] for(var i=0; i>1] var leftIntervals = [] var rightIntervals = [] var centerIntervals = [] for(var i=0; i= 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 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(clickVal === false) return; if(numClicks === 1) { legend._clickTimeout = setTimeout(function() { 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); if(dblClickVal !== false) handleClick(legendItem, gd, numClicks); } } function drawTexts(g, gd) { var legendItem = g.data()[0][0]; var fullLayout = gd._fullLayout; var opts = fullLayout.legend; var trace = legendItem.trace; var isPieLike = Registry.traceIs(trace, 'pie-like'); var traceIndex = trace.index; var isEditable = gd._context.edits.legendText && !isPieLike; var maxNameLength = opts._maxNameLength; var name = isPieLike ? legendItem.label : trace.name; if(trace._meta) { name = Lib.templateString(name, trace._meta); } var textEl = Lib.ensureSingle(g, 'text', 'legendtext'); textEl.attr('text-anchor', 'start') .classed('user-select-none', true) .call(Drawing.font, opts.font) .text(isEditable ? ensureLength(name, maxNameLength) : name); svgTextUtils.positionText(textEl, constants.textGap, 0); if(isEditable) { textEl.call(svgTextUtils.makeEditable, {gd: gd, text: name}) .call(textLayout, g, gd) .on('edit', function(newName) { this.text(ensureLength(newName, maxNameLength)) .call(textLayout, g, gd); 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; } return Registry.call('_guiRestyle', gd, update, traceIndex); }); } else { textLayout(textEl, g, gd); } } /* * 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) { var doubleClickDelay = gd._context.doubleClickDelay; var newMouseDownTime; var numClicks = 1; var traceToggle = Lib.ensureSingle(g, 'rect', 'legendtoggle', function(s) { s.style('cursor', 'pointer') .attr('pointer-events', 'all') .call(Color.fill, 'rgba(0,0,0,0)'); }); 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.legend; 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) { svgTextUtils.convertToTspans(s, gd, function() { computeTextDimensions(g, gd); }); } function computeTextDimensions(g, gd) { var legendItem = g.data()[0][0]; if(legendItem && !legendItem.trace.showlegend) { g.remove(); return; } var mathjaxGroup = g.select('g[class*=math-group]'); var mathjaxNode = mathjaxGroup.node(); var bw = gd._fullLayout.legend.borderwidth; var opts = gd._fullLayout.legend; var lineHeight = (legendItem ? opts : opts.title).font.size * LINE_SPACING; var height, width; if(mathjaxNode) { var mathjaxBB = Drawing.bBox(mathjaxNode); height = mathjaxBB.height; width = mathjaxBB.width; if(legendItem) { Drawing.setTranslate(mathjaxGroup, 0, height * 0.25); } else { // case of title Drawing.setTranslate(mathjaxGroup, bw, height * 0.75 + bw); } } else { var textEl = g.select(legendItem ? '.legendtext' : '.legendtitletext' ); 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 var textY = lineHeight * ((textLines - 1) / 2 - 0.3); if(legendItem) { svgTextUtils.positionText(textEl, constants.textGap, -textY); } else { // case of title svgTextUtils.positionText(textEl, constants.titlePad + bw, lineHeight + bw); } } if(legendItem) { legendItem.lineHeight = lineHeight; legendItem.height = Math.max(height, 16) + 3; legendItem.width = width; } else { // case of title opts._titleWidth = width; opts._titleHeight = height; } } function getTitleSize(opts) { var w = 0; var h = 0; var side = opts.title.side; if(side) { if(side.indexOf('left') !== -1) { w = opts._titleWidth; } if(side.indexOf('top') !== -1) { h = opts._titleHeight; } } return [w, h]; } /* * Computes in fullLayout.legend: * * - _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) { var fullLayout = gd._fullLayout; var opts = fullLayout.legend; var gs = fullLayout._size; var isVertical = helpers.isVertical(opts); var isGrouped = helpers.isGrouped(opts); var bw = opts.borderwidth; var bw2 = 2 * bw; var textGap = constants.textGap; var itemGap = constants.itemGap; var endPad = 2 * (bw + itemGap); var yanchor = getYanchor(opts); var isBelowPlotArea = opts.y < 0 || (opts.y === 0 && yanchor === 'top'); var isAbovePlotArea = opts.y > 1 || (opts.y === 1 && yanchor === 'bottom'); // - if below/above plot area, give it the maximum potential margin-push value // - otherwise, extend the height of the plot area opts._maxHeight = Math.max( (isBelowPlotArea || isAbovePlotArea) ? fullLayout.height / 2 : gs.h, 30 ); var toggleRectWidth = 0; opts._width = 0; opts._height = 0; var titleSize = getTitleSize(opts); if(isVertical) { traces.each(function(d) { var h = d[0].height; Drawing.setTranslate(this, bw + titleSize[0], bw + titleSize[1] + opts._height + h / 2 + itemGap ); opts._height += h; opts._width = Math.max(opts._width, d[0].width); }); toggleRectWidth = textGap + opts._width; opts._width += itemGap + textGap + bw2; opts._height += endPad; if(isGrouped) { groups.each(function(d, i) { Drawing.setTranslate(this, 0, i * opts.tracegroupgap); }); opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; } } else { var xanchor = getXanchor(opts); var isLeftOfPlotArea = opts.x < 0 || (opts.x === 0 && xanchor === 'right'); var isRightOfPlotArea = opts.x > 1 || (opts.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 opts._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 = d[0].width + 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 h = d[0].height; Drawing.setTranslate(this, titleSize[0], titleSize[1] + bw + itemGap + h / 2 + offsetY ); offsetY += h; maxWidthInGroup = Math.max(maxWidthInGroup, textGap + d[0].width); }); maxGroupHeightInRow = Math.max(maxGroupHeightInRow, offsetY); var next = maxWidthInGroup + itemGap; if((next + bw + groupOffsetX) > opts._maxWidth) { maxRowWidth = Math.max(maxRowWidth, groupOffsetX); groupOffsetX = 0; groupOffsetY += maxGroupHeightInRow + opts.tracegroupgap; maxGroupHeightInRow = offsetY; } Drawing.setTranslate(this, groupOffsetX, groupOffsetY); groupOffsetX += next; }); opts._width = Math.max(maxRowWidth, groupOffsetX) + bw; opts._height = groupOffsetY + maxGroupHeightInRow + endPad; } else { var nTraces = traces.size(); var oneRowLegend = (combinedItemWidth + bw2 + (nTraces - 1) * itemGap) < opts._maxWidth; var maxItemHeightInRow = 0; var offsetX = 0; var offsetY = 0; var rowWidth = 0; traces.each(function(d) { var h = d[0].height; var w = textGap + d[0].width; var next = (oneRowLegend ? w : maxItemWidth) + itemGap; if((next + bw + offsetX) > opts._maxWidth) { maxRowWidth = Math.max(maxRowWidth, rowWidth); offsetX = 0; offsetY += maxItemHeightInRow; opts._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) { opts._width = offsetX + bw2; opts._height = maxItemHeightInRow + endPad; } else { opts._width = Math.max(maxRowWidth, rowWidth) + bw2; opts._height += maxItemHeightInRow + endPad; } } } opts._width = Math.ceil( Math.max( opts._width + titleSize[0], opts._titleWidth + 2 * (bw + constants.titlePad) ) ); opts._height = Math.ceil( Math.max( opts._height + titleSize[1], opts._titleHeight + 2 * (bw + constants.itemGap) ) ); opts._effHeight = Math.min(opts._height, opts._maxHeight); var edits = gd._context.edits; var isEditable = edits.legendText || edits.legendPosition; traces.each(function(d) { var traceToggle = d3.select(this).select('.legendtoggle'); var h = d[0].height; var w = isEditable ? textGap : (toggleRectWidth || (textGap + d[0].width)); if(!isVertical) w += itemGap / 2; Drawing.setRect(traceToggle, 0, -h / 2, w, h); }); } function expandMargin(gd) { var fullLayout = gd._fullLayout; var opts = fullLayout.legend; var xanchor = getXanchor(opts); var yanchor = getYanchor(opts); return Plots.autoMargin(gd, 'legend', { x: opts.x, y: opts.y, l: opts._width * (FROM_TL[xanchor]), r: opts._width * (FROM_BR[xanchor]), b: opts._effHeight * (FROM_BR[yanchor]), t: opts._effHeight * (FROM_TL[yanchor]) }); } function getXanchor(opts) { return Lib.isRightAnchor(opts) ? 'right' : Lib.isCenterAnchor(opts) ? 'center' : 'left'; } function getYanchor(opts) { return Lib.isBottomAnchor(opts) ? 'bottom' : Lib.isMiddleAnchor(opts) ? 'middle' : 'top'; } /***/ }), /***/ "43ef": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var heatmapAttrs = __webpack_require__("0435"); var scatterAttrs = __webpack_require__("107c"); var colorScaleAttrs = __webpack_require__("f4e9"); var dash = __webpack_require__("db54").dash; var fontAttrs = __webpack_require__("9845"); var extendFlat = __webpack_require__("9092").extendFlat; var filterOps = __webpack_require__("6c77"); var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2; var INTERVAL_OPS = filterOps.INTERVAL_OPS; var FORMAT_LINK = __webpack_require__("78df").FORMAT_LINK; 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, text: heatmapAttrs.text, hovertext: heatmapAttrs.hovertext, transpose: heatmapAttrs.transpose, xtype: heatmapAttrs.xtype, ytype: heatmapAttrs.ytype, zhoverformat: heatmapAttrs.zhoverformat, hovertemplate: heatmapAttrs.hovertemplate, 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', }, 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' } }, colorScaleAttrs('', { cLetter: 'z', autoColorDflt: false, editTypeOverride: 'calc' }) ); /***/ }), /***/ "442f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var main = __webpack_require__("b5e3"); exports.plot = main.plot; 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; exports.toImage = __webpack_require__("a288"); exports.validate = __webpack_require__("3fb2"); exports.downloadImage = __webpack_require__("ad91"); var templateApi = __webpack_require__("2d9a"); exports.makeTemplate = templateApi.makeTemplate; exports.validateTemplate = templateApi.validateTemplate; /***/ }), /***/ "447e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var attributes = __webpack_require__("86d2"); var constants = __webpack_require__("000c"); module.exports = function supplyDefaults(traceIn, traceOut) { function coerce(attr, dflt) { return Lib.coerce(traceIn, traceOut, attributes, attr, dflt); } var z = coerce('z'); if(z === undefined || !z.length || !z[0] || !z[0].length) { traceOut.visible = false; return; } coerce('x0'); coerce('y0'); coerce('dx'); coerce('dy'); var colormodel = coerce('colormodel'); coerce('zmin', constants.colormodel[colormodel].min); coerce('zmax', constants.colormodel[colormodel].max); coerce('text'); coerce('hovertext'); coerce('hovertemplate'); traceOut._length = null; }; /***/ }), /***/ "44ad": /***/ (function(module, exports, __webpack_require__) { var fails = __webpack_require__("d039"); var classof = __webpack_require__("c6b6"); var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings module.exports = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins return !Object('z').propertyIsEnumerable(0); }) ? function (it) { return classof(it) == 'String' ? split.call(it, '') : Object(it); } : Object; /***/ }), /***/ "44c3": /***/ (function(module, exports, __webpack_require__) { "use strict"; var createTexture = __webpack_require__("1d5b") 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; j 1) { 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; i maxFBOSize || 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; i maxFBOSize || 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) } /***/ }), /***/ "44d4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("ea27"); /***/ }), /***/ "44fe": /***/ (function(module, exports) { module.exports = rotateY; /** * Rotates a matrix by the given angle around the Y axis * * @param {mat4} out the receiving matrix * @param {mat4} a the matrix to rotate * @param {Number} rad the angle to rotate the matrix by * @returns {mat4} out */ function rotateY(out, a, rad) { var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; if (a !== out) { // If the source and destination differ, copy the unchanged rows out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; out[15] = a[15]; } // Perform axis-specific matrix multiplication out[0] = a00 * c - a20 * s; out[1] = a01 * c - a21 * s; out[2] = a02 * c - a22 * s; out[3] = a03 * c - a23 * s; out[8] = a00 * s + a20 * c; out[9] = a01 * s + a21 * c; out[10] = a02 * s + a22 * c; out[11] = a03 * s + a23 * c; return out; }; /***/ }), /***/ "45a2": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorAttrs = __webpack_require__("dfb3"); var domainAttrs = __webpack_require__("81f0").attributes; var axesAttrs = __webpack_require__("d798"); var overrideAll = __webpack_require__("cb34").overrideAll; var extendFlat = __webpack_require__("9092").extendFlat; var ternaryAxesAttrs = { title: { text: axesAttrs.title.text, font: axesAttrs.title.font // TODO does standoff here make sense? }, color: axesAttrs.color, // ticks tickmode: axesAttrs.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, showticklabels: axesAttrs.showticklabels, showtickprefix: axesAttrs.showtickprefix, tickprefix: axesAttrs.tickprefix, showticksuffix: axesAttrs.showticksuffix, ticksuffix: axesAttrs.ticksuffix, showexponent: axesAttrs.showexponent, exponentformat: axesAttrs.exponentformat, 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, 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', }; /***/ }), /***/ "45be": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorAttrs = __webpack_require__("dfb3"); var domainAttrs = __webpack_require__("81f0").attributes; var constants = __webpack_require__("0804"); var overrideAll = __webpack_require__("cb34").overrideAll; 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, } }; 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: Object.keys(constants.scopeDefaults), dflt: 'world', }, projection: { type: { valType: 'enumerated', values: Object.keys(constants.projNames), }, rotation: { lon: { valType: 'number', }, lat: { valType: 'number', }, roll: { valType: 'number', } }, 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', }; /***/ }), /***/ "4633": /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! * repeat-string * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ /** * Results cache */ var res = ''; var cache; /** * Expose `repeat` */ module.exports = repeat; /** * Repeat the given `string` the specified `number` * of times. * * **Example:** * * ```js * var repeat = require('repeat-string'); * repeat('A', 5); * //=> AAAAA * ``` * * @param {String} `string` The string to repeat * @param {Number} `number` The number of times to repeat the string * @return {String} Repeated string * @api public */ function repeat(str, num) { if (typeof str !== 'string') { throw new TypeError('expected a string'); } // cover common, quick use cases if (num === 1) return str; if (num === 2) return str + str; var max = str.length * num; if (cache !== str || typeof cache === 'undefined') { cache = str; res = ''; } else if (res.length >= max) { return res.substr(0, max); } while (max > res.length && num > 1) { if (num & 1) { res += str; } num >>= 1; str += str; } res += str; res = res.substr(0, max); return res; } /***/ }), /***/ "464d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); module.exports = function style(gd) { d3.select(gd).selectAll('.im image') .style('opacity', function(d) { return d.trace.opacity; }); }; /***/ }), /***/ "4665": /***/ (function(module, exports, __webpack_require__) { "use strict"; var callable = __webpack_require__("1a94") , forEach = __webpack_require__("6858") , call = Function.prototype.call; module.exports = function (obj, cb/*, thisArg*/) { var result = {}, thisArg = arguments[2]; callable(cb); forEach(obj, function (value, key, targetObj, index) { result[key] = call.call(cb, thisArg, value, key, targetObj, index); }); return result; }; /***/ }), /***/ "469b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); /* * 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); } }); } /***/ }), /***/ "46bc": /***/ (function(module, exports, __webpack_require__) { "use strict"; var inCircle = __webpack_require__("0b1d")[4] var bsearch = __webpack_require__("cc77") module.exports = delaunayRefine function testFlip(points, triangulation, stack, a, b, x) { var y = triangulation.opposite(a, b) //Test boundary edge if(y < 0) { return } //Swap edge if order flipped if(b < a) { var tmp = a a = b b = tmp tmp = x x = y y = tmp } //Test if edge is constrained if(triangulation.isConstraint(a, b)) { return } //Test if edge is delaunay if(inCircle(points[a], points[b], points[x], points[y]) < 0) { stack.push(a, b) } } //Assume edges are sorted lexicographically function delaunayRefine(points, triangulation) { var stack = [] var numPoints = points.length var stars = triangulation.stars for(var a=0; a 0) { 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) } } /***/ }), /***/ "46c1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("60c5"); /***/ }), /***/ "4746": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("48bb"); /***/ }), /***/ "47cc": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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 }; }; /***/ }), /***/ "4852": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var tinycolor = __webpack_require__("66cb"); 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 }; /***/ }), /***/ "487e": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createLines var createBuffer = __webpack_require__("efce") var createVAO = __webpack_require__("b205") var createShader = __webpack_require__("c185").line var MAJOR_AXIS = [0,0,0] var MINOR_AXIS = [0,0,0] var SCREEN_AXIS = [0,0,0] var OFFSET_VEC = [0,0,0] var SHAPE = [1,1] function zeroVec(a) { a[0] = a[1] = a[2] = 0 return a } function copyVec(a,b) { a[0] = b[0] a[1] = b[1] a[2] = b[2] return a } function Lines(gl, vertBuffer, vao, shader, tickCount, tickOffset, gridCount, gridOffset) { this.gl = gl this.vertBuffer = vertBuffer this.vao = vao this.shader = shader this.tickCount = tickCount this.tickOffset = tickOffset this.gridCount = gridCount this.gridOffset = gridOffset } var proto = Lines.prototype proto.bind = function(model, view, projection) { this.shader.bind() this.shader.uniforms.model = model this.shader.uniforms.view = view this.shader.uniforms.projection = projection SHAPE[0] = this.gl.drawingBufferWidth SHAPE[1] = this.gl.drawingBufferHeight this.shader.uniforms.screenShape = SHAPE this.vao.bind() } proto.unbind = function() { this.vao.unbind() } proto.drawAxisLine = function(j, bounds, offset, color, lineWidth) { var minorAxis = zeroVec(MINOR_AXIS) this.shader.uniforms.majorAxis = MINOR_AXIS minorAxis[j] = bounds[1][j] - bounds[0][j] this.shader.uniforms.minorAxis = minorAxis var noffset = copyVec(OFFSET_VEC, offset) noffset[j] += bounds[0][j] this.shader.uniforms.offset = noffset this.shader.uniforms.lineWidth = lineWidth this.shader.uniforms.color = color var screenAxis = zeroVec(SCREEN_AXIS) screenAxis[(j+2)%3] = 1 this.shader.uniforms.screenAxis = screenAxis this.vao.draw(this.gl.TRIANGLES, 6) var screenAxis = zeroVec(SCREEN_AXIS) screenAxis[(j+1)%3] = 1 this.shader.uniforms.screenAxis = screenAxis this.vao.draw(this.gl.TRIANGLES, 6) } proto.drawAxisTicks = function(j, offset, minorAxis, color, lineWidth) { if(!this.tickCount[j]) { return } var majorAxis = zeroVec(MAJOR_AXIS) majorAxis[j] = 1 this.shader.uniforms.majorAxis = majorAxis this.shader.uniforms.offset = offset this.shader.uniforms.minorAxis = minorAxis this.shader.uniforms.color = color this.shader.uniforms.lineWidth = lineWidth var screenAxis = zeroVec(SCREEN_AXIS) screenAxis[j] = 1 this.shader.uniforms.screenAxis = screenAxis this.vao.draw(this.gl.TRIANGLES, this.tickCount[j], this.tickOffset[j]) } proto.drawGrid = function(i, j, bounds, offset, color, lineWidth) { if(!this.gridCount[i]) { return } var minorAxis = zeroVec(MINOR_AXIS) minorAxis[j] = bounds[1][j] - bounds[0][j] this.shader.uniforms.minorAxis = minorAxis var noffset = copyVec(OFFSET_VEC, offset) noffset[j] += bounds[0][j] this.shader.uniforms.offset = noffset var majorAxis = zeroVec(MAJOR_AXIS) majorAxis[i] = 1 this.shader.uniforms.majorAxis = majorAxis var screenAxis = zeroVec(SCREEN_AXIS) screenAxis[i] = 1 this.shader.uniforms.screenAxis = screenAxis this.shader.uniforms.lineWidth = lineWidth this.shader.uniforms.color = color this.vao.draw(this.gl.TRIANGLES, this.gridCount[i], this.gridOffset[i]) } proto.drawZero = function(j, i, bounds, offset, color, lineWidth) { var minorAxis = zeroVec(MINOR_AXIS) this.shader.uniforms.majorAxis = minorAxis minorAxis[j] = bounds[1][j] - bounds[0][j] this.shader.uniforms.minorAxis = minorAxis var noffset = copyVec(OFFSET_VEC, offset) noffset[j] += bounds[0][j] this.shader.uniforms.offset = noffset var screenAxis = zeroVec(SCREEN_AXIS) screenAxis[i] = 1 this.shader.uniforms.screenAxis = screenAxis this.shader.uniforms.lineWidth = lineWidth this.shader.uniforms.color = color this.vao.draw(this.gl.TRIANGLES, 6) } proto.dispose = function() { this.vao.dispose() this.vertBuffer.dispose() this.shader.dispose() } function createLines(gl, bounds, ticks) { var vertices = [] var tickOffset = [0,0,0] var tickCount = [0,0,0] //Create grid lines for each axis/direction var gridOffset = [0,0,0] var gridCount = [0,0,0] //Add zero line vertices.push( 0,0,1, 0,1,1, 0,0,-1, 0,0,-1, 0,1,1, 0,1,-1) for(var i=0; i<3; ++i) { //Axis tick marks var start = ((vertices.length / 3)|0) for(var j=0; j * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT license. */ var repeat = __webpack_require__("4633"); module.exports = function padLeft(str, num, ch) { ch = typeof ch !== 'undefined' ? (ch + '') : ' '; return repeat(ch, num) + str; }; /***/ }), /***/ "48f0": /***/ (function(module, exports) { module.exports = invert /** * Inverts a mat2 * * @alias mat2.invert * @param {mat2} out the receiving matrix * @param {mat2} a the source matrix * @returns {mat2} out */ function invert(out, a) { var a0 = a[0] var a1 = a[1] var a2 = a[2] var a3 = a[3] var det = a0 * a3 - a2 * a1 if (!det) return null det = 1.0 / det out[0] = a3 * det out[1] = -a1 * det out[2] = -a2 * det out[3] = a0 * det return out } /***/ }), /***/ "492e": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createSlabDecomposition var bounds = __webpack_require__("2e46") var createRBTree = __webpack_require__("c8ac") var orient = __webpack_require__("92ba") var orderSegments = __webpack_require__("9cfb") function SlabDecomposition(slabs, coordinates, horizontal) { this.slabs = slabs this.coordinates = coordinates this.horizontal = horizontal } var proto = SlabDecomposition.prototype function compareHorizontal(e, y) { return e.y - y } function searchBucket(root, p) { var lastNode = null while(root) { var seg = root.key var l, r if(seg[0][0] < seg[1][0]) { l = seg[0] r = seg[1] } else { l = seg[1] r = seg[0] } var o = orient(l, r, p) if(o < 0) { root = root.left } else if(o > 0) { if(p[0] !== seg[1][0]) { lastNode = root root = root.right } else { var val = searchBucket(root.right, p) if(val) { return val } root = root.left } } else { if(p[0] !== seg[1][0]) { return root } else { var val = searchBucket(root.right, p) if(val) { return val } root = root.left } } } return lastNode } proto.castUp = function(p) { var bucket = bounds.le(this.coordinates, p[0]) if(bucket < 0) { return -1 } var root = this.slabs[bucket] var hitNode = searchBucket(this.slabs[bucket], p) var lastHit = -1 if(hitNode) { lastHit = hitNode.value } //Edge case: need to handle horizontal segments (sucks) if(this.coordinates[bucket] === p[0]) { var lastSegment = null if(hitNode) { lastSegment = hitNode.key } if(bucket > 0) { var otherHitNode = searchBucket(this.slabs[bucket-1], p) if(otherHitNode) { if(lastSegment) { if(orderSegments(otherHitNode.key, lastSegment) > 0) { lastSegment = otherHitNode.key lastHit = otherHitNode.value } } else { lastHit = otherHitNode.value lastSegment = otherHitNode.key } } } var horiz = this.horizontal[bucket] if(horiz.length > 0) { var hbucket = bounds.ge(horiz, p[1], compareHorizontal) if(hbucket < horiz.length) { var e = horiz[hbucket] if(p[1] === e.y) { if(e.closed) { return e.index } else { while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) { hbucket = hbucket+1 e = horiz[hbucket] if(e.closed) { return e.index } } if(e.y === p[1] && !e.start) { hbucket = hbucket+1 if(hbucket >= horiz.length) { return lastHit } e = horiz[hbucket] } } } //Check if e is above/below last segment if(e.start) { if(lastSegment) { var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y]) if(lastSegment[0][0] > lastSegment[1][0]) { o = -o } if(o > 0) { lastHit = e.index } } else { lastHit = e.index } } else if(e.y !== p[1]) { lastHit = e.index } } } } return lastHit } function IntervalSegment(y, index, start, closed) { this.y = y this.index = index this.start = start this.closed = closed } function Event(x, segment, create, index) { this.x = x this.segment = segment this.create = create this.index = index } function createSlabDecomposition(segments) { var numSegments = segments.length var numEvents = 2 * numSegments var events = new Array(numEvents) for(var i=0; i bounds[2]) bounds[2] = points[j + 0] if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1] } } return bounds } /***/ }), /***/ "4aa8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var layoutAttributes = __webpack_require__("3e8e"); module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt); } coerce('treemapcolorway', layoutOut.colorway); coerce('extendtreemapcolors'); }; /***/ }), /***/ "4ae2": /***/ (function(module, exports, __webpack_require__) { module.exports = preprocessPolygon var orient = __webpack_require__("92ba")[3] var makeSlabs = __webpack_require__("492e") var makeIntervalTree = __webpack_require__("4393") var bsearch = __webpack_require__("b707") function visitInterval() { return true } function intervalSearch(table) { return function(x, y) { var tree = table[x] if(tree) { return !!tree.queryPoint(y, visitInterval) } return false } } function buildVerticalIndex(segments) { var table = {} for(var i=0; i 0 && coordinates[bucket] === p[0]) { root = slabs[bucket-1] } else { return 1 } } var lastOrientation = 1 while(root) { var s = root.key var o = orient(p, s[0], s[1]) if(s[0][0] < s[1][0]) { if(o < 0) { root = root.left } else if(o > 0) { lastOrientation = -1 root = root.right } else { return 0 } } else { if(o > 0) { root = root.left } else if(o < 0) { lastOrientation = 1 root = root.right } else { return 0 } } } return lastOrientation } } function classifyEmpty(p) { return 1 } function createClassifyVertical(testVertical) { return function classify(p) { if(testVertical(p[0], p[1])) { return 0 } return 1 } } function createClassifyPointDegen(testVertical, testNormal) { return function classify(p) { if(testVertical(p[0], p[1])) { return 0 } return testNormal(p) } } function preprocessPolygon(loops) { //Compute number of loops var numLoops = loops.length //Unpack segments var segments = [] var vsegments = [] var ptr = 0 for(var i=0; i 1 ? { type: "MultiPolygon", coordinates: polygons } : { type: "Polygon", coordinates: polygons[0] }; } }; var d3_geo_projectGeometryType = { Point: d3_geo_projectPoint, MultiPoint: d3_geo_projectPoint, LineString: d3_geo_projectLine, MultiLineString: d3_geo_projectLine, Polygon: d3_geo_projectPolygon, MultiPolygon: d3_geo_projectPolygon, Sphere: d3_geo_projectPolygon }; function d3_geo_projectNoop() {} function d3_geo_projectClockwise(ring) { if ((n = ring.length) < 4) return false; var i = 0, n, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1]; while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1]; return area <= 0; } function d3_geo_projectContains(ring, point) { var x = point[0], y = point[1], contains = false; for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) { var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1]; if (yi > y ^ yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) contains = !contains; } return contains; } var ε = 1e-6, ε2 = ε * ε, π = Math.PI, halfπ = π / 2, sqrtπ = Math.sqrt(π), radians = π / 180, degrees = 180 / π; function sinci(x) { return x ? x / Math.sin(x) : 1; } function sgn(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } function asin(x) { return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); } function acos(x) { return x > 1 ? 0 : x < -1 ? π : Math.acos(x); } function asqrt(x) { return x > 0 ? Math.sqrt(x) : 0; } var projection = d3.geo.projection, projectionMutator = d3.geo.projectionMutator; d3.geo.interrupt = function(project) { var lobes = [ [ [ [ -π, 0 ], [ 0, halfπ ], [ π, 0 ] ] ], [ [ [ -π, 0 ], [ 0, -halfπ ], [ π, 0 ] ] ] ]; var bounds; function forward(λ, φ) { var sign = φ < 0 ? -1 : +1, hemilobes = lobes[+(φ < 0)]; for (var i = 0, n = hemilobes.length - 1; i < n && λ > hemilobes[i][2][0]; ++i) ; var coordinates = project(λ - hemilobes[i][1][0], φ); coordinates[0] += project(hemilobes[i][1][0], sign * φ > sign * hemilobes[i][0][1] ? hemilobes[i][0][1] : φ)[0]; return coordinates; } function reset() { bounds = lobes.map(function(hemilobes) { return hemilobes.map(function(lobe) { var x0 = project(lobe[0][0], lobe[0][1])[0], x1 = project(lobe[2][0], lobe[2][1])[0], y0 = project(lobe[1][0], lobe[0][1])[1], y1 = project(lobe[1][0], lobe[1][1])[1], t; if (y0 > y1) t = y0, y0 = y1, y1 = t; return [ [ x0, y0 ], [ x1, y1 ] ]; }); }); } if (project.invert) forward.invert = function(x, y) { var hemibounds = bounds[+(y < 0)], hemilobes = lobes[+(y < 0)]; for (var i = 0, n = hemibounds.length; i < n; ++i) { var b = hemibounds[i]; if (b[0][0] <= x && x < b[1][0] && b[0][1] <= y && y < b[1][1]) { var coordinates = project.invert(x - project(hemilobes[i][1][0], 0)[0], y); coordinates[0] += hemilobes[i][1][0]; return pointEqual(forward(coordinates[0], coordinates[1]), [ x, y ]) ? coordinates : null; } } }; var projection = d3.geo.projection(forward), stream_ = projection.stream; projection.stream = function(stream) { var rotate = projection.rotate(), rotateStream = stream_(stream), sphereStream = (projection.rotate([ 0, 0 ]), stream_(stream)); projection.rotate(rotate); rotateStream.sphere = function() { d3.geo.stream(sphere(), sphereStream); }; return rotateStream; }; projection.lobes = function(_) { if (!arguments.length) return lobes.map(function(lobes) { return lobes.map(function(lobe) { return [ [ lobe[0][0] * 180 / π, lobe[0][1] * 180 / π ], [ lobe[1][0] * 180 / π, lobe[1][1] * 180 / π ], [ lobe[2][0] * 180 / π, lobe[2][1] * 180 / π ] ]; }); }); lobes = _.map(function(lobes) { return lobes.map(function(lobe) { return [ [ lobe[0][0] * π / 180, lobe[0][1] * π / 180 ], [ lobe[1][0] * π / 180, lobe[1][1] * π / 180 ], [ lobe[2][0] * π / 180, lobe[2][1] * π / 180 ] ]; }); }); reset(); return projection; }; function sphere() { var ε = 1e-6, coordinates = []; for (var i = 0, n = lobes[0].length; i < n; ++i) { var lobe = lobes[0][i], λ0 = lobe[0][0] * 180 / π, φ0 = lobe[0][1] * 180 / π, φ1 = lobe[1][1] * 180 / π, λ2 = lobe[2][0] * 180 / π, φ2 = lobe[2][1] * 180 / π; coordinates.push(resample([ [ λ0 + ε, φ0 + ε ], [ λ0 + ε, φ1 - ε ], [ λ2 - ε, φ1 - ε ], [ λ2 - ε, φ2 + ε ] ], 30)); } for (var i = lobes[1].length - 1; i >= 0; --i) { var lobe = lobes[1][i], λ0 = lobe[0][0] * 180 / π, φ0 = lobe[0][1] * 180 / π, φ1 = lobe[1][1] * 180 / π, λ2 = lobe[2][0] * 180 / π, φ2 = lobe[2][1] * 180 / π; coordinates.push(resample([ [ λ2 - ε, φ2 - ε ], [ λ2 - ε, φ1 + ε ], [ λ0 + ε, φ1 + ε ], [ λ0 + ε, φ0 - ε ] ], 30)); } return { type: "Polygon", coordinates: [ d3.merge(coordinates) ] }; } function resample(coordinates, m) { var i = -1, n = coordinates.length, p0 = coordinates[0], p1, dx, dy, resampled = []; while (++i < n) { p1 = coordinates[i]; dx = (p1[0] - p0[0]) / m; dy = (p1[1] - p0[1]) / m; for (var j = 0; j < m; ++j) resampled.push([ p0[0] + j * dx, p0[1] + j * dy ]); p0 = p1; } resampled.push(p1); return resampled; } function pointEqual(a, b) { return Math.abs(a[0] - b[0]) < ε && Math.abs(a[1] - b[1]) < ε; } return projection; }; function eckert4(λ, φ) { var k = (2 + halfπ) * Math.sin(φ); φ /= 2; for (var i = 0, δ = Infinity; i < 10 && Math.abs(δ) > ε; i++) { var cosφ = Math.cos(φ); φ -= δ = (φ + Math.sin(φ) * (cosφ + 2) - k) / (2 * cosφ * (1 + cosφ)); } return [ 2 / Math.sqrt(π * (4 + π)) * λ * (1 + Math.cos(φ)), 2 * Math.sqrt(π / (4 + π)) * Math.sin(φ) ]; } eckert4.invert = function(x, y) { var A = .5 * y * Math.sqrt((4 + π) / π), k = asin(A), c = Math.cos(k); return [ x / (2 / Math.sqrt(π * (4 + π)) * (1 + c)), asin((k + A * (c + 2)) / (2 + halfπ)) ]; }; (d3.geo.eckert4 = function() { return projection(eckert4); }).raw = eckert4; var hammerAzimuthalEqualArea = d3.geo.azimuthalEqualArea.raw; function hammer(A, B) { if (arguments.length < 2) B = A; if (B === 1) return hammerAzimuthalEqualArea; if (B === Infinity) return hammerQuarticAuthalic; function forward(λ, φ) { var coordinates = hammerAzimuthalEqualArea(λ / B, φ); coordinates[0] *= A; return coordinates; } forward.invert = function(x, y) { var coordinates = hammerAzimuthalEqualArea.invert(x / A, y); coordinates[0] *= B; return coordinates; }; return forward; } function hammerProjection() { var B = 2, m = projectionMutator(hammer), p = m(B); p.coefficient = function(_) { if (!arguments.length) return B; return m(B = +_); }; return p; } function hammerQuarticAuthalic(λ, φ) { return [ λ * Math.cos(φ) / Math.cos(φ /= 2), 2 * Math.sin(φ) ]; } hammerQuarticAuthalic.invert = function(x, y) { var φ = 2 * asin(y / 2); return [ x * Math.cos(φ / 2) / Math.cos(φ), φ ]; }; (d3.geo.hammer = hammerProjection).raw = hammer; function kavrayskiy7(λ, φ) { return [ 3 * λ / (2 * π) * Math.sqrt(π * π / 3 - φ * φ), φ ]; } kavrayskiy7.invert = function(x, y) { return [ 2 / 3 * π * x / Math.sqrt(π * π / 3 - y * y), y ]; }; (d3.geo.kavrayskiy7 = function() { return projection(kavrayskiy7); }).raw = kavrayskiy7; function miller(λ, φ) { return [ λ, 1.25 * Math.log(Math.tan(π / 4 + .4 * φ)) ]; } miller.invert = function(x, y) { return [ x, 2.5 * Math.atan(Math.exp(.8 * y)) - .625 * π ]; }; (d3.geo.miller = function() { return projection(miller); }).raw = miller; function mollweideBromleyθ(Cp) { return function(θ) { var Cpsinθ = Cp * Math.sin(θ), i = 30, δ; do θ -= δ = (θ + Math.sin(θ) - Cpsinθ) / (1 + Math.cos(θ)); while (Math.abs(δ) > ε && --i > 0); return θ / 2; }; } function mollweideBromley(Cx, Cy, Cp) { var θ = mollweideBromleyθ(Cp); function forward(λ, φ) { return [ Cx * λ * Math.cos(φ = θ(φ)), Cy * Math.sin(φ) ]; } forward.invert = function(x, y) { var θ = asin(y / Cy); return [ x / (Cx * Math.cos(θ)), asin((2 * θ + Math.sin(2 * θ)) / Cp) ]; }; return forward; } var mollweideθ = mollweideBromleyθ(π), mollweide = mollweideBromley(Math.SQRT2 / halfπ, Math.SQRT2, π); (d3.geo.mollweide = function() { return projection(mollweide); }).raw = mollweide; function naturalEarth(λ, φ) { var φ2 = φ * φ, φ4 = φ2 * φ2; return [ λ * (.8707 - .131979 * φ2 + φ4 * (-.013791 + φ4 * (.003971 * φ2 - .001529 * φ4))), φ * (1.007226 + φ2 * (.015085 + φ4 * (-.044475 + .028874 * φ2 - .005916 * φ4))) ]; } naturalEarth.invert = function(x, y) { var φ = y, i = 25, δ; do { var φ2 = φ * φ, φ4 = φ2 * φ2; φ -= δ = (φ * (1.007226 + φ2 * (.015085 + φ4 * (-.044475 + .028874 * φ2 - .005916 * φ4))) - y) / (1.007226 + φ2 * (.015085 * 3 + φ4 * (-.044475 * 7 + .028874 * 9 * φ2 - .005916 * 11 * φ4))); } while (Math.abs(δ) > ε && --i > 0); return [ x / (.8707 + (φ2 = φ * φ) * (-.131979 + φ2 * (-.013791 + φ2 * φ2 * φ2 * (.003971 - .001529 * φ2)))), φ ]; }; (d3.geo.naturalEarth = function() { return projection(naturalEarth); }).raw = naturalEarth; var robinsonConstants = [ [ .9986, -.062 ], [ 1, 0 ], [ .9986, .062 ], [ .9954, .124 ], [ .99, .186 ], [ .9822, .248 ], [ .973, .31 ], [ .96, .372 ], [ .9427, .434 ], [ .9216, .4958 ], [ .8962, .5571 ], [ .8679, .6176 ], [ .835, .6769 ], [ .7986, .7346 ], [ .7597, .7903 ], [ .7186, .8435 ], [ .6732, .8936 ], [ .6213, .9394 ], [ .5722, .9761 ], [ .5322, 1 ] ]; robinsonConstants.forEach(function(d) { d[1] *= 1.0144; }); function robinson(λ, φ) { var i = Math.min(18, Math.abs(φ) * 36 / π), i0 = Math.floor(i), di = i - i0, ax = (k = robinsonConstants[i0])[0], ay = k[1], bx = (k = robinsonConstants[++i0])[0], by = k[1], cx = (k = robinsonConstants[Math.min(19, ++i0)])[0], cy = k[1], k; return [ λ * (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2), (φ > 0 ? halfπ : -halfπ) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) ]; } robinson.invert = function(x, y) { var yy = y / halfπ, φ = yy * 90, i = Math.min(18, Math.abs(φ / 5)), i0 = Math.max(0, Math.floor(i)); do { var ay = robinsonConstants[i0][1], by = robinsonConstants[i0 + 1][1], cy = robinsonConstants[Math.min(19, i0 + 2)][1], u = cy - ay, v = cy - 2 * by + ay, t = 2 * (Math.abs(yy) - by) / u, c = v / u, di = t * (1 - c * t * (1 - 2 * c * t)); if (di >= 0 || i0 === 1) { φ = (y >= 0 ? 5 : -5) * (di + i); var j = 50, δ; do { i = Math.min(18, Math.abs(φ) / 5); i0 = Math.floor(i); di = i - i0; ay = robinsonConstants[i0][1]; by = robinsonConstants[i0 + 1][1]; cy = robinsonConstants[Math.min(19, i0 + 2)][1]; φ -= (δ = (y >= 0 ? halfπ : -halfπ) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) - y) * degrees; } while (Math.abs(δ) > ε2 && --j > 0); break; } } while (--i0 >= 0); var ax = robinsonConstants[i0][0], bx = robinsonConstants[i0 + 1][0], cx = robinsonConstants[Math.min(19, i0 + 2)][0]; return [ x / (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2), φ * radians ]; }; (d3.geo.robinson = function() { return projection(robinson); }).raw = robinson; function sinusoidal(λ, φ) { return [ λ * Math.cos(φ), φ ]; } sinusoidal.invert = function(x, y) { return [ x / Math.cos(y), y ]; }; (d3.geo.sinusoidal = function() { return projection(sinusoidal); }).raw = sinusoidal; function aitoff(λ, φ) { var cosφ = Math.cos(φ), sinciα = sinci(acos(cosφ * Math.cos(λ /= 2))); return [ 2 * cosφ * Math.sin(λ) * sinciα, Math.sin(φ) * sinciα ]; } aitoff.invert = function(x, y) { if (x * x + 4 * y * y > π * π + ε) return; var λ = x, φ = y, i = 25; do { var sinλ = Math.sin(λ), sinλ_2 = Math.sin(λ / 2), cosλ_2 = Math.cos(λ / 2), sinφ = Math.sin(φ), cosφ = Math.cos(φ), sin_2φ = Math.sin(2 * φ), sin2φ = sinφ * sinφ, cos2φ = cosφ * cosφ, sin2λ_2 = sinλ_2 * sinλ_2, C = 1 - cos2φ * cosλ_2 * cosλ_2, E = C ? acos(cosφ * cosλ_2) * Math.sqrt(F = 1 / C) : F = 0, F, fx = 2 * E * cosφ * sinλ_2 - x, fy = E * sinφ - y, δxδλ = F * (cos2φ * sin2λ_2 + E * cosφ * cosλ_2 * sin2φ), δxδφ = F * (.5 * sinλ * sin_2φ - E * 2 * sinφ * sinλ_2), δyδλ = F * .25 * (sin_2φ * sinλ_2 - E * sinφ * cos2φ * sinλ), δyδφ = F * (sin2φ * cosλ_2 + E * sin2λ_2 * cosφ), denominator = δxδφ * δyδλ - δyδφ * δxδλ; if (!denominator) break; var δλ = (fy * δxδφ - fx * δyδφ) / denominator, δφ = (fx * δyδλ - fy * δxδλ) / denominator; λ -= δλ, φ -= δφ; } while ((Math.abs(δλ) > ε || Math.abs(δφ) > ε) && --i > 0); return [ λ, φ ]; }; (d3.geo.aitoff = function() { return projection(aitoff); }).raw = aitoff; function winkel3(λ, φ) { var coordinates = aitoff(λ, φ); return [ (coordinates[0] + λ / halfπ) / 2, (coordinates[1] + φ) / 2 ]; } winkel3.invert = function(x, y) { var λ = x, φ = y, i = 25; do { var cosφ = Math.cos(φ), sinφ = Math.sin(φ), sin_2φ = Math.sin(2 * φ), sin2φ = sinφ * sinφ, cos2φ = cosφ * cosφ, sinλ = Math.sin(λ), cosλ_2 = Math.cos(λ / 2), sinλ_2 = Math.sin(λ / 2), sin2λ_2 = sinλ_2 * sinλ_2, C = 1 - cos2φ * cosλ_2 * cosλ_2, E = C ? acos(cosφ * cosλ_2) * Math.sqrt(F = 1 / C) : F = 0, F, fx = .5 * (2 * E * cosφ * sinλ_2 + λ / halfπ) - x, fy = .5 * (E * sinφ + φ) - y, δxδλ = .5 * F * (cos2φ * sin2λ_2 + E * cosφ * cosλ_2 * sin2φ) + .5 / halfπ, δxδφ = F * (sinλ * sin_2φ / 4 - E * sinφ * sinλ_2), δyδλ = .125 * F * (sin_2φ * sinλ_2 - E * sinφ * cos2φ * sinλ), δyδφ = .5 * F * (sin2φ * cosλ_2 + E * sin2λ_2 * cosφ) + .5, denominator = δxδφ * δyδλ - δyδφ * δxδλ, δλ = (fy * δxδφ - fx * δyδφ) / denominator, δφ = (fx * δyδλ - fy * δxδλ) / denominator; λ -= δλ, φ -= δφ; } while ((Math.abs(δλ) > ε || Math.abs(δφ) > ε) && --i > 0); return [ λ, φ ]; }; (d3.geo.winkel3 = function() { return projection(winkel3); }).raw = winkel3; } module.exports = addProjectionsToD3; /***/ }), /***/ "4bba": /***/ (function(module, exports) { module.exports = inverse; /** * Returns the inverse of the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to invert * @returns {vec3} out */ function inverse(out, a) { out[0] = 1.0 / a[0] out[1] = 1.0 / a[1] out[2] = 1.0 / a[2] return out } /***/ }), /***/ "4c18": /***/ (function(module, exports, __webpack_require__) { "use strict"; var uniq = __webpack_require__("175e") // This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) // TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. function innerFill(order, proc, body) { var dimension = order.length , nargs = proc.arrayArgs.length , has_index = proc.indexArgs.length>0 , code = [] , vars = [] , idx=0, pidx=0, i, j for(i=0; i 0) { code.push("var " + vars.join(",")) } //Scan loop for(i=dimension-1; i>=0; --i) { // Start at largest stride and work your way inwards idx = order[i] code.push(["for(i",i,"=0;i",i," 0) { code.push(["index[",pidx,"]-=s",pidx].join("")) } code.push(["++index[",idx,"]"].join("")) } code.push("}") } return code.join("\n") } // Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. // TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. // I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. function outerFill(matched, order, proc, body) { var dimension = order.length , nargs = proc.arrayArgs.length , blockSize = proc.blockSize , has_index = proc.indexArgs.length > 0 , code = [] for(var i=0; i0;){"].join("")) // Iterate back to front code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). code.push(["s",order[i],"=j",i].join("")) code.push(["j",i,"=0"].join("")) code.push(["}else{s",order[i],"=",blockSize].join("")) code.push(["j",i,"-=",blockSize,"}"].join("")) if(has_index) { code.push(["index[",order[i],"]=j",i].join("")) } } for(var i=0; i 0) { allEqual = allEqual && summary[i] === summary[i-1] } } if(allEqual) { return summary[0] } return summary.join("") } //Generates a cwise operator function generateCWiseOp(proc, typesig) { //Compute dimension // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 var orders = new Array(proc.arrayArgs.length) var dtypes = new Array(proc.arrayArgs.length) for(var i=0; i 0) { vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) } if(proc.indexArgs.length > 0) { // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. var zeros = new Array(dimension) for(var i=0; i 0) { code.push("var " + vars.join(",")) } for(var i=0; i 3) { code.push(processBlock(proc.pre, proc, dtypes)) } //Process body var body = processBlock(proc.body, proc, dtypes) var matched = countMatches(loopOrders) if(matched < dimension) { code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. } else { code.push(innerFill(loopOrders[0], proc, body)) } //Inline epilog if(proc.post.body.length > 3) { code.push(processBlock(proc.post, proc, dtypes)) } if(proc.debug) { console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") } var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) return f() } module.exports = generateCWiseOp /***/ }), /***/ "4c66": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var axisIDs = __webpack_require__("3c1c"); var svgTextUtils = __webpack_require__("0379"); var constants = __webpack_require__("22f9"); var LINE_SPACING = __webpack_require__("63dc").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 }; }; /***/ }), /***/ "4c69": /***/ (function(module, exports) { module.exports = function parseUnit(str, out) { if (!out) out = [ 0, '' ] str = String(str) var num = parseFloat(str, 10) out[0] = num out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || '' return out } /***/ }), /***/ "4cd2": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var listAxes = __webpack_require__("3c1c").list; var getAutoRange = __webpack_require__("ce56").getAutoRange; var constants = __webpack_require__("22f9"); 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); } } }; /***/ }), /***/ "4cd5": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { RELATIVE_CULL_TOLERANCE: 1e-6 }; /***/ }), /***/ "4ce7": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { barmode: { valType: 'enumerated', values: ['stack', 'overlay'], dflt: 'stack', editType: 'calc', }, bargap: { valType: 'number', dflt: 0.1, min: 0, max: 1, editType: 'calc', } }; /***/ }), /***/ "4d64": /***/ (function(module, exports, __webpack_require__) { var toIndexedObject = __webpack_require__("fc6a"); var toLength = __webpack_require__("50c4"); var toAbsoluteIndex = __webpack_require__("23cb"); // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; module.exports = { // `Array.prototype.includes` method // https://tc39.github.io/ecma262/#sec-array.prototype.includes includes: createMethod(true), // `Array.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.indexof indexOf: createMethod(false) }; /***/ }), /***/ "4de4": /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__("23e7"); var $filter = __webpack_require__("b727").filter; var arrayMethodHasSpeciesSupport = __webpack_require__("1dde"); var arrayMethodUsesToLength = __webpack_require__("ae40"); var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); // Edge 14- issue var USES_TO_LENGTH = arrayMethodUsesToLength('filter'); // `Array.prototype.filter` method // https://tc39.github.io/ecma262/#sec-array.prototype.filter // with adding support of @@species $({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, { filter: function filter(callbackfn /* , thisArg */) { return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); /***/ }), /***/ "4e7e": /***/ (function(module, exports, __webpack_require__) { "use strict"; var BN = __webpack_require__("399f") 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) } /***/ }), /***/ "4e89": /***/ (function(module, exports) { module.exports = length /** * Calculates the length of a vec4 * * @param {vec4} a vector to calculate length of * @returns {Number} length of a */ function length (a) { var x = a[0], y = a[1], z = a[2], w = a[3] return Math.sqrt(x * x + y * y + z * z + w * w) } /***/ }), /***/ "4ebd": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var EventEmitter = __webpack_require__("7e25").EventEmitter; var helpers = __webpack_require__("4248"); 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'); var img = new Image(); var svgBlob, url; if(format === 'svg' || Lib.isIE9orBelow() || Lib.isSafari()) { url = helpers.encodeSVG(svg); } else { svgBlob = helpers.createBlob(svg, 'svg'); url = helpers.createObjectURL(svgBlob); } canvas.width = w1; canvas.height = h1; img.onload = function() { var imgData; svgBlob = null; helpers.revokeObjectURL(url); // don't need to draw to canvas if svg // save some time and also avoid failure on IE if(format !== 'svg') { 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; /***/ }), /***/ "4eee": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isArrayOrTypedArray = __webpack_require__("fc26").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; }; /***/ }), /***/ "4efe": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var mouseOffset = __webpack_require__("8b98"); var hasHover = __webpack_require__("2c8d"); var supportsPassive = __webpack_require__("1477"); var removeElement = __webpack_require__("fc26").removeElement; var constants = __webpack_require__("d301"); var dragElement = module.exports = {}; dragElement.align = __webpack_require__("296e"); dragElement.getCursor = __webpack_require__("13a4"); var unhover = __webpack_require__("855b"); 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); } 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 ); } /***/ }), /***/ "4f25": /***/ (function(module, exports, __webpack_require__) { "use strict"; var glslify = __webpack_require__("e98f") module.exports = { fragment: glslify(["precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n"]), vertex: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 color;\nattribute vec2 weight;\n\nuniform vec2 shape;\nuniform mat3 viewTransform;\n\nvarying vec4 fragColor;\n\nvoid main() {\n vec3 vPosition = viewTransform * vec3( position + (weight-.5)/(shape-1.) , 1.0);\n fragColor = color;\n gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"]), pickFragment: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\nvarying vec2 vWeight;\n\nuniform vec2 shape;\nuniform vec4 pickOffset;\n\nvoid main() {\n vec2 d = step(.5, vWeight);\n vec4 id = fragId + pickOffset;\n id.x += d.x + d.y*shape.x;\n\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 gl_FragColor = id/255.;\n}\n"]), pickVertex: glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\nattribute vec2 weight;\n\nuniform vec2 shape;\nuniform mat3 viewTransform;\n\nvarying vec4 fragId;\nvarying vec2 vWeight;\n\nvoid main() {\n vWeight = weight;\n\n fragId = pickId;\n\n vec3 vPosition = viewTransform * vec3( position + (weight-.5)/(shape-1.) , 1.0);\n gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"]) } /***/ }), /***/ "4f4d": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /***/ }), /***/ "4f65": /***/ (function(module, exports) { module.exports = rotateY; /** * Rotate a 3D vector around the y-axis * @param {vec3} out The receiving vec3 * @param {vec3} a The vec3 point to rotate * @param {vec3} b The origin of the rotation * @param {Number} c The angle of rotation * @returns {vec3} out */ function rotateY(out, a, b, c){ var bx = b[0] var bz = b[2] // translate point to the origin var px = a[0] - bx var pz = a[2] - bz var sc = Math.sin(c) var cc = Math.cos(c) // perform rotation and translate to correct position out[0] = bx + pz * sc + px * cc out[1] = a[1] out[2] = bz + pz * cc - px * sc return out } /***/ }), /***/ "4f94": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("1ebf"), layoutAttributes: __webpack_require__("60dc"), supplyDefaults: __webpack_require__("abc9").supplyDefaults, crossTraceDefaults: __webpack_require__("abc9").crossTraceDefaults, supplyLayoutDefaults: __webpack_require__("06ad").supplyLayoutDefaults, calc: __webpack_require__("6a77"), crossTraceCalc: __webpack_require__("f4b3").crossTraceCalc, plot: __webpack_require__("d34f").plot, style: __webpack_require__("b4c7").style, styleOnSelect: __webpack_require__("b4c7").styleOnSelect, hoverPoints: __webpack_require__("fa10").hoverPoints, eventData: __webpack_require__("5885"), selectPoints: __webpack_require__("71b1"), moduleType: 'trace', name: 'box', basePlotModule: __webpack_require__("91cd"), categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'boxLayout', 'zoomScale'], meta: { } }; /***/ }), /***/ "4fc7": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("af50"); /***/ }), /***/ "4ffa": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = extractPlanes function extractPlanes(M, zNear, zFar) { var z = zNear || 0.0 var zf = zFar || 1.0 return [ [ M[12] + M[0], M[13] + M[1], M[14] + M[2], M[15] + M[3] ], [ M[12] - M[0], M[13] - M[1], M[14] - M[2], M[15] - M[3] ], [ M[12] + M[4], M[13] + M[5], M[14] + M[6], M[15] + M[7] ], [ M[12] - M[4], M[13] - M[5], M[14] - M[6], M[15] - M[7] ], [ z*M[12] + M[8], z*M[13] + M[9], z*M[14] + M[10], z*M[15] + M[11] ], [ zf*M[12] - M[8], zf*M[13] - M[9], zf*M[14] - M[10], zf*M[15] - M[11] ] ] } /***/ }), /***/ "5008": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var layoutAttributes = __webpack_require__("d798"); var handleArrayContainerDefaults = __webpack_require__("e5ac"); module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options, config) { if(!config || config.pass === 1) { handlePrefixSuffix(containerIn, containerOut, coerce, axType, options); } if(!config || config.pass === 2) { handleOtherDefaults(containerIn, containerOut, coerce, axType, options); } }; function handlePrefixSuffix(containerIn, containerOut, coerce, axType, options) { var showAttrDflt = getShowAttrDflt(containerIn); var tickPrefix = coerce('tickprefix'); if(tickPrefix) coerce('showtickprefix', showAttrDflt); var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); if(tickSuffix) coerce('showticksuffix', showAttrDflt); } function handleOtherDefaults(containerIn, containerOut, coerce, axType, options) { var showAttrDflt = getShowAttrDflt(containerIn); var tickPrefix = coerce('tickprefix'); if(tickPrefix) coerce('showtickprefix', showAttrDflt); var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); if(tickSuffix) coerce('showticksuffix', showAttrDflt); var showTickLabels = coerce('showticklabels'); if(showTickLabels) { var font = options.font || {}; var contColor = containerOut.color; // as with titlefont.color, inherit axis.color only if one was // explicitly provided var dfltFontColor = (contColor && contColor !== layoutAttributes.color.dflt) ? contColor : font.color; Lib.coerceFont(coerce, 'tickfont', { family: font.family, size: font.size, color: dfltFontColor }); coerce('tickangle'); if(axType !== 'category') { var tickFormat = coerce('tickformat'); var tickformatStops = containerIn.tickformatstops; if(Array.isArray(tickformatStops) && tickformatStops.length) { handleArrayContainerDefaults(containerIn, containerOut, { name: 'tickformatstops', inclusionAttr: 'enabled', handleItemDefaults: tickformatstopDefaults }); } if(!tickFormat && axType !== 'date') { coerce('showexponent', showAttrDflt); coerce('exponentformat'); coerce('separatethousands'); } } } } /* * 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. * */ 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]]; } } 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'); } } /***/ }), /***/ "5047": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Color = __webpack_require__("d115"); var hasColorscale = __webpack_require__("215c").hasColorscale; var colorscaleDefaults = __webpack_require__("4183"); var subTypes = __webpack_require__("de81"); /* * 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'); 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'); } } }; /***/ }), /***/ "5053": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("8be6") /***/ }), /***/ "50c4": /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__("a691"); var min = Math.min; // `ToLength` abstract operation // https://tc39.github.io/ecma262/#sec-tolength module.exports = function (argument) { return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; /***/ }), /***/ "50da": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var constants = __webpack_require__("b326"); 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; }; /***/ }), /***/ "510f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Color = __webpack_require__("d115"); var heatmapHoverPoints = __webpack_require__("d6fb"); module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { var hoverData = heatmapHoverPoints(pointData, xval, yval, hovermode, hoverLayer, true); 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; }; /***/ }), /***/ "5135": /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /***/ "5243": /***/ (function(module, exports) { module.exports = normalize /** * Normalize a vec4 * * @param {vec4} out the receiving vector * @param {vec4} a vector to normalize * @returns {vec4} out */ function normalize (out, a) { var x = a[0], y = a[1], z = a[2], w = a[3] var len = x * x + y * y + z * z + w * w if (len > 0) { len = 1 / Math.sqrt(len) out[0] = x * len out[1] = y * len out[2] = z * len out[3] = w * len } return out } /***/ }), /***/ "52d8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("a08c"), supplyDefaults: __webpack_require__("07dd").supplyDefaults, calc: __webpack_require__("edf7"), colorbar: { min: 'cmin', max: 'cmax' }, plot: __webpack_require__("caf7").createIsosurfaceTrace, moduleType: 'trace', name: 'isosurface', basePlotModule: __webpack_require__("134c"), categories: ['gl3d', 'showLegend'], meta: { } }; /***/ }), /***/ "52e8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Drawing = __webpack_require__("83d1"); var Registry = __webpack_require__("371e"); 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); 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 }; /***/ }), /***/ "5319": /***/ (function(module, exports, __webpack_require__) { "use strict"; var fixRegExpWellKnownSymbolLogic = __webpack_require__("d784"); var anObject = __webpack_require__("825a"); var toObject = __webpack_require__("7b0b"); var toLength = __webpack_require__("50c4"); var toInteger = __webpack_require__("a691"); var requireObjectCoercible = __webpack_require__("1d80"); var advanceStringIndex = __webpack_require__("8aa5"); var regExpExec = __webpack_require__("14c3"); var max = Math.max; var min = Math.min; var floor = Math.floor; var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g; var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g; var maybeToString = function (it) { return it === undefined ? it : String(it); }; // @@replace logic fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) { var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE; var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0; var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0'; return [ // `String.prototype.replace` method // https://tc39.github.io/ecma262/#sec-string.prototype.replace function replace(searchValue, replaceValue) { var O = requireObjectCoercible(this); var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; return replacer !== undefined ? replacer.call(searchValue, O, replaceValue) : nativeReplace.call(String(O), searchValue, replaceValue); }, // `RegExp.prototype[@@replace]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace function (regexp, replaceValue) { if ( (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0) || (typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1) ) { var res = maybeCallNative(nativeReplace, regexp, this, replaceValue); if (res.done) return res.value; } var rx = anObject(regexp); var S = String(this); var functionalReplace = typeof replaceValue === 'function'; if (!functionalReplace) replaceValue = String(replaceValue); var global = rx.global; if (global) { var fullUnicode = rx.unicode; rx.lastIndex = 0; } var results = []; while (true) { var result = regExpExec(rx, S); if (result === null) break; results.push(result); if (!global) break; var matchStr = String(result[0]); if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); } var accumulatedResult = ''; var nextSourcePosition = 0; for (var i = 0; i < results.length; i++) { result = results[i]; var matched = String(result[0]); var position = max(min(toInteger(result.index), S.length), 0); var captures = []; // NOTE: This is equivalent to // captures = result.slice(1).map(maybeToString) // but for some reason `nativeSlice.call(result, 1, result.length)` (called in // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); var namedCaptures = result.groups; if (functionalReplace) { var replacerArgs = [matched].concat(captures, position, S); if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); var replacement = String(replaceValue.apply(undefined, replacerArgs)); } else { replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); } if (position >= nextSourcePosition) { accumulatedResult += S.slice(nextSourcePosition, position) + replacement; nextSourcePosition = position + matched.length; } } return accumulatedResult + S.slice(nextSourcePosition); } ]; // https://tc39.github.io/ecma262/#sec-getsubstitution function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { var tailPos = position + matched.length; var m = captures.length; var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; if (namedCaptures !== undefined) { namedCaptures = toObject(namedCaptures); symbols = SUBSTITUTION_SYMBOLS; } return nativeReplace.call(replacement, symbols, function (match, ch) { var capture; switch (ch.charAt(0)) { case '$': return '$'; case '&': return matched; case '`': return str.slice(0, position); case "'": return str.slice(tailPos); case '<': capture = namedCaptures[ch.slice(1, -1)]; break; default: // \d\d? var n = +ch; if (n === 0) return match; if (n > m) { var f = floor(n / 10); if (f === 0) return match; if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); return match; } capture = captures[n - 1]; } return capture === undefined ? '' : capture; }); } }); /***/ }), /***/ "531f": /***/ (function(module, exports, __webpack_require__) { "use strict"; var glslify = __webpack_require__("e98f") var createShader = __webpack_require__("28dd") 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'} ]) } /***/ }), /***/ "5348": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorScaleAttrs = __webpack_require__("f4e9"); var isosurfaceAttrs = __webpack_require__("a08c"); var baseAttrs = __webpack_require__("a876"); var extendFlat = __webpack_require__("9092").extendFlat; var overrideAll = __webpack_require__("cb34").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, hovertemplate: isosurfaceAttrs.hovertemplate }, colorScaleAttrs('', { colorAttr: '`value`', showScaleDflt: true, editTypeOverride: 'calc' }), { colorbar: isosurfaceAttrs.colorbar, opacity: isosurfaceAttrs.opacity, opacityscale: { valType: 'any', editType: 'calc', }, 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; /***/ }), /***/ "535c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorScaleAttrs = __webpack_require__("f4e9"); var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var baseAttrs = __webpack_require__("a876"); var scatterMapboxAttrs = __webpack_require__("74b4"); var extendFlat = __webpack_require__("9092").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' }) ); /***/ }), /***/ "5374": /***/ (function(module, exports) { module.exports = min /** * Returns the minimum of two vec4's * * @param {vec4} out the receiving vector * @param {vec4} a the first operand * @param {vec4} b the second operand * @returns {vec4} out */ function min (out, a, b) { out[0] = Math.min(a[0], b[0]) out[1] = Math.min(a[1], b[1]) out[2] = Math.min(a[2], b[2]) out[3] = Math.min(a[3], b[3]) return out } /***/ }), /***/ "538c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var geoUtils = __webpack_require__("0919"); var getTopojsonFeatures = __webpack_require__("c400").getTopojsonFeatures; var findExtremes = __webpack_require__("ce56").findExtremes; var style = __webpack_require__("e7ab").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 }; /***/ }), /***/ "53a5": /***/ (function(module, exports) { module.exports = clamp function clamp(value, min, max) { return min < max ? (value < min ? min : value > max ? max : value) : (value < max ? max : value > min ? min : value) } /***/ }), /***/ "53cc": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = stronglyConnectedComponents function stronglyConnectedComponents(adjList) { var numVertices = adjList.length; var index = new Array(numVertices) var lowValue = new Array(numVertices) var active = new Array(numVertices) var child = new Array(numVertices) var scc = new Array(numVertices) var sccLinks = new Array(numVertices) //Initialize tables for(var i=0; i 0) { v = T[T.length-1] var e = adjList[v] if (child[v] < e.length) { // If we're not done iterating over the children, first try finishing that. for(var i=child[v]; i= 0) { // Node v is not yet assigned an scc, but once it is that scc can apparently reach scc[u]. sccLinks[v].push(scc[u]) } } child[v] = i // Remember where we left off. } else { // If we're done iterating over the children, check whether we have an scc. if(lowValue[v] === index[v]) { // TODO: It /might/ be true that T is always a prefix of S (at this point!!!), and if so, this could be used here. var component = [] var links = [], linkCount = 0 for(var i=S.length-1; i>=0; --i) { var w = S[i] active[w] = false component.push(w) links.push(sccLinks[w]) linkCount += sccLinks[w].length scc[w] = components.length if(w === v) { S.length = i break } } components.push(component) var allLinks = new Array(linkCount) for(var i=0; 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; /***/ }), /***/ "54ea": /***/ (function(module, exports, __webpack_require__) { /* * World Calendars * https://github.com/alexcjohnson/world-calendars * * Batch-converted from kbwood/calendars * Many thanks to Keith Wood and all of the contributors to the original project! * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* http://keith-wood.name/calendars.html Calendars extras for jQuery v2.0.2. Written by Keith Wood (wood.keith{at}optusnet.com.au) August 2009. Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ var assign = __webpack_require__("320c"); var main = __webpack_require__("0230"); assign(main.regionalOptions[''], { invalidArguments: 'Invalid arguments', invalidFormat: 'Cannot format a date from another calendar', missingNumberAt: 'Missing number at position {0}', unknownNameAt: 'Unknown name at position {0}', unexpectedLiteralAt: 'Unexpected literal at position {0}', unexpectedText: 'Additional text found at end' }); main.local = main.regionalOptions['']; assign(main.cdate.prototype, { /** Format this date. Found in the jquery.calendars.plus.js module. @memberof CDate @param [format] {string} The date format to use (see formatDate). @param [settings] {object} Options for the formatDate function. @return {string} The formatted date. */ formatDate: function(format, settings) { if (typeof format !== 'string') { settings = format; format = ''; } return this._calendar.formatDate(format || '', this, settings); } }); assign(main.baseCalendar.prototype, { UNIX_EPOCH: main.instance().newDate(1970, 1, 1).toJD(), SECS_PER_DAY: 24 * 60 * 60, TICKS_EPOCH: main.instance().jdEpoch, // 1 January 0001 CE TICKS_PER_DAY: 24 * 60 * 60 * 10000000, /** Date form for ATOM (RFC 3339/ISO 8601). Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ ATOM: 'yyyy-mm-dd', /** Date form for cookies. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ COOKIE: 'D, dd M yyyy', /** Date form for full date. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ FULL: 'DD, MM d, yyyy', /** Date form for ISO 8601. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ ISO_8601: 'yyyy-mm-dd', /** Date form for Julian date. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ JULIAN: 'J', /** Date form for RFC 822. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ RFC_822: 'D, d M yy', /** Date form for RFC 850. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ RFC_850: 'DD, dd-M-yy', /** Date form for RFC 1036. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ RFC_1036: 'D, d M yy', /** Date form for RFC 1123. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ RFC_1123: 'D, d M yyyy', /** Date form for RFC 2822. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ RFC_2822: 'D, d M yyyy', /** Date form for RSS (RFC 822). Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ RSS: 'D, d M yy', /** Date form for Windows ticks. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ TICKS: '!', /** Date form for Unix timestamp. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ TIMESTAMP: '@', /** Date form for W3c (ISO 8601). Found in the jquery.calendars.plus.js module. @memberof BaseCalendar */ W3C: 'yyyy-mm-dd', /** Format a date object into a string value. The format can be combinations of the following:

  • d - day of month (no leading zero)
  • dd - day of month (two digit)
  • o - day of year (no leading zeros)
  • oo - day of year (three digit)
  • D - day name short
  • DD - day name long
  • w - week of year (no leading zero)
  • ww - week of year (two digit)
  • m - month of year (no leading zero)
  • mm - month of year (two digit)
  • M - month name short
  • MM - month name long
  • yy - year (two digit)
  • yyyy - year (four digit)
  • YYYY - formatted year
  • J - Julian date (days since January 1, 4713 BCE Greenwich noon)
  • @ - Unix timestamp (s since 01/01/1970)
  • ! - Windows ticks (100ns since 01/01/0001)
  • '...' - literal text
  • '' - single quote
Found in the jquery.calendars.plus.js module. @memberof BaseCalendar @param [format] {string} The desired format of the date (defaults to calendar format). @param date {CDate} The date value to format. @param [settings] {object} Addition options, whose attributes include: @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday. @property [dayNames] {string[]} Names of the days from Sunday. @property [monthNamesShort] {string[]} Abbreviated names of the months. @property [monthNames] {string[]} Names of the months. @property [calculateWeek] {CalendarsPickerCalculateWeek} Function that determines week of the year. @property [localNumbers=false] {boolean} true to localise numbers (if available), false to use normal Arabic numerals. @return {string} The date in the above format. @throws Errors if the date is from a different calendar. */ formatDate: function(format, date, settings) { if (typeof format !== 'string') { settings = date; date = format; format = ''; } if (!date) { return ''; } if (date.calendar() !== this) { throw main.local.invalidFormat || main.regionalOptions[''].invalidFormat; } format = format || this.local.dateFormat; settings = settings || {}; var dayNamesShort = settings.dayNamesShort || this.local.dayNamesShort; var dayNames = settings.dayNames || this.local.dayNames; var monthNumbers = settings.monthNumbers || this.local.monthNumbers; var monthNamesShort = settings.monthNamesShort || this.local.monthNamesShort; var monthNames = settings.monthNames || this.local.monthNames; var calculateWeek = settings.calculateWeek || this.local.calculateWeek; // Check whether a format character is doubled var doubled = function(match, step) { var matches = 1; while (iFormat + matches < format.length && format.charAt(iFormat + matches) === match) { matches++; } iFormat += matches - 1; return Math.floor(matches / (step || 1)) > 1; }; // Format a number, with leading zeroes if necessary var formatNumber = function(match, value, len, step) { var num = '' + value; if (doubled(match, step)) { while (num.length < len) { num = '0' + num; } } return num; }; // Format a name, short or long as requested var formatName = function(match, value, shortNames, longNames) { return (doubled(match) ? longNames[value] : shortNames[value]); }; // Format month number // (e.g. Chinese calendar needs to account for intercalary months) var calendar = this; var formatMonth = function(date) { return (typeof monthNumbers === 'function') ? monthNumbers.call(calendar, date, doubled('m')) : localiseNumbers(formatNumber('m', date.month(), 2)); }; // Format a month name, short or long as requested var formatMonthName = function(date, useLongName) { if (useLongName) { return (typeof monthNames === 'function') ? monthNames.call(calendar, date) : monthNames[date.month() - calendar.minMonth]; } else { return (typeof monthNamesShort === 'function') ? monthNamesShort.call(calendar, date) : monthNamesShort[date.month() - calendar.minMonth]; } }; // Localise numbers if requested and available var digits = this.local.digits; var localiseNumbers = function(value) { return (settings.localNumbers && digits ? digits(value) : value); }; var output = ''; var literal = false; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !doubled("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case 'd': output += localiseNumbers(formatNumber('d', date.day(), 2)); break; case 'D': output += formatName('D', date.dayOfWeek(), dayNamesShort, dayNames); break; case 'o': output += formatNumber('o', date.dayOfYear(), 3); break; case 'w': output += formatNumber('w', date.weekOfYear(), 2); break; case 'm': output += formatMonth(date); break; case 'M': output += formatMonthName(date, doubled('M')); break; case 'y': output += (doubled('y', 2) ? date.year() : (date.year() % 100 < 10 ? '0' : '') + date.year() % 100); break; case 'Y': doubled('Y', 2); output += date.formatYear(); break; case 'J': output += date.toJD(); break; case '@': output += (date.toJD() - this.UNIX_EPOCH) * this.SECS_PER_DAY; break; case '!': output += (date.toJD() - this.TICKS_EPOCH) * this.TICKS_PER_DAY; break; case "'": if (doubled("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } return output; }, /** Parse a string value into a date object. See formatDate for the possible formats, plus:
  • * - ignore rest of string
Found in the jquery.calendars.plus.js module. @memberof BaseCalendar @param format {string} The expected format of the date ('' for default calendar format). @param value {string} The date in the above format. @param [settings] {object} Additional options whose attributes include: @property [shortYearCutoff] {number} The cutoff year for determining the century. @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday. @property [dayNames] {string[]} Names of the days from Sunday. @property [monthNamesShort] {string[]} Abbreviated names of the months. @property [monthNames] {string[]} Names of the months. @return {CDate} The extracted date value or null if value is blank. @throws Errors if the format and/or value are missing, if the value doesn't match the format, or if the date is invalid. */ parseDate: function(format, value, settings) { if (value == null) { throw main.local.invalidArguments || main.regionalOptions[''].invalidArguments; } value = (typeof value === 'object' ? value.toString() : value + ''); if (value === '') { return null; } format = format || this.local.dateFormat; settings = settings || {}; var shortYearCutoff = settings.shortYearCutoff || this.shortYearCutoff; shortYearCutoff = (typeof shortYearCutoff !== 'string' ? shortYearCutoff : this.today().year() % 100 + parseInt(shortYearCutoff, 10)); var dayNamesShort = settings.dayNamesShort || this.local.dayNamesShort; var dayNames = settings.dayNames || this.local.dayNames; var parseMonth = settings.parseMonth || this.local.parseMonth; var monthNumbers = settings.monthNumbers || this.local.monthNumbers; var monthNamesShort = settings.monthNamesShort || this.local.monthNamesShort; var monthNames = settings.monthNames || this.local.monthNames; var jd = -1; var year = -1; var month = -1; var day = -1; var doy = -1; var shortYear = false; var literal = false; // Check whether a format character is doubled var doubled = function(match, step) { var matches = 1; while (iFormat + matches < format.length && format.charAt(iFormat + matches) === match) { matches++; } iFormat += matches - 1; return Math.floor(matches / (step || 1)) > 1; }; // Extract a number from the string value var getNumber = function(match, step) { var isDoubled = doubled(match, step); var size = [2, 3, isDoubled ? 4 : 2, isDoubled ? 4 : 2, 10, 11, 20]['oyYJ@!'.indexOf(match) + 1]; var digits = new RegExp('^-?\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) { throw (main.local.missingNumberAt || main.regionalOptions[''].missingNumberAt). replace(/\{0\}/, iValue); } iValue += num[0].length; return parseInt(num[0], 10); }; // Extract a month number from the string value var calendar = this; var getMonthNumber = function() { if (typeof monthNumbers === 'function') { doubled('m'); // update iFormat var month = monthNumbers.call(calendar, value.substring(iValue)); iValue += month.length; return month; } return getNumber('m'); }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames, step) { var names = (doubled(match, step) ? longNames : shortNames); for (var i = 0; i < names.length; i++) { if (value.substr(iValue, names[i].length).toLowerCase() === names[i].toLowerCase()) { iValue += names[i].length; return i + calendar.minMonth; } } throw (main.local.unknownNameAt || main.regionalOptions[''].unknownNameAt). replace(/\{0\}/, iValue); }; // Extract a month number from the string value var getMonthName = function() { if (typeof monthNames === 'function') { var month = doubled('M') ? monthNames.call(calendar, value.substring(iValue)) : monthNamesShort.call(calendar, value.substring(iValue)); iValue += month.length; return month; } return getName('M', monthNamesShort, monthNames); }; // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw (main.local.unexpectedLiteralAt || main.regionalOptions[''].unexpectedLiteralAt).replace(/\{0\}/, iValue); } iValue++; }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !doubled("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'w': getNumber('w'); break; case 'm': month = getMonthNumber(); break; case 'M': month = getMonthName(); break; case 'y': var iSave = iFormat; shortYear = !doubled('y', 2); iFormat = iSave; year = getNumber('y', 2); break; case 'Y': year = getNumber('Y', 2); break; case 'J': jd = getNumber('J') + 0.5; if (value.charAt(iValue) === '.') { iValue++; getNumber('J'); } break; case '@': jd = getNumber('@') / this.SECS_PER_DAY + this.UNIX_EPOCH; break; case '!': jd = getNumber('!') / this.TICKS_PER_DAY + this.TICKS_EPOCH; break; case '*': iValue = value.length; break; case "'": if (doubled("'")) { checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length) { throw main.local.unexpectedText || main.regionalOptions[''].unexpectedText; } if (year === -1) { year = this.today().year(); } else if (year < 100 && shortYear) { year += (shortYearCutoff === -1 ? 1900 : this.today().year() - this.today().year() % 100 - (year <= shortYearCutoff ? 0 : 100)); } if (typeof month === 'string') { month = parseMonth.call(this, year, month); } if (doy > -1) { month = 1; day = doy; for (var dim = this.daysInMonth(year, month); day > dim; dim = this.daysInMonth(year, month)) { month++; day -= dim; } } return (jd > -1 ? this.fromJD(jd) : this.newDate(year, month, day)); }, /** A date may be specified as an exact value or a relative one. Found in the jquery.calendars.plus.js module. @memberof BaseCalendar @param dateSpec {CDate|number|string} The date as an object or string in the given format or an offset - numeric days from today, or string amounts and periods, e.g. '+1m +2w'. @param defaultDate {CDate} The date to use if no other supplied, may be null. @param currentDate {CDate} The current date as a possible basis for relative dates, if null today is used (optional) @param [dateFormat] {string} The expected date format - see formatDate. @param [settings] {object} Additional options whose attributes include: @property [shortYearCutoff] {number} The cutoff year for determining the century. @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday. @property [dayNames] {string[]} Names of the days from Sunday. @property [monthNamesShort] {string[]} Abbreviated names of the months. @property [monthNames] {string[]} Names of the months. @return {CDate} The decoded date. */ determineDate: function(dateSpec, defaultDate, currentDate, dateFormat, settings) { if (currentDate && typeof currentDate !== 'object') { settings = dateFormat; dateFormat = currentDate; currentDate = null; } if (typeof dateFormat !== 'string') { settings = dateFormat; dateFormat = ''; } var calendar = this; var offsetString = function(offset) { try { return calendar.parseDate(dateFormat, offset, settings); } catch (e) { // Ignore } offset = offset.toLowerCase(); var date = (offset.match(/^c/) && currentDate ? currentDate.newDate() : null) || calendar.today(); var pattern = /([+-]?[0-9]+)\s*(d|w|m|y)?/g; var matches = pattern.exec(offset); while (matches) { date.add(parseInt(matches[1], 10), matches[2] || 'd'); matches = pattern.exec(offset); } return date; }; defaultDate = (defaultDate ? defaultDate.newDate() : null); dateSpec = (dateSpec == null ? defaultDate : (typeof dateSpec === 'string' ? offsetString(dateSpec) : (typeof dateSpec === 'number' ? (isNaN(dateSpec) || dateSpec === Infinity || dateSpec === -Infinity ? defaultDate : calendar.today().add(dateSpec, 'd')) : calendar.newDate(dateSpec)))); return dateSpec; } }); /***/ }), /***/ "5506": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Polar = module.exports = __webpack_require__("3a99"); Polar.manager = __webpack_require__("2381"); /***/ }), /***/ "551a": /***/ (function(module, exports, __webpack_require__) { "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 = __webpack_require__("28dd") var createBuffer = __webpack_require__("efce") var createVAO = __webpack_require__("b205") var createTexture = __webpack_require__("1d5b") var normals = __webpack_require__("075f") var multiply = __webpack_require__("1417") var invert = __webpack_require__("9343") var ndarray = __webpack_require__("b5bb") var colormap = __webpack_require__("595c") var getContour = __webpack_require__("b7f8") var pool = __webpack_require__("cea5") var shaders = __webpack_require__("38eb") var closestPoint = __webpack_require__("b82b") 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.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; i < opacityscale.length; ++i) { if(opacityscale.length < 2) return 1 if(opacityscale[i][0] === ratio) return opacityscale[i][1] if(opacityscale[i][0] > ratio && 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 unpackIntensity(cells, numVerts, cellIntensity) { var result = new Array(numVerts) for(var i=0; i 0) { 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; i 0; 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', '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', '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; } /***/ }), /***/ "5567": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * 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; }; /***/ }), /***/ "55eb": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { eventDataKeys: [ 'initial', 'delta', 'final' ] }; /***/ }), /***/ "55f6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var isArrayOrTypedArray = __webpack_require__("fc26").isArrayOrTypedArray; var BADNUM = __webpack_require__("e806").BADNUM; var colorscaleCalc = __webpack_require__("3aa8"); var _ = __webpack_require__("fc26")._; 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; }; /***/ }), /***/ "5664": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = earcut; module.exports.default = earcut; function earcut(data, holeIndices, dim) { dim = dim || 2; var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = []; if (!outerNode || outerNode.next === outerNode.prev) return triangles; var minX, minY, maxX, maxY, x, y, invSize; if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox if (data.length > 80 * dim) { minX = maxX = data[0]; minY = maxY = data[1]; for (var i = dim; i < outerLen; i += dim) { x = data[i]; y = data[i + 1]; if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (y > maxY) maxY = y; } // minX, minY and invSize are later used to transform coords into integers for z-order calculation invSize = Math.max(maxX - minX, maxY - minY); invSize = invSize !== 0 ? 1 / invSize : 0; } earcutLinked(outerNode, triangles, dim, minX, minY, invSize); return triangles; } // create a circular doubly linked list from polygon points in the specified winding order function linkedList(data, start, end, dim, clockwise) { var i, last; if (clockwise === (signedArea(data, start, end, dim) > 0)) { for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); } else { for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); } if (last && equals(last, last.next)) { removeNode(last); last = last.next; } return last; } // eliminate colinear or duplicate points function filterPoints(start, end) { if (!start) return start; if (!end) end = start; var p = start, again; do { again = false; if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { removeNode(p); p = end = p.prev; if (p === p.next) break; again = true; } else { p = p.next; } } while (again || p !== end); return end; } // main ear slicing loop which triangulates a polygon (given as a linked list) function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { if (!ear) return; // interlink polygon nodes in z-order if (!pass && invSize) indexCurve(ear, minX, minY, invSize); var stop = ear, prev, next; // iterate through ears, slicing them one by one while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { // cut off the triangle triangles.push(prev.i / dim); triangles.push(ear.i / dim); triangles.push(next.i / dim); removeNode(ear); // skipping the next vertex leads to less sliver triangles ear = next.next; stop = next.next; continue; } ear = next; // if we looped through the whole remaining polygon and can't find any more ears if (ear === stop) { // try filtering points and slicing again if (!pass) { earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally } else if (pass === 1) { ear = cureLocalIntersections(filterPoints(ear), triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, invSize); } break; } } } // check whether a polygon node forms a valid ear with adjacent nodes function isEar(ear) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p = ear.next.next; while (p !== ear.prev) { if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.next; } return true; } function isEarHashed(ear, minX, minY, invSize) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); // z-order range for the current triangle bbox; var minZ = zOrder(minTX, minTY, minX, minY, invSize), maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); var p = ear.prevZ, n = ear.nextZ; // look for points inside the triangle in both directions while (p && p.z >= minZ && n && n.z <= maxZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.prevZ; if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; n = n.nextZ; } // look for remaining points in decreasing z-order while (p && p.z >= minZ) { if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; p = p.prevZ; } // look for remaining points in increasing z-order while (n && n.z <= maxZ) { if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; n = n.nextZ; } return true; } // go through all polygon nodes and cure small local self-intersections function cureLocalIntersections(start, triangles, dim) { var p = start; do { var a = p.prev, b = p.next.next; if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); // remove two nodes involved removeNode(p); removeNode(p.next); p = start = b; } p = p.next; } while (p !== start); return filterPoints(p); } // try splitting polygon into two and triangulate them independently function splitEarcut(start, triangles, dim, minX, minY, invSize) { // look for a valid diagonal that divides the polygon into two var a = start; do { var b = a.next.next; while (b !== a.prev) { if (a.i !== b.i && isValidDiagonal(a, b)) { // split the polygon in two by the diagonal var c = splitPolygon(a, b); // filter colinear points around the cuts a = filterPoints(a, a.next); c = filterPoints(c, c.next); // run earcut on each half earcutLinked(a, triangles, dim, minX, minY, invSize); earcutLinked(c, triangles, dim, minX, minY, invSize); return; } b = b.next; } a = a.next; } while (a !== start); } // link every hole into the outer loop, producing a single-ring polygon without holes function eliminateHoles(data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list; for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim; end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; list = linkedList(data, start, end, dim, false); if (list === list.next) list.steiner = true; queue.push(getLeftmost(list)); } queue.sort(compareX); // process holes from left to right for (i = 0; i < queue.length; i++) { eliminateHole(queue[i], outerNode); outerNode = filterPoints(outerNode, outerNode.next); } return outerNode; } function compareX(a, b) { return a.x - b.x; } // find a bridge between vertices that connects hole with an outer ring and and link it function eliminateHole(hole, outerNode) { outerNode = findHoleBridge(hole, outerNode); if (outerNode) { var b = splitPolygon(outerNode, hole); filterPoints(b, b.next); } } // David Eberly's algorithm for finding a bridge between hole and outer polygon function findHoleBridge(hole, outerNode) { var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); if (x <= hx && x > qx) { qx = x; if (x === hx) { if (hy === p.y) return p; if (hy === p.next.y) return p.next; } m = p.x < p.next.x ? p : p.next; } } p = p.next; } while (p !== outerNode); if (!m) return null; if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint // look for points inside the triangle of hole point, segment intersection and endpoint; // if there are no points found, we have a valid connection; // otherwise choose the point of the minimum angle with the ray as connection point var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; p = m; do { if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { tan = Math.abs(hy - p.y) / (hx - p.x); // tangential if (locallyInside(p, hole) && (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { m = p; tanMin = tan; } } p = p.next; } while (p !== stop); return m; } // whether sector in vertex m contains sector in vertex p in the same coordinates function sectorContainsSector(m, p) { return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; } // interlink polygon nodes in z-order function indexCurve(start, minX, minY, invSize) { var p = start; do { if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); p.prevZ = p.prev; p.nextZ = p.next; p = p.next; } while (p !== start); p.prevZ.nextZ = null; p.prevZ = null; sortLinked(p); } // Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked(list) { var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; do { p = list; list = null; tail = null; numMerges = 0; while (p) { numMerges++; q = p; pSize = 0; for (i = 0; i < inSize; i++) { pSize++; q = q.nextZ; if (!q) break; } qSize = inSize; while (pSize > 0 || (qSize > 0 && q)) { if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { e = p; p = p.nextZ; pSize--; } else { e = q; q = q.nextZ; qSize--; } if (tail) tail.nextZ = e; else list = e; e.prevZ = tail; tail = e; } p = q; } tail.nextZ = null; inSize *= 2; } while (numMerges > 1); return list; } // z-order of a point given coords and inverse of the longer side of data bbox function zOrder(x, y, minX, minY, invSize) { // coords are transformed into non-negative 15-bit integer range x = 32767 * (x - minX) * invSize; y = 32767 * (y - minY) * invSize; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y = (y | (y << 8)) & 0x00FF00FF; y = (y | (y << 4)) & 0x0F0F0F0F; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); } // find the leftmost node of a polygon ring function getLeftmost(start) { var p = start, leftmost = start; do { if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; p = p.next; } while (p !== start); return leftmost; } // check if a point lies within a convex triangle function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; } // check if a diagonal between two polygon nodes is valid (lies in polygon interior) function isValidDiagonal(a, b) { return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case } // signed area of a triangle function area(p, q, r) { return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); } // check if two points are equal function equals(p1, p2) { return p1.x === p2.x && p1.y === p2.y; } // check if two segments intersect function intersects(p1, q1, p2, q2) { var o1 = sign(area(p1, q1, p2)); var o2 = sign(area(p1, q1, q2)); var o3 = sign(area(p2, q2, p1)); var o4 = sign(area(p2, q2, q1)); if (o1 !== o2 && o3 !== o4) return true; // general case if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 return false; } // for collinear points p, q, r, check if point q lies on segment pr function onSegment(p, q, r) { return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); } function sign(num) { return num > 0 ? 1 : num < 0 ? -1 : 0; } // check if a polygon diagonal intersects any polygon segments function intersectsPolygon(a, b) { var p = a; do { if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true; p = p.next; } while (p !== a); return false; } // check if a polygon diagonal is locally inside the polygon function locallyInside(a, b) { return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; } // check if the middle point of a polygon diagonal is inside the polygon function middleInside(a, b) { var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2; do { if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) inside = !inside; p = p.next; } while (p !== a); return inside; } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon(a, b) { var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev; a.next = b; b.prev = a; a2.next = an; an.prev = a2; b2.next = a2; a2.prev = b2; bp.next = b2; b2.prev = bp; return b2; } // create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode(i, x, y, last) { var p = new Node(i, x, y); if (!last) { p.prev = p; p.next = p; } else { p.next = last.next; p.prev = last; last.next.prev = p; last.next = p; } return p; } function removeNode(p) { p.next.prev = p.prev; p.prev.next = p.next; if (p.prevZ) p.prevZ.nextZ = p.nextZ; if (p.nextZ) p.nextZ.prevZ = p.prevZ; } function Node(i, x, y) { // vertex index in coordinates array this.i = i; // vertex coordinates this.x = x; this.y = y; // previous and next vertex nodes in a polygon ring this.prev = null; this.next = null; // z-order curve value this.z = null; // previous and next nodes in z-order this.prevZ = null; this.nextZ = null; // indicates whether this is a steiner point this.steiner = false; } // return a percentage difference between the polygon area and its triangulation area; // used to verify correctness of triangulation earcut.deviation = function (data, holeIndices, dim, triangles) { var hasHoles = holeIndices && holeIndices.length; var outerLen = hasHoles ? holeIndices[0] * dim : data.length; var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); if (hasHoles) { for (var i = 0, len = holeIndices.length; i < len; i++) { var start = holeIndices[i] * dim; var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; polygonArea -= Math.abs(signedArea(data, start, end, dim)); } } var trianglesArea = 0; for (i = 0; i < triangles.length; i += 3) { var a = triangles[i] * dim; var b = triangles[i + 1] * dim; var c = triangles[i + 2] * dim; trianglesArea += Math.abs( (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); } return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea); }; function signedArea(data, start, end, dim) { var sum = 0; for (var i = start, j = end - dim; i < end; i += dim) { sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); j = i; } return sum; } // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts earcut.flatten = function (data) { var dim = data[0][0].length, result = {vertices: [], holes: [], dimensions: dim}, holeIndex = 0; for (var i = 0; i < data.length; i++) { for (var j = 0; j < data[i].length; j++) { for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); } if (i > 0) { holeIndex += data[i - 1].length; result.holes.push(holeIndex); } } return result; }; /***/ }), /***/ "566e": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = boundary function boundary (cells) { var i, j, k var n = cells.length var sz = 0 for (i = 0; i < n; ++i) { sz += cells[i].length } var result = new Array(sz) var ptr = 0 for (i = 0; i < n; ++i) { var c = cells[i] var d = c.length for (j = 0; j < d; ++j) { var b = result[ptr++] = new Array(d - 1) var p = 0 for (k = 0; k < d; ++k) { if (k === j) { continue } b[p++] = c[k] } if (j & 1) { var tmp = b[1] b[1] = b[0] b[0] = tmp } } } return result } /***/ }), /***/ "567e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Axes = __webpack_require__("0642"); var handleArrayContainerDefaults = __webpack_require__("e5ac"); var attributes = __webpack_require__("a5cc"); var helpers = __webpack_require__("fdc7"); module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) { handleArrayContainerDefaults(layoutIn, layoutOut, { name: 'shapes', handleItemDefaults: handleShapeDefaults }); }; function handleShapeDefaults(shapeIn, shapeOut, fullLayout) { function coerce(attr, dflt) { return Lib.coerce(shapeIn, shapeOut, attributes, attr, dflt); } var visible = coerce('visible'); if(!visible) return; coerce('layer'); coerce('opacity'); coerce('fillcolor'); coerce('line.color'); coerce('line.width'); coerce('line.dash'); var dfltType = shapeIn.path ? 'path' : 'rect'; var shapeType = coerce('type', dfltType); 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, '', 'paper'); if(axRef !== 'paper') { ax = Axes.getFromId(gdMock, axRef); ax._shapeIndices.push(shapeOut._index); r2pos = helpers.rangeToShapePosition(ax); pos2r = helpers.shapePositionToRange(ax); } else { pos2r = r2pos = Lib.identity; } // Coerce x0, x1, y0, y1 if(shapeType !== 'path') { var dflt0 = 0.25; var dflt1 = 0.75; // hack until V2.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(shapeType === 'path') { coerce('path'); } else { Lib.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); } } /***/ }), /***/ "5692": /***/ (function(module, exports, __webpack_require__) { var IS_PURE = __webpack_require__("c430"); var store = __webpack_require__("c6cd"); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.6.4', mode: IS_PURE ? 'pure' : 'global', copyright: '© 2020 Denis Pushkarev (zloirock.ru)' }); /***/ }), /***/ "569b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "56b4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var layoutAttributes = __webpack_require__("78d8"); 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'); }; /***/ }), /***/ "56cf": /***/ (function(module, exports) { module.exports = subtract /** * Subtracts vector b from vector a * * @param {vec4} out the receiving vector * @param {vec4} a the first operand * @param {vec4} b the second operand * @returns {vec4} out */ function subtract (out, a, b) { out[0] = a[0] - b[0] out[1] = a[1] - b[1] out[2] = a[2] - b[2] out[3] = a[3] - b[3] return out } /***/ }), /***/ "56ef": /***/ (function(module, exports, __webpack_require__) { var getBuiltIn = __webpack_require__("d066"); var getOwnPropertyNamesModule = __webpack_require__("241c"); var getOwnPropertySymbolsModule = __webpack_require__("7418"); var anObject = __webpack_require__("825a"); // all object keys, includes non-enumerable and symbols module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = getOwnPropertyNamesModule.f(anObject(it)); var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; }; /***/ }), /***/ "56f3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var texttemplateAttrs = __webpack_require__("94d5").texttemplateAttrs; var scatterAttrs = __webpack_require__("107c"); var baseAttrs = __webpack_require__("a876"); var colorAttributes = __webpack_require__("f4e9"); var dash = __webpack_require__("db54").dash; var extendFlat = __webpack_require__("9092").extendFlat; var overrideAll = __webpack_require__("cb34").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, 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: scatterAttrs.fillcolor, selected: scatterAttrs.selected, unselected: scatterAttrs.unselected, hoverinfo: extendFlat({}, baseAttrs.hoverinfo, { flags: ['lon', 'lat', 'location', 'text', 'name'] }), hovertemplate: hovertemplateAttrs(), }, 'calc', 'nested'); /***/ }), /***/ "56fc": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* * 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; }; } }; /***/ }), /***/ "5714": /***/ (function(module, exports) { module.exports = ceil /** * Math.ceil the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to ceil * @returns {vec3} out */ function ceil(out, a) { out[0] = Math.ceil(a[0]) out[1] = Math.ceil(a[1]) out[2] = Math.ceil(a[2]) return out } /***/ }), /***/ "5752": /***/ (function(module, exports, __webpack_require__) { "use strict"; var BN = __webpack_require__("399f") module.exports = str2BN function str2BN(x) { return new BN(x) } /***/ }), /***/ "578f": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createSelectBuffer var createFBO = __webpack_require__("44c3") var pool = __webpack_require__("cea5") var ndarray = __webpack_require__("b5bb") var nextPow2 = __webpack_require__("a48a").nextPow2 var selectRange = __webpack_require__("dd8f")({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(_inline_7_arg0_<255||_inline_7_arg1_<255||_inline_7_arg2_<255||_inline_7_arg3_<255){var _inline_7_l=_inline_7_arg4_-_inline_7_arg6_[0],_inline_7_a=_inline_7_arg5_-_inline_7_arg6_[1],_inline_7_f=_inline_7_l*_inline_7_l+_inline_7_a*_inline_7_a;_inline_7_f this.buffer.length) { pool.free(this.buffer) var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) for(var i=0; i -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; }; 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' ); }; // 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 FILLET = 0; // TODO: may expose this constant var r = ( dx > 2 * FILLET && dy > 2 * FILLET ) ? FILLET : 0; 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 hasFlag = function(f) { return trace.textposition.indexOf(f) !== -1; }; var hasBottom = hasFlag('bottom'); var hasTop = hasFlag('top') || (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; var pad = trace.marker.pad; if(opts.isHeader) { x0 += pad.l - TEXTPAD; x1 -= 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 - pad.b; if(y0 < limY && limY < y1) y0 = limY; } else { limY = y0 + 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 d3.interpolate(prev, next); }; var makeUpdateSliceInterpolator = function(pt, onPathbar, refRect, size) { 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 = pt; } } else { prev = {}; } } } return d3.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 d3.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 }); } } /***/ }), /***/ "5844": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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' }; /***/ }), /***/ "5885": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "5913": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var numConstants = __webpack_require__("e806"); 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__("0642").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; } /***/ }), /***/ "5928": /***/ (function(module, exports) { module.exports = fromQuat; /** * Creates a matrix from a quaternion rotation. * * @param {mat4} out mat4 receiving operation result * @param {quat4} q Rotation quaternion * @returns {mat4} out */ function fromQuat(out, q) { var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, yx = y * x2, yy = y * y2, zx = z * x2, zy = z * y2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2; out[0] = 1 - yy - zz; out[1] = yx + wz; out[2] = zx - wy; out[3] = 0; out[4] = yx - wz; out[5] = 1 - xx - zz; out[6] = zy + wx; out[7] = 0; out[8] = zx + wy; out[9] = zy - wx; out[10] = 1 - xx - yy; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return out; }; /***/ }), /***/ "595c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Ben Postlethwaite * January 2013 * License MIT */ var colorScale = __webpack_require__("9a02"); var lerp = __webpack_require__("9b49") module.exports = createColormap; function createColormap (spec) { /* * Default Options */ var indicies, fromrgba, torgba, nsteps, cmap, colormap, format, nshades, colors, alpha, i; if ( !spec ) spec = {}; nshades = (spec.nshades || 72) - 1; format = spec.format || 'hex'; colormap = spec.colormap; if (!colormap) colormap = 'jet'; if (typeof colormap === 'string') { colormap = colormap.toLowerCase(); if (!colorScale[colormap]) { throw Error(colormap + ' not a supported colorscale'); } cmap = colorScale[colormap]; } else if (Array.isArray(colormap)) { cmap = colormap.slice(); } else { throw Error('unsupported colormap option', colormap); } if (cmap.length > nshades + 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 < indicies.length-1; ++i) { nsteps = indicies[i+1] - indicies[i]; fromrgba = steps[i]; torgba = steps[i+1]; for (var j = 0; j < nsteps; j++) { var amt = j / nsteps colors.push([ Math.round(lerp(fromrgba[0], torgba[0], amt)), Math.round(lerp(fromrgba[1], torgba[1], amt)), Math.round(lerp(fromrgba[2], torgba[2], amt)), lerp(fromrgba[3], torgba[3], amt) ]) } } //add 1 step as last value colors.push(cmap[cmap.length - 1].rgb.concat(alpha[1])) if (format === 'hex') colors = colors.map( rgb2hex ); else if (format === 'rgbaString') colors = colors.map( rgbaStr ); else if (format === 'float') colors = colors.map( rgb2float ); return colors; }; function rgb2float (rgba) { return [ rgba[0] / 255, rgba[1] / 255, rgba[2] / 255, rgba[3] ] } function rgb2hex (rgba) { var dig, hex = '#'; for (var i = 0; i < 3; ++i) { dig = rgba[i]; dig = dig.toString(16); hex += ('00' + dig).substr( dig.length ); } return hex; } function rgbaStr (rgba) { return 'rgba(' + rgba.join(',') + ')'; } /***/ }), /***/ "59be": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isArrayOrTypedArray = __webpack_require__("fc26").isArrayOrTypedArray; var hasColorscale = __webpack_require__("215c").hasColorscale; var colorscaleDefaults = __webpack_require__("4183"); module.exports = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; 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'); }; /***/ }), /***/ "59ce": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var tinycolor = __webpack_require__("66cb"); var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var Color = __webpack_require__("d115"); var Drawing = __webpack_require__("83d1"); var Plots = __webpack_require__("bb71"); var Axes = __webpack_require__("0642"); var setConvertCartesian = __webpack_require__("1a40"); var setConvertPolar = __webpack_require__("7a52"); var doAutoRange = __webpack_require__("ce56").doAutoRange; var dragBox = __webpack_require__("9676"); var dragElement = __webpack_require__("4efe"); var Fx = __webpack_require__("a5c4"); var Titles = __webpack_require__("1999"); var prepSelect = __webpack_require__("1876").prepSelect; var selectOnClick = __webpack_require__("1876").selectOnClick; var clearSelect = __webpack_require__("1876").clearSelect; var setCursor = __webpack_require__("0f37"); var clearGlCanvases = __webpack_require__("821b"); var redrawReglTraces = __webpack_require__("a392").redrawReglTraces; var MID_SHIFT = __webpack_require__("63dc").MID_SHIFT; var constants = __webpack_require__("f510"); var helpers = __webpack_require__("a60f"); var _ = Lib._; var mod = Lib.mod; var deg2rad = Lib.deg2rad; var rad2deg = Lib.rad2deg; function Polar(gd, id) { 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._polarlayer.append('g') .attr('class', id); // 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) { return new Polar(gd, id); }; proto.plot = function(polarCalcData, fullLayout) { var _this = this; var polarLayout = fullLayout[_this.id]; _this._hasClipOnAxisFalse = false; for(var i = 0; i < polarCalcData.length; i++) { var trace = polarCalcData[i][0].trace; if(trace.cliponaxis === false) { _this._hasClipOnAxisFalse = true; break; } } _this.updateLayers(fullLayout, polarLayout); _this.updateLayout(fullLayout, polarLayout); Plots.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout); _this.updateFx(fullLayout, polarLayout); }; proto.updateLayers = function(fullLayout, polarLayout) { var _this = this; var layers = _this.layers; var radialLayout = polarLayout.radialaxis; var angularLayout = polarLayout.angularaxis; 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 join = _this.framework.selectAll('.polarsublayer') .data(layerData, String); join.enter().append('g') .attr('class', function(d) { return 'polarsublayer ' + d;}) .each(function(d) { var sel = layers[d] = d3.select(this); switch(d) { case 'frontplot': // TODO add option to place in 'backplot' layer?? 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: * * - polarLayout.radialaxis (aka radialLayout in this file): * - polarLayout.angularaxis (aka angularLayout in this file): * used for data -> calcdata conversions (aka d2c) during the calc step * * - this.radialAxis * extends polarLayout.radialaxis, 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 polarLayout.angularaxis, 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 = polarLayout.radialaxis; var angularLayout = polarLayout.angularaxis; // 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 = polarLayout.sector; _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 = polarLayout.hole * 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; _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: { counterclockwise: 'top', clockwise: 'bottom' }[radialLayout.side], // 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 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 - polarLayout.hole); ax.range = [sectorBBox[ind[0]] * drl, sectorBBox[ind[1]] * drl]; }; ax.isPtWithinRange = axId === 'x' ? function(d) { return _this.isPtInside(d); } : function() { return true; }; ax.setRange(); ax.setScale(); return ax; }; proto.doAutoRange = function(fullLayout, polarLayout) { var gd = this.gd; var radialAxis = this.radialAxis; var radialLayout = polarLayout.radialaxis; radialAxis.setScale(); 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') ]; }; 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 = polarLayout.radialaxis; var a0 = mod(polarLayout.sector[0], 360); var ax = _this.radialAxis; var hasRoomForIt = innerRadius < radius; _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 = function(d) { return 'translate(' + (ax.l2p(d.x) + innerRadius) + ',0)'; }; // set special grid path function var gridPathFn = 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 vals = Axes.calcTicks(ax); var valsClipped = Axes.clipEnds(ax, vals); var tickSign = Axes.getTickSigns(ax)[2]; 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, 0) }); } // 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: tLayer} ); updateElement( layers['radial-line'].select('line'), hasRoomForIt && radialLayout.showline, { x1: 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) { var _this = this; var gd = _this.gd; var radius = _this.radius; var cx = _this.cx; var cy = _this.cy; var radialLayout = polarLayout.radialaxis; var titleClass = _this.id + 'title'; var angle = _angle !== undefined ? _angle : _this.radialAxisAngle; var angleRad = deg2rad(angle); var cosa = Math.cos(angleRad); var sina = Math.sin(angleRad); 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; pad = radialLayout.side === 'counterclockwise' ? -h - ts * 0.4 : h + ts * 0.8; } _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: cx + (radius / 2) * cosa + pad * sina, y: cy - (radius / 2) * sina + pad * cosa, '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 = polarLayout.angularaxis; var ax = _this.angularAxis; _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 = 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 = function(d) { return _transFn(t2g(d)); }; var transFn2 = function(d) { var rad = t2g(d); return _transFn(rad) + strRotate(-rad2deg(rad)); }; var gridPathFn = 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 = Axes.calcTicks(ax); // 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) { this.updateAngularDrag(fullLayout); this.updateRadialDrag(fullLayout, polarLayout, 0); this.updateRadialDrag(fullLayout, polarLayout, 1); this.updateMainDrag(fullLayout); } }; proto.updateMainDrag = function(fullLayout) { var _this = this; 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 mainDrag = dragBox.makeDragger(layers, 'path', 'maindrag', 'crosshair'); d3.select(mainDrag) .attr('d', _this.pathSubplot()) .attr('transform', strTranslate(cx, cy)); 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); clearSelect(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) { 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(); x0 = startX - bbox.left; y0 = startY - bbox.top; // 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': if(vangles) { dragOpts.moveFn = zoomMoveForPolygons; } else { dragOpts.moveFn = zoomMove; } dragOpts.clickFn = zoomClick; dragOpts.doneFn = zoomDone; zoomPrep(evt, startX, startY); break; case 'select': case 'lasso': prepSelect(evt, startX, startY, dragOpts, dragModeNow); break; } }; 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); }; 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 - polarLayout.hole) / 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}; 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; clearSelect(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', 'move'); var dragOpts = {element: angularDrag, gd: gd}; 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; var y1 = y0 + dy; 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; a0 = xy2a(x0, y0); dragOpts.moveFn = moveFn; dragOpts.doneFn = doneFn; clearSelect(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) { 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; } function strTranslate(x, y) { return 'translate(' + x + ',' + y + ')'; } function strRotate(angle) { return 'rotate(' + angle + ')'; } /***/ }), /***/ "59e0": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); exports.formatPiePercent = function formatPiePercent(v, separators) { var vRounded = (v * 100).toPrecision(3); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } return Lib.numSeparate(vRounded, separators) + '%'; }; exports.formatPieValue = function formatPieValue(v, separators) { var vRounded = v.toPrecision(10); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } return Lib.numSeparate(vRounded, separators); }; exports.getFirstFilled = function getFirstFilled(array, indices) { if(!Array.isArray(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(Array.isArray(item)) return exports.getFirstFilled(item, indices); else if(item) return item; }; /***/ }), /***/ "5a1b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * 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; }; /***/ }), /***/ "5a1e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Color = __webpack_require__("d115"); var ARROWPATHS = __webpack_require__("a935"); /** * 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: 'translate(' + p.x + ',' + p.y + ')' + (rot ? 'rotate(' + (rot * 180 / Math.PI) + ')' : '') + 'scale(' + arrowScale + ')' }) .style({ fill: Color.rgb(options.arrowcolor), 'stroke-width': 0 }); } if(doStart) drawhead(startHeadStyle, start, startRot, startScale); if(doEnd) drawhead(headStyle, end, endRot, scale); }; /***/ }), /***/ "5aa9": /***/ (function(module, exports, __webpack_require__) { "use strict"; var bn2num = __webpack_require__("0948") var ctz = __webpack_require__("7223") 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) } } /***/ }), /***/ "5aae": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var scatterAttrs = __webpack_require__("107c"); var baseAttrs = __webpack_require__("a876"); var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var texttemplateAttrs = __webpack_require__("94d5").texttemplateAttrs; var colorScaleAttrs = __webpack_require__("f4e9"); var extendFlat = __webpack_require__("9092").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, 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: scatterAttrs.fillcolor, marker: extendFlat({ symbol: scatterMarkerAttrs.symbol, opacity: scatterMarkerAttrs.opacity, 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', 'text', 'name'] }), hoveron: scatterAttrs.hoveron, hovertemplate: hovertemplateAttrs() }; /***/ }), /***/ "5ad1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // 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 }; /***/ }), /***/ "5ad3": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__("f6a2") //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjpudWxsLCJzb3VyY2VzIjpbIkY6L3NvdXJjZS92dWUtcGxvdGx5LmpzL25vZGVfbW9kdWxlcy9wb2ludC1jbHVzdGVyL2luZGV4LmpzIl0sInNvdXJjZXNDb250ZW50IjpbIid1c2Ugc3RyaWN0J1xuXG5tb2R1bGUuZXhwb3J0cyA9IHJlcXVpcmUoJy4vcXVhZCcpXG4iXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsWUFBWTtBQUNaO0FBQ0EsTUFBTSxDQUFDLE9BQU8sR0FBRyxPQUFPLENBQUMsUUFBUSxDQUFDOyJ9 /***/ }), /***/ "5b68": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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', } } }; /***/ }), /***/ "5bec": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "5c33": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var annAttrs = __webpack_require__("bb4a"); var extendFlat = __webpack_require__("9092").extendFlat; var overrideAll = __webpack_require__("cb34").overrideAll; var fontAttrs = __webpack_require__("9845"); var domainAttrs = __webpack_require__("81f0").attributes; var FORMAT_LINK = __webpack_require__("78df").FORMAT_LINK; 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: [], }, 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: [], }, 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; /***/ }), /***/ "5c6c": /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /***/ "5c79": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var tinycolor = __webpack_require__("66cb"); var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var _ = Lib._; var Color = __webpack_require__("d115"); var Drawing = __webpack_require__("83d1"); var setConvert = __webpack_require__("1a40"); var extendFlat = __webpack_require__("9092").extendFlat; var Plots = __webpack_require__("bb71"); var Axes = __webpack_require__("0642"); var dragElement = __webpack_require__("4efe"); var Fx = __webpack_require__("a5c4"); var Titles = __webpack_require__("1999"); var prepSelect = __webpack_require__("1876").prepSelect; var selectOnClick = __webpack_require__("1876").selectOnClick; var clearSelect = __webpack_require__("1876").clearSelect; var constants = __webpack_require__("d301"); 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 = 'translate(' + 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 = 'translate(' + (x0 - baxis._offset) + ',' + (y0 + h) + ')'; _this.layers.baxis.attr('transform', bTransform); _this.layers.bgrid.attr('transform', bTransform); var aTransform = 'translate(' + (x0 + w / 2) + ',' + y0 + ')rotate(30)translate(0,' + -aaxis._offset + ')'; _this.layers.aaxis.attr('transform', aTransform); _this.layers.agrid.attr('transform', aTransform); var cTransform = 'translate(' + (x0 + w / 2) + ',' + y0 + ')rotate(-30)translate(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.makeTransFn(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.initInteractions = function() { var _this = this; var dragger = _this.layers.plotbg.select('path').node(); var gd = _this.graphDiv; var zoomLayer = gd._fullLayout._zoomlayer; // use plotbg for the main interactions var dragOptions = { element: dragger, gd: gd, plotinfo: { id: _this.id, xaxis: _this.xaxis, yaxis: _this.yaxis }, subplot: _this.id, prepFn: function(e, startX, startY) { // these aren't available yet when initInteractions // is called dragOptions.xaxes = [_this.xaxis]; dragOptions.yaxes = [_this.yaxis]; var dragModeNow = gd._fullLayout.dragmode; if(dragModeNow === 'lasso') dragOptions.minDrag = 1; else dragOptions.minDrag = undefined; if(dragModeNow === 'zoom') { dragOptions.moveFn = zoomMove; dragOptions.clickFn = clickZoomPan; dragOptions.doneFn = zoomDone; zoomPrep(e, startX, startY); } else if(dragModeNow === 'pan') { dragOptions.moveFn = plotDrag; dragOptions.clickFn = clickZoomPan; dragOptions.doneFn = dragDone; panPrep(); clearSelect(gd); } else if(dragModeNow === 'select' || dragModeNow === 'lasso') { prepSelect(e, startX, startY, 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, 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; 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', 'translate(' + _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', 'translate(' + _this.x0 + ', ' + _this.y0 + ')') .style({ fill: Color.background, stroke: Color.defaultLine, 'stroke-width': 1, opacity: 0 }) .attr('d', 'M0,0Z'); clearSelect(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; var y1 = y0 + dy0; 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(); 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 = 'translate(' + (_this.x0 + dx) + ',' + (_this.y0 + dy) + ')'; _this.plotContainer.selectAll('.scatterlayer,.maplayer') .attr('transform', plotTransform); var plotTransform2 = 'translate(' + -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(dragOptions); }; function removeZoombox(gd) { d3.select(gd) .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') .remove(); } /***/ }), /***/ "5c9a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("43ef"), supplyDefaults: __webpack_require__("1a06"), calc: __webpack_require__("6bd5"), plot: __webpack_require__("6954").plot, style: __webpack_require__("ee6b"), colorbar: __webpack_require__("a5e1"), hoverPoints: __webpack_require__("510f"), moduleType: 'trace', name: 'contour', basePlotModule: __webpack_require__("91cd"), categories: ['cartesian', 'svg', '2dMap', 'contour', 'showLegend'], meta: { } }; /***/ }), /***/ "5cc5": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("5c9a"); /***/ }), /***/ "5ccc": /***/ (function(module, exports, __webpack_require__) { var glslify = __webpack_require__("e98f") var createShader = __webpack_require__("28dd") 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'}]) } /***/ }), /***/ "5cf9": /***/ (function(module, exports, __webpack_require__) { "use strict"; function mouseButtons(ev) { if(typeof ev === 'object') { if('buttons' in ev) { return ev.buttons } else if('which' in ev) { var b = ev.which if(b === 2) { return 4 } else if(b === 3) { return 2 } else if(b > 0) { return 1<<(b-1) } } else if('button' in ev) { var b = ev.button if(b === 1) { return 4 } else if(b === 2) { return 2 } else if(b >= 0) { return 1<= 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; i 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; }; /***/ }), /***/ "5e2e": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createBoxes var createBuffer = __webpack_require__("efce") var createShader = __webpack_require__("28dd") var shaders = __webpack_require__("b44d") function Boxes(plot, vbo, shader) { this.plot = plot this.vbo = vbo this.shader = shader } var proto = Boxes.prototype proto.bind = function() { var shader = this.shader this.vbo.bind() this.shader.bind() shader.attributes.coord.pointer() shader.uniforms.screenBox = this.plot.screenBox } proto.drawBox = (function() { var lo = [0,0] var hi = [0,0] return function(loX, loY, hiX, hiY, color) { var plot = this.plot var shader = this.shader var gl = plot.gl lo[0] = loX lo[1] = loY hi[0] = hiX hi[1] = hiY shader.uniforms.lo = lo shader.uniforms.hi = hi shader.uniforms.color = color gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) } }()) proto.dispose = function() { this.vbo.dispose() this.shader.dispose() } function createBoxes(plot) { var gl = plot.gl var vbo = createBuffer(gl, [ 0,0, 0,1, 1,0, 1,1]) var shader = createShader(gl, shaders.boxVert, shaders.lineFrag) return new Boxes(plot, vbo, shader) } /***/ }), /***/ "5e46": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var scatterPolarFormatLabels = __webpack_require__("98e74"); 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); }; /***/ }), /***/ "5e8f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var subtypes = __webpack_require__("de81"); module.exports = { hasLines: subtypes.hasLines, hasMarkers: subtypes.hasMarkers, hasText: subtypes.hasText, isBubble: subtypes.isBubble, attributes: __webpack_require__("107c"), supplyDefaults: __webpack_require__("0eb7"), crossTraceDefaults: __webpack_require__("0324"), calc: __webpack_require__("70b4").calc, crossTraceCalc: __webpack_require__("4324"), arraysToCalcdata: __webpack_require__("106b"), plot: __webpack_require__("f118"), colorbar: __webpack_require__("f3cf"), formatLabels: __webpack_require__("7e96"), style: __webpack_require__("52e8").style, styleOnSelect: __webpack_require__("52e8").styleOnSelect, hoverPoints: __webpack_require__("391b"), selectPoints: __webpack_require__("214c"), animatable: true, moduleType: 'trace', name: 'scatter', basePlotModule: __webpack_require__("91cd"), categories: [ 'cartesian', 'svg', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like', 'zoomScale' ], meta: { } }; /***/ }), /***/ "5ecd": /***/ (function(module, exports) { module.exports = [ // Keep this list sorted 'abs' , 'acos' , 'all' , 'any' , 'asin' , 'atan' , 'ceil' , 'clamp' , 'cos' , 'cross' , 'dFdx' , 'dFdy' , 'degrees' , 'distance' , 'dot' , 'equal' , 'exp' , 'exp2' , 'faceforward' , 'floor' , 'fract' , 'gl_BackColor' , 'gl_BackLightModelProduct' , 'gl_BackLightProduct' , 'gl_BackMaterial' , 'gl_BackSecondaryColor' , 'gl_ClipPlane' , 'gl_ClipVertex' , 'gl_Color' , 'gl_DepthRange' , 'gl_DepthRangeParameters' , 'gl_EyePlaneQ' , 'gl_EyePlaneR' , 'gl_EyePlaneS' , 'gl_EyePlaneT' , 'gl_Fog' , 'gl_FogCoord' , 'gl_FogFragCoord' , 'gl_FogParameters' , 'gl_FragColor' , 'gl_FragCoord' , 'gl_FragData' , 'gl_FragDepth' , 'gl_FragDepthEXT' , 'gl_FrontColor' , 'gl_FrontFacing' , 'gl_FrontLightModelProduct' , 'gl_FrontLightProduct' , 'gl_FrontMaterial' , 'gl_FrontSecondaryColor' , 'gl_LightModel' , 'gl_LightModelParameters' , 'gl_LightModelProducts' , 'gl_LightProducts' , 'gl_LightSource' , 'gl_LightSourceParameters' , 'gl_MaterialParameters' , 'gl_MaxClipPlanes' , 'gl_MaxCombinedTextureImageUnits' , 'gl_MaxDrawBuffers' , 'gl_MaxFragmentUniformComponents' , 'gl_MaxLights' , 'gl_MaxTextureCoords' , 'gl_MaxTextureImageUnits' , 'gl_MaxTextureUnits' , 'gl_MaxVaryingFloats' , 'gl_MaxVertexAttribs' , 'gl_MaxVertexTextureImageUnits' , 'gl_MaxVertexUniformComponents' , 'gl_ModelViewMatrix' , 'gl_ModelViewMatrixInverse' , 'gl_ModelViewMatrixInverseTranspose' , 'gl_ModelViewMatrixTranspose' , 'gl_ModelViewProjectionMatrix' , 'gl_ModelViewProjectionMatrixInverse' , 'gl_ModelViewProjectionMatrixInverseTranspose' , 'gl_ModelViewProjectionMatrixTranspose' , 'gl_MultiTexCoord0' , 'gl_MultiTexCoord1' , 'gl_MultiTexCoord2' , 'gl_MultiTexCoord3' , 'gl_MultiTexCoord4' , 'gl_MultiTexCoord5' , 'gl_MultiTexCoord6' , 'gl_MultiTexCoord7' , 'gl_Normal' , 'gl_NormalMatrix' , 'gl_NormalScale' , 'gl_ObjectPlaneQ' , 'gl_ObjectPlaneR' , 'gl_ObjectPlaneS' , 'gl_ObjectPlaneT' , 'gl_Point' , 'gl_PointCoord' , 'gl_PointParameters' , 'gl_PointSize' , 'gl_Position' , 'gl_ProjectionMatrix' , 'gl_ProjectionMatrixInverse' , 'gl_ProjectionMatrixInverseTranspose' , 'gl_ProjectionMatrixTranspose' , 'gl_SecondaryColor' , 'gl_TexCoord' , 'gl_TextureEnvColor' , 'gl_TextureMatrix' , 'gl_TextureMatrixInverse' , 'gl_TextureMatrixInverseTranspose' , 'gl_TextureMatrixTranspose' , 'gl_Vertex' , 'greaterThan' , 'greaterThanEqual' , 'inversesqrt' , 'length' , 'lessThan' , 'lessThanEqual' , 'log' , 'log2' , 'matrixCompMult' , 'max' , 'min' , 'mix' , 'mod' , 'normalize' , 'not' , 'notEqual' , 'pow' , 'radians' , 'reflect' , 'refract' , 'sign' , 'sin' , 'smoothstep' , 'sqrt' , 'step' , 'tan' , 'texture2D' , 'texture2DLod' , 'texture2DProj' , 'texture2DProjLod' , 'textureCube' , 'textureCubeLod' , 'texture2DLodEXT' , 'texture2DProjLodEXT' , 'textureCubeLodEXT' , 'texture2DGradEXT' , 'texture2DProjGradEXT' , 'textureCubeGradEXT' ] /***/ }), /***/ "5edd": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isValue = __webpack_require__("936a"); // prettier-ignore var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ }; module.exports = function (value) { if (!isValue(value)) return false; return hasOwnProperty.call(possibleTypes, typeof value); }; /***/ }), /***/ "5f0d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var tarjan = __webpack_require__("53cc"); var Lib = __webpack_require__("fc26"); var wrap = __webpack_require__("0a3e").wrap; var isArrayOrTypedArray = Lib.isArrayOrTypedArray; var isIndex = Lib.isIndex; var Colorscale = __webpack_require__("c258"); function convertToD3Sankey(trace) { var nodeSpec = trace.node; var linkSpec = trace.link; var links = []; var hasLinkColorArray = isArrayOrTypedArray(linkSpec.color); 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, 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 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 }); } // 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, }); }; /***/ }), /***/ "5f5f": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createSpikes2D function GLSpikes2D(plot) { this.plot = plot this.enable = [true, true, false, false] this.width = [1, 1, 1, 1] this.color = [[0,0,0,1], [0,0,0,1], [0,0,0,1], [0,0,0,1]] this.center = [Infinity, Infinity] } var proto = GLSpikes2D.prototype proto.update = function(options) { options = options || {} this.enable = (options.enable || [true,true,false,false]).slice() this.width = (options.width || [1,1,1,1]).slice() this.color = (options.color || [ [0,0,0,1], [0,0,0,1], [0,0,0,1], [0,0,0,1]]).map(function(x) { return x.slice() }) this.center = (options.center || [Infinity,Infinity]).slice() this.plot.setOverlayDirty() } proto.draw = function() { var spikeEnable = this.enable var spikeWidth = this.width var spikeColor = this.color var spikeCenter = this.center var plot = this.plot var line = plot.line var dataBox = plot.dataBox var viewPixels = plot.viewBox line.bind() if(dataBox[0] <= spikeCenter[0] && spikeCenter[0] <= dataBox[2] && dataBox[1] <= spikeCenter[1] && spikeCenter[1] <= dataBox[3]) { var centerX = viewPixels[0] + (spikeCenter[0] - dataBox[0]) / (dataBox[2] - dataBox[0]) * (viewPixels[2] - viewPixels[0]) var centerY = viewPixels[1] + (spikeCenter[1] - dataBox[1]) / (dataBox[3] - dataBox[1]) * (viewPixels[3] - viewPixels[1]) if(spikeEnable[0]) { line.drawLine( centerX, centerY, viewPixels[0], centerY, spikeWidth[0], spikeColor[0]) } if(spikeEnable[1]) { line.drawLine( centerX, centerY, centerX, viewPixels[1], spikeWidth[1], spikeColor[1]) } if(spikeEnable[2]) { line.drawLine( centerX, centerY, viewPixels[2], centerY, spikeWidth[2], spikeColor[2]) } if(spikeEnable[3]) { line.drawLine( centerX, centerY, centerX, viewPixels[3], spikeWidth[3], spikeColor[3]) } } } proto.dispose = function() { this.plot.removeOverlay(this) } function createSpikes2D(plot, options) { var spikes = new GLSpikes2D(plot) spikes.update(options) plot.addOverlay(spikes) return spikes } /***/ }), /***/ "6024": /***/ (function(module, exports, __webpack_require__) { "use strict"; var setPrototypeOf = __webpack_require__("e0f6") , contains = __webpack_require__("f973") , d = __webpack_require__("f508") , Symbol = __webpack_require__("1c4a") , Iterator = __webpack_require__("06a2"); var defineProperty = Object.defineProperty, ArrayIterator; ArrayIterator = module.exports = function (arr, kind) { if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'"); Iterator.call(this, arr); if (!kind) kind = "value"; else if (contains.call(kind, "key+value")) kind = "key+value"; else if (contains.call(kind, "key")) kind = "key"; else kind = "value"; defineProperty(this, "__kind__", d("", kind)); }; if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); // Internal %ArrayIteratorPrototype% doesn't expose its constructor delete ArrayIterator.prototype.constructor; ArrayIterator.prototype = Object.create(Iterator.prototype, { _resolve: d(function (i) { if (this.__kind__ === "value") return this.__list__[i]; if (this.__kind__ === "key+value") return [i, this.__list__[i]]; return i; }) }); defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator")); /***/ }), /***/ "605a": /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.create = defaultTicks exports.equal = ticksEqual function prettyPrint(spacing, i) { var stepStr = spacing + "" var u = stepStr.indexOf(".") var sigFigs = 0 if(u >= 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 < sigFigs) { xs = "0" + xs } return xis + "." + xs } else { return xis } } function defaultTicks(bounds, tickSpacing) { var array = [] for(var d=0; d<3; ++d) { var ticks = [] var m = 0.5*(bounds[0][d]+bounds[1][d]) for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) { ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) } for(var t=-1; t*tickSpacing[d]>=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; j index) { var S = IndexedObject(arguments[index++]); var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S); var length = keys.length; var j = 0; var key; while (length > j) { key = keys[j++]; if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key]; } } return T; } : nativeAssign; /***/ }), /***/ "60dc": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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', } }; /***/ }), /***/ "615a": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createTextElements var createBuffer = __webpack_require__("efce") var createShader = __webpack_require__("28dd") var getText = __webpack_require__("9662") var bsearch = __webpack_require__("cc77") var shaders = __webpack_require__("b44d") function TextElements(plot, vbo, shader) { this.plot = plot this.vbo = vbo this.shader = shader this.tickOffset = [[],[]] this.tickX = [[],[]] this.labelOffset = [0,0] this.labelCount = [0,0] } var proto = TextElements.prototype proto.drawTicks = (function() { var DATA_AXIS = [0,0] var SCREEN_OFFSET = [0,0] var ZERO_2 = [0,0] return function(axis) { var plot = this.plot var shader = this.shader var tickX = this.tickX[axis] var tickOffset = this.tickOffset[axis] var gl = plot.gl var viewBox = plot.viewBox var dataBox = plot.dataBox var screenBox = plot.screenBox var pixelRatio = plot.pixelRatio var tickEnable = plot.tickEnable var tickPad = plot.tickPad var textColor = plot.tickColor var textAngle = plot.tickAngle // todo check if this should be used (now unused) // var tickLength = plot.tickMarkLength var labelEnable = plot.labelEnable var labelPad = plot.labelPad var labelColor = plot.labelColor var labelAngle = plot.labelAngle var labelOffset = this.labelOffset[axis] var labelCount = this.labelCount[axis] var start = bsearch.lt(tickX, dataBox[axis]) var end = bsearch.le(tickX, dataBox[axis+2]) DATA_AXIS[0] = DATA_AXIS[1] = 0 DATA_AXIS[axis] = 1 SCREEN_OFFSET[axis] = (viewBox[2+axis] + viewBox[axis]) / (screenBox[2+axis] - screenBox[axis]) - 1.0 var screenScale = 2.0 / screenBox[2+(axis^1)] - screenBox[axis^1] SCREEN_OFFSET[axis^1] = screenScale * viewBox[axis^1] - 1.0 if(tickEnable[axis]) { SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * tickPad[axis] if(start < end && tickOffset[end] > tickOffset[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(start < end && tickOffset[end] > tickOffset[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 1e-6) { out[0] = ax/al out[1] = ay/al out[2] = az/al out[3] = aw/al } else { out[0] = out[1] = out[2] = 0.0 out[3] = 1.0 } } function OrbitCameraController(initQuat, initCenter, initRadius) { this.radius = filterVector([initRadius]) this.center = filterVector(initCenter) this.rotation = filterVector(initQuat) this.computedRadius = this.radius.curve(0) this.computedCenter = this.center.curve(0) this.computedRotation = this.rotation.curve(0) this.computedUp = [0.1,0,0] this.computedEye = [0.1,0,0] this.computedMatrix = [0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] this.recalcMatrix(0) } var proto = OrbitCameraController.prototype proto.lastT = function() { return Math.max( this.radius.lastT(), this.center.lastT(), this.rotation.lastT()) } proto.recalcMatrix = function(t) { this.radius.curve(t) this.center.curve(t) this.rotation.curve(t) var quat = this.computedRotation normalize4(quat, quat) var mat = this.computedMatrix mat4FromQuat(mat, quat) var center = this.computedCenter var eye = this.computedEye var up = this.computedUp var radius = Math.exp(this.computedRadius[0]) eye[0] = center[0] + radius * mat[2] eye[1] = center[1] + radius * mat[6] eye[2] = center[2] + radius * mat[10] up[0] = mat[1] up[1] = mat[5] up[2] = mat[9] for(var i=0; i<3; ++i) { var rr = 0.0 for(var j=0; j<3; ++j) { rr += mat[i+4*j] * eye[j] } mat[12+i] = -rr } } proto.getMatrix = function(t, result) { this.recalcMatrix(t) var m = this.computedMatrix if(result) { for(var i=0; i<16; ++i) { result[i] = m[i] } return result } return m } proto.idle = function(t) { this.center.idle(t) this.radius.idle(t) this.rotation.idle(t) } proto.flush = function(t) { this.center.flush(t) this.radius.flush(t) this.rotation.flush(t) } proto.pan = function(t, dx, dy, dz) { dx = dx || 0.0 dy = dy || 0.0 dz = dz || 0.0 this.recalcMatrix(t) var mat = this.computedMatrix var ux = mat[1] var uy = mat[5] var uz = mat[9] var ul = len3(ux, uy, uz) ux /= ul uy /= ul uz /= ul var rx = mat[0] var ry = mat[4] var rz = mat[8] var ru = rx * ux + ry * uy + rz * uz rx -= ux * ru ry -= uy * ru rz -= uz * ru var rl = len3(rx, ry, rz) rx /= rl ry /= rl rz /= rl var fx = mat[2] var fy = mat[6] var fz = mat[10] var fu = fx * ux + fy * uy + fz * uz var fr = fx * rx + fy * ry + fz * rz fx -= fu * ux + fr * rx fy -= fu * uy + fr * ry fz -= fu * uz + fr * rz var fl = len3(fx, fy, fz) fx /= fl fy /= fl fz /= fl var vx = rx * dx + ux * dy var vy = ry * dx + uy * dy var vz = rz * dx + uz * dy this.center.move(t, vx, vy, vz) //Update z-component of radius var radius = Math.exp(this.computedRadius[0]) radius = Math.max(1e-4, radius + dz) this.radius.set(t, Math.log(radius)) } proto.rotate = function(t, dx, dy, dz) { this.recalcMatrix(t) dx = dx||0.0 dy = dy||0.0 var mat = this.computedMatrix var rx = mat[0] var ry = mat[4] var rz = mat[8] var ux = mat[1] var uy = mat[5] var uz = mat[9] var fx = mat[2] var fy = mat[6] var fz = mat[10] var qx = dx * rx + dy * ux var qy = dx * ry + dy * uy var qz = dx * rz + dy * uz var bx = -(fy * qz - fz * qy) var by = -(fz * qx - fx * qz) var bz = -(fx * qy - fy * qx) var bw = Math.sqrt(Math.max(0.0, 1.0 - Math.pow(bx,2) - Math.pow(by,2) - Math.pow(bz,2))) var bl = len4(bx, by, bz, bw) if(bl > 1e-6) { bx /= bl by /= bl bz /= bl bw /= bl } else { bx = by = bz = 0.0 bw = 1.0 } var rotation = this.computedRotation var ax = rotation[0] var ay = rotation[1] var az = rotation[2] var aw = rotation[3] var cx = ax*bw + aw*bx + ay*bz - az*by var cy = ay*bw + aw*by + az*bx - ax*bz var cz = az*bw + aw*bz + ax*by - ay*bx var cw = aw*bw - ax*bx - ay*by - az*bz //Apply roll if(dz) { bx = fx by = fy bz = fz var s = Math.sin(dz) / len3(bx, by, bz) bx *= s by *= s bz *= s bw = Math.cos(dx) cx = cx*bw + cw*bx + cy*bz - cz*by cy = cy*bw + cw*by + cz*bx - cx*bz cz = cz*bw + cw*bz + cx*by - cy*bx cw = cw*bw - cx*bx - cy*by - cz*bz } var cl = len4(cx, cy, cz, cw) if(cl > 1e-6) { cx /= cl cy /= cl cz /= cl cw /= cl } else { cx = cy = cz = 0.0 cw = 1.0 } this.rotation.set(t, cx, cy, cz, cw) } proto.lookAt = function(t, eye, center, up) { this.recalcMatrix(t) center = center || this.computedCenter eye = eye || this.computedEye up = up || this.computedUp var mat = this.computedMatrix lookAt(mat, eye, center, up) var rotation = this.computedRotation quatFromFrame(rotation, mat[0], mat[1], mat[2], mat[4], mat[5], mat[6], mat[8], mat[9], mat[10]) normalize4(rotation, rotation) this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3]) var fl = 0.0 for(var i=0; i<3; ++i) { fl += Math.pow(center[i] - eye[i], 2) } this.radius.set(t, 0.5 * Math.log(Math.max(fl, 1e-6))) this.center.set(t, center[0], center[1], center[2]) } proto.translate = function(t, dx, dy, dz) { this.center.move(t, dx||0.0, dy||0.0, dz||0.0) } proto.setMatrix = function(t, matrix) { var rotation = this.computedRotation quatFromFrame(rotation, matrix[0], matrix[1], matrix[2], matrix[4], matrix[5], matrix[6], matrix[8], matrix[9], matrix[10]) normalize4(rotation, rotation) this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3]) var mat = this.computedMatrix invert44(mat, matrix) var w = mat[15] if(Math.abs(w) > 1e-6) { var cx = mat[12]/w var cy = mat[13]/w var cz = mat[14]/w this.recalcMatrix(t) var r = Math.exp(this.computedRadius[0]) this.center.set(t, cx-mat[2]*r, cy-mat[6]*r, cz-mat[10]*r) this.radius.idle(t) } else { this.center.idle(t) this.radius.idle(t) } } proto.setDistance = function(t, d) { if(d > 0) { this.radius.set(t, Math.log(d)) } } proto.setDistanceLimits = function(lo, hi) { if(lo > 0) { lo = Math.log(lo) } else { lo = -Infinity } if(hi > 0) { hi = Math.log(hi) } else { hi = Infinity } hi = Math.max(hi, lo) this.radius.bounds[0][0] = lo this.radius.bounds[1][0] = hi } proto.getDistanceLimits = function(out) { var bounds = this.radius.bounds if(out) { out[0] = Math.exp(bounds[0][0]) out[1] = Math.exp(bounds[1][0]) return out } return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ] } proto.toJSON = function() { this.recalcMatrix(this.lastT()) return { center: this.computedCenter.slice(), rotation: this.computedRotation.slice(), distance: Math.log(this.computedRadius[0]), zoomMin: this.radius.bounds[0][0], zoomMax: this.radius.bounds[1][0] } } proto.fromJSON = function(options) { var t = this.lastT() var c = options.center if(c) { this.center.set(t, c[0], c[1], c[2]) } var r = options.rotation if(r) { this.rotation.set(t, r[0], r[1], r[2], r[3]) } var d = options.distance if(d && d > 0) { this.radius.set(t, Math.log(d)) } this.setDistanceLimits(options.zoomMin, options.zoomMax) } function createOrbitController(options) { options = options || {} var center = options.center || [0,0,0] var rotation = options.rotation || [0,0,0,1] var radius = options.radius || 1.0 center = [].slice.call(center, 0, 3) rotation = [].slice.call(rotation, 0, 4) normalize4(rotation, rotation) var result = new OrbitCameraController( rotation, center, Math.log(radius)) result.setDistanceLimits(options.zoomMin, options.zoomMax) if('eye' in options || 'up' in options) { result.lookAt(0, options.eye, options.center, options.up) } return result } /***/ }), /***/ "6259": /***/ (function(module, exports) { module.exports = transformMat4 /** * Transforms the vec4 with a mat4. * * @param {vec4} out the receiving vector * @param {vec4} a the vector to transform * @param {mat4} m matrix to transform with * @returns {vec4} out */ function transformMat4 (out, a, m) { var x = a[0], y = a[1], z = a[2], w = a[3] out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w return out } /***/ }), /***/ "6295": /***/ (function(module, exports, __webpack_require__) { var createShader = __webpack_require__("28dd") var glslify = __webpack_require__("e98f") var vertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform vec3 objectOffset;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n vec3 localCoordinate = vec3(uv.zw, f.x);\n worldCoordinate = objectOffset + localCoordinate;\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n vColor = texture2D(colormap, vec2(value, value));\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n"]) var fragSrc = glslify(["precision 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 beckmannSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\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 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform float vertexColor;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n if ((kill > 0.0) ||\n (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = max(beckmannSpecular(L, V, N, roughness), 0.);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n //decide how to interpolate color — in vertex or in fragment\n vec4 surfaceColor =\n step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) +\n step(.5, vertexColor) * vColor;\n\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n"]) var contourVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform vec3 objectOffset;\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n worldCoordinate = objectOffset + dataCoordinate;\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z += zOffset;\n\n gl_Position = clipPosition;\n value = f + objectOffset.z;\n kill = -1.0;\n planeCoordinate = uv.zw;\n\n vColor = texture2D(colormap, vec2(value, value));\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n"]) var pickSrc = 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 vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if ((kill > 0.0) ||\n (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n"]) exports.createShader = function (gl) { var shader = createShader(gl, vertSrc, fragSrc, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'vec3'}, {name: 'normal', type: 'vec3'} ]) shader.attributes.uv.location = 0 shader.attributes.f.location = 1 shader.attributes.normal.location = 2 return shader } exports.createPickShader = function (gl) { var shader = createShader(gl, vertSrc, pickSrc, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'vec3'}, {name: 'normal', type: 'vec3'} ]) shader.attributes.uv.location = 0 shader.attributes.f.location = 1 shader.attributes.normal.location = 2 return shader } exports.createContourShader = function (gl) { var shader = createShader(gl, contourVertSrc, fragSrc, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'float'} ]) shader.attributes.uv.location = 0 shader.attributes.f.location = 1 return shader } exports.createPickContourShader = function (gl) { var shader = createShader(gl, contourVertSrc, pickSrc, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'float'} ]) shader.attributes.uv.location = 0 shader.attributes.f.location = 1 return shader } /***/ }), /***/ "62c4": /***/ (function(module, exports, __webpack_require__) { "use strict"; var _undefined = __webpack_require__("e76c")(); // Support ES3 engines module.exports = function (val) { return val !== _undefined && val !== null; }; /***/ }), /***/ "62d6": /***/ (function(module, exports, __webpack_require__) { "use strict"; var compile = __webpack_require__("40ce") var EmptyProc = { body: "", args: [], thisVars: [], localVars: [] } function fixup(x) { if(!x) { return EmptyProc } for(var i=0; i>", rrshift: ">>>" } ;(function(){ for(var id in assign_ops) { var op = assign_ops[id] exports[id] = makeOp({ args: ["array","array","array"], body: {args:["a","b","c"], body: "a=b"+op+"c"}, funcName: id }) exports[id+"eq"] = makeOp({ args: ["array","array"], body: {args:["a","b"], body:"a"+op+"=b"}, rvalue: true, funcName: id+"eq" }) exports[id+"s"] = makeOp({ args: ["array", "array", "scalar"], body: {args:["a","b","s"], body:"a=b"+op+"s"}, funcName: id+"s" }) exports[id+"seq"] = makeOp({ args: ["array","scalar"], body: {args:["a","s"], body:"a"+op+"=s"}, rvalue: true, funcName: id+"seq" }) } })(); var unary_ops = { not: "!", bnot: "~", neg: "-", recip: "1.0/" } ;(function(){ for(var id in unary_ops) { var op = unary_ops[id] exports[id] = makeOp({ args: ["array", "array"], body: {args:["a","b"], body:"a="+op+"b"}, funcName: id }) exports[id+"eq"] = makeOp({ args: ["array"], body: {args:["a"], body:"a="+op+"a"}, rvalue: true, count: 2, funcName: id+"eq" }) } })(); var binary_ops = { and: "&&", or: "||", eq: "===", neq: "!==", lt: "<", gt: ">", leq: "<=", geq: ">=" } ;(function() { for(var id in binary_ops) { var op = binary_ops[id] exports[id] = makeOp({ args: ["array","array","array"], body: {args:["a", "b", "c"], body:"a=b"+op+"c"}, funcName: id }) exports[id+"s"] = makeOp({ args: ["array","array","scalar"], body: {args:["a", "b", "s"], body:"a=b"+op+"s"}, funcName: id+"s" }) exports[id+"eq"] = makeOp({ args: ["array", "array"], body: {args:["a", "b"], body:"a=a"+op+"b"}, rvalue:true, count:2, funcName: id+"eq" }) exports[id+"seq"] = makeOp({ args: ["array", "scalar"], body: {args:["a","s"], body:"a=a"+op+"s"}, rvalue:true, count:2, funcName: id+"seq" }) } })(); var math_unary = [ "abs", "acos", "asin", "atan", "ceil", "cos", "exp", "floor", "log", "round", "sin", "sqrt", "tan" ] ;(function() { for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, funcName: "norminf" }) exports.norm1 = compile({ args:["array"], pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]}, post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, funcName: "norm1" }) exports.sup = compile({ args: [ "array" ], pre: { body: "this_h=-Infinity", args: [], thisVars: [ "this_h" ], localVars: [] }, body: { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_", args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], thisVars: [ "this_h" ], localVars: [] }, post: { body: "return this_h", args: [], thisVars: [ "this_h" ], localVars: [] } }) exports.inf = compile({ args: [ "array" ], pre: { body: "this_h=Infinity", args: [], thisVars: [ "this_h" ], localVars: [] }, body: { body: "if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", args:[ {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], thisVars:["this_i","this_v"], localVars:["_inline_1_k"]}, post:{ body:"{return this_i}", args:[], thisVars:["this_i"], localVars:[]} }) exports.random = makeOp({ args: ["array"], pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, funcName: "random" }) exports.assign = makeOp({ args:["array", "array"], body: {args:["a", "b"], body:"a=b"}, funcName: "assign" }) exports.assigns = makeOp({ args:["array", "scalar"], body: {args:["a", "b"], body:"a=b"}, funcName: "assigns" }) exports.equals = compile({ args:["array", "array"], pre: EmptyProc, body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}, {name:"y", lvalue:false, rvalue:true, count:1}], body: "if(x!==y){return false}", localVars: [], thisVars: []}, post: {args:[], localVars:[], thisVars:[], body:"return true"}, funcName: "equals" }) /***/ }), /***/ "62e4": /***/ (function(module, exports) { module.exports = function(module) { if (!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if (!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /***/ "6321": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isPrototype = __webpack_require__("9013"); module.exports = function (value) { if (typeof value !== "function") return false; if (!hasOwnProperty.call(value, "length")) return false; try { if (typeof value.length !== "number") return false; if (typeof value.call !== "function") return false; if (typeof value.apply !== "function") return false; } catch (error) { return false; } return !isPrototype(value); }; /***/ }), /***/ "6386": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { moduleType: 'trace', name: 'scatterpolar', basePlotModule: __webpack_require__("c07c"), categories: ['polar', 'symbols', 'showLegend', 'scatter-like'], attributes: __webpack_require__("8a6e"), supplyDefaults: __webpack_require__("66db").supplyDefaults, colorbar: __webpack_require__("f3cf"), formatLabels: __webpack_require__("98e74"), calc: __webpack_require__("8a43"), plot: __webpack_require__("8260"), style: __webpack_require__("52e8").style, styleOnSelect: __webpack_require__("52e8").styleOnSelect, hoverPoints: __webpack_require__("efcd").hoverPoints, selectPoints: __webpack_require__("214c"), meta: { } }; /***/ }), /***/ "63dc": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // 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' } }; /***/ }), /***/ "643c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var plots = __webpack_require__("bb71"); 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); }; /***/ }), /***/ "644a": /***/ (function(module, exports) { module.exports = squaredLength /** * Calculates the squared length of a vec4 * * @param {vec4} a vector to calculate squared length of * @returns {Number} squared length of a */ function squaredLength (a) { var x = a[0], y = a[1], z = a[2], w = a[3] return x * x + y * y + z * z + w * w } /***/ }), /***/ "64c3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var extendFlat = __webpack_require__("fc26").extendFlat; var OHLCattrs = __webpack_require__("6657"); var boxAttrs = __webpack_require__("1ebf"); 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 = { 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, }; /***/ }), /***/ "6533": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); module.exports = function handleLabelDefaults(coerce, layout, lineColor, opts) { if(!opts) opts = {}; var showLabels = coerce('contours.showlabels'); if(showLabels) { var globalFont = layout.font; Lib.coerceFont(coerce, 'contours.labelfont', { family: globalFont.family, size: globalFont.size, color: lineColor }); coerce('contours.labelformat'); } if(opts.hasHover !== false) coerce('zhoverformat'); }; /***/ }), /***/ "6547": /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__("a691"); var requireObjectCoercible = __webpack_require__("1d80"); // `String.prototype.{ codePointAt, at }` methods implementation var createMethod = function (CONVERT_TO_STRING) { return function ($this, pos) { var S = String(requireObjectCoercible($this)); var position = toInteger(pos); var size = S.length; var first, second; if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; first = S.charCodeAt(position); return first < 0xD800 || first > 0xDBFF || position + 1 === size || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF ? CONVERT_TO_STRING ? S.charAt(position) : first : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; }; }; module.exports = { // `String.prototype.codePointAt` method // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat codeAt: createMethod(false), // `String.prototype.at` method // https://github.com/mathiasbynens/String.prototype.at charAt: createMethod(true) }; /***/ }), /***/ "654e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var colorscaleDefaults = __webpack_require__("4183"); var attributes = __webpack_require__("535c"); 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'}); }; /***/ }), /***/ "6578": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("16ef"); /***/ }), /***/ "6599": /***/ (function(module, exports, __webpack_require__) { "use strict"; var generated = Object.create(null), random = Math.random; module.exports = function () { var str; do { str = random().toString(36).slice(2); } while (generated[str]); return str; }; /***/ }), /***/ "65f0": /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__("861d"); var isArray = __webpack_require__("e8b5"); var wellKnownSymbol = __webpack_require__("b622"); var SPECIES = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation // https://tc39.github.io/ecma262/#sec-arrayspeciescreate module.exports = function (originalArray, length) { var C; if (isArray(originalArray)) { C = originalArray.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; else if (isObject(C)) { C = C[SPECIES]; if (C === null) C = undefined; } } return new (C === undefined ? Array : C)(length === 0 ? 0 : length); }; /***/ }), /***/ "661c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var isNumeric = __webpack_require__("19b2"); var Loggers = __webpack_require__("ae13"); var mod = __webpack_require__("d3dc").mod; var constants = __webpack_require__("e806"); 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__("371e"); var utcFormat = d3.time.format.utc; 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 * * bool sunday is for week ticks, shift it to a Sunday. */ exports.dateTick0 = function(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, or [+\-]HH:?MM and we THROW IT AWAY * this format comes from https://tools.ietf.org/html/rfc3339#section-5.6 * 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 http://support.microsoft.com/kb/244664: * 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 * http://www.filemaker.com/12help/html/add_view_data.4.21.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 = d3.time.format('%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 one item to * d3's vocabulary: * %{n}f where n is the max number of digits of fractional seconds */ var fracMatch = /%\d?f/g; 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)); 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 }; }; /***/ }), /***/ "6626": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("0b4f"); /***/ }), /***/ "6649": /***/ (function(module, exports, __webpack_require__) { var hiddenStore = __webpack_require__("b332"); module.exports = createStore; function createStore() { var key = {}; return function (obj) { if ((typeof obj !== 'object' || obj === null) && typeof obj !== 'function' ) { throw new Error('Weakmap-shim: Key must be object') } var store = obj.valueOf(key); return store && store.identity === key ? store : hiddenStore(obj, key); }; } /***/ }), /***/ "664d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("9509"); /***/ }), /***/ "6657": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var extendFlat = __webpack_require__("fc26").extendFlat; var scatterAttrs = __webpack_require__("107c"); var dash = __webpack_require__("db54").dash; var fxAttrs = __webpack_require__("a462"); var delta = __webpack_require__("b8ce"); 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 = { 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', } }), }; /***/ }), /***/ "6672": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var tinycolor = __webpack_require__("66cb"); var baseTraceAttrs = __webpack_require__("a876"); var colorscales = __webpack_require__("4852"); var DESELECTDIM = __webpack_require__("72a4").DESELECTDIM; var nestedProperty = __webpack_require__("74d6"); var counterRegex = __webpack_require__("055a").counter; var modHalf = __webpack_require__("d3dc").modHalf; var isArrayOrTypedArray = __webpack_require__("6af8").isArrayOrTypedArray; exports.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also if(isArrayOrTypedArray(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(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(!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(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(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(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(typeof v !== 'string') { propOut.set(dflt); return; } if((opts.extras || []).indexOf(v) !== -1) { propOut.set(v); 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(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; } var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); return; } var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); var arrayItems2D = arrayItems && twoD && Array.isArray(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 = Array.isArray(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(!Array.isArray(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(!Array.isArray(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; /** * 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) */ if(opts.arrayOk && isArrayOrTypedArray(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) { var out = {}; dfltObj = dfltObj || {}; out.family = coerce(attr + '.family', dfltObj.family); out.size = coerce(attr + '.size', dfltObj.size); out.color = coerce(attr + '.color', dfltObj.color); return out; }; /** 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; /***/ }), /***/ "66ac": /***/ (function(module, exports, __webpack_require__) { "use strict"; var bnsub = __webpack_require__("9c7c") module.exports = sub function sub(a, b) { var n = a.length var r = new Array(n) for(var i=0; i= 0; var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); if (needsAlphaFormat) { // Special case for "transparent", all other non-alpha formats // will return rgba when there is transparency. if (format === "name" && this._a === 0) { return this.toName(); } return this.toRgbString(); } if (format === "rgb") { formattedString = this.toRgbString(); } if (format === "prgb") { formattedString = this.toPercentageRgbString(); } if (format === "hex" || format === "hex6") { formattedString = this.toHexString(); } if (format === "hex3") { formattedString = this.toHexString(true); } if (format === "hex4") { formattedString = this.toHex8String(true); } if (format === "hex8") { formattedString = this.toHex8String(); } if (format === "name") { formattedString = this.toName(); } if (format === "hsl") { formattedString = this.toHslString(); } if (format === "hsv") { formattedString = this.toHsvString(); } return formattedString || this.toHexString(); }, clone: function() { return tinycolor(this.toString()); }, _applyModification: function(fn, args) { var color = fn.apply(null, [this].concat([].slice.call(args))); this._r = color._r; this._g = color._g; this._b = color._b; this.setAlpha(color._a); return this; }, lighten: function() { return this._applyModification(lighten, arguments); }, brighten: function() { return this._applyModification(brighten, arguments); }, darken: function() { return this._applyModification(darken, arguments); }, desaturate: function() { return this._applyModification(desaturate, arguments); }, saturate: function() { return this._applyModification(saturate, arguments); }, greyscale: function() { return this._applyModification(greyscale, arguments); }, spin: function() { return this._applyModification(spin, arguments); }, _applyCombination: function(fn, args) { return fn.apply(null, [this].concat([].slice.call(args))); }, analogous: function() { return this._applyCombination(analogous, arguments); }, complement: function() { return this._applyCombination(complement, arguments); }, monochromatic: function() { return this._applyCombination(monochromatic, arguments); }, splitcomplement: function() { return this._applyCombination(splitcomplement, arguments); }, triad: function() { return this._applyCombination(triad, arguments); }, tetrad: function() { return this._applyCombination(tetrad, arguments); } }; // If input is an object, force 1 into "1.0" to handle ratios properly // String input requires "1.0" as input, so 1 will be treated as 1 tinycolor.fromRatio = function(color, opts) { if (typeof color == "object") { var newColor = {}; for (var i in color) { if (color.hasOwnProperty(i)) { if (i === "a") { newColor[i] = color[i]; } else { newColor[i] = convertToPercentage(color[i]); } } } color = newColor; } return tinycolor(color, opts); }; // Given a string or object, convert that input to RGB // Possible string inputs: // // "red" // "#f00" or "f00" // "#ff0000" or "ff0000" // "#ff000000" or "ff000000" // "rgb 255 0 0" or "rgb (255, 0, 0)" // "rgb 1.0 0 0" or "rgb (1, 0, 0)" // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" // function inputToRGB(color) { var rgb = { r: 0, g: 0, b: 0 }; var a = 1; var s = null; var v = null; var l = null; var ok = false; var format = false; if (typeof color == "string") { color = stringInputToObject(color); } if (typeof color == "object") { if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { rgb = rgbToRgb(color.r, color.g, color.b); ok = true; format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { s = convertToPercentage(color.s); v = convertToPercentage(color.v); rgb = hsvToRgb(color.h, s, v); ok = true; format = "hsv"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { s = convertToPercentage(color.s); l = convertToPercentage(color.l); rgb = hslToRgb(color.h, s, l); ok = true; format = "hsl"; } if (color.hasOwnProperty("a")) { a = color.a; } } a = boundAlpha(a); return { ok: ok, format: color.format || format, r: mathMin(255, mathMax(rgb.r, 0)), g: mathMin(255, mathMax(rgb.g, 0)), b: mathMin(255, mathMax(rgb.b, 0)), a: a }; } // Conversion Functions // -------------------- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: // // `rgbToRgb` // Handle bounds / percentage checking to conform to CSS color spec // // *Assumes:* r, g, b in [0, 255] or [0, 1] // *Returns:* { r, g, b } in [0, 255] function rgbToRgb(r, g, b){ return { r: bound01(r, 255) * 255, g: bound01(g, 255) * 255, b: bound01(b, 255) * 255 }; } // `rgbToHsl` // Converts an RGB color value to HSL. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] // *Returns:* { h, s, l } in [0,1] function rgbToHsl(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, l = (max + min) / 2; if(max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; } // `hslToRgb` // Converts an HSL color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hslToRgb(h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } if(s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHsv` // Converts an RGB color value to HSV // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] // *Returns:* { h, s, v } in [0,1] function rgbToHsv(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, v = max; var d = max - min; s = max === 0 ? 0 : d / max; if(max == min) { h = 0; // achromatic } else { switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, v: v }; } // `hsvToRgb` // Converts an HSV color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hsvToRgb(h, s, v) { h = bound01(h, 360) * 6; s = bound01(s, 100); v = bound01(v, 100); var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod]; return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHex` // Converts an RGB color to hex // Assumes r, g, and b are contained in the set [0, 255] // Returns a 3 or 6 character hex function rgbToHex(r, g, b, allow3Char) { var hex = [ pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)) ]; // Return a 3 character hex if possible if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } return hex.join(""); } // `rgbaToHex` // Converts an RGBA color plus alpha transparency to hex // Assumes r, g, b are contained in the set [0, 255] and // a in [0, 1]. Returns a 4 or 8 character rgba hex function rgbaToHex(r, g, b, a, allow4Char) { var hex = [ pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)), pad2(convertDecimalToHex(a)) ]; // Return a 4 character hex if possible if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); } return hex.join(""); } // `rgbaToArgbHex` // Converts an RGBA color to an ARGB Hex8 string // Rarely used, but required for "toFilter()" function rgbaToArgbHex(r, g, b, a) { var hex = [ pad2(convertDecimalToHex(a)), pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)) ]; return hex.join(""); } // `equals` // Can be called with any tinycolor input tinycolor.equals = function (color1, color2) { if (!color1 || !color2) { return false; } return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); }; tinycolor.random = function() { return tinycolor.fromRatio({ r: mathRandom(), g: mathRandom(), b: mathRandom() }); }; // Modification Functions // ---------------------- // Thanks to less.js for some of the basics here // function desaturate(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.s -= amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function saturate(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.s += amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function greyscale(color) { return tinycolor(color).desaturate(100); } function lighten (color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.l += amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } function brighten(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var rgb = tinycolor(color).toRgb(); rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); return tinycolor(rgb); } function darken (color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.l -= amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. // Values outside of this range will be wrapped into this range. function spin(color, amount) { var hsl = tinycolor(color).toHsl(); var hue = (hsl.h + amount) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return tinycolor(hsl); } // Combination Functions // --------------------- // Thanks to jQuery xColor for some of the ideas behind these // function complement(color) { var hsl = tinycolor(color).toHsl(); hsl.h = (hsl.h + 180) % 360; return tinycolor(hsl); } function triad(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) ]; } function tetrad(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) ]; } function splitcomplement(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) ]; } function analogous(color, results, slices) { results = results || 6; slices = slices || 30; var hsl = tinycolor(color).toHsl(); var part = 360 / slices; var ret = [tinycolor(color)]; for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { hsl.h = (hsl.h + part) % 360; ret.push(tinycolor(hsl)); } return ret; } function monochromatic(color, results) { results = results || 6; var hsv = tinycolor(color).toHsv(); var h = hsv.h, s = hsv.s, v = hsv.v; var ret = []; var modification = 1 / results; while (results--) { ret.push(tinycolor({ h: h, s: s, v: v})); v = (v + modification) % 1; } return ret; } // Utility Functions // --------------------- tinycolor.mix = function(color1, color2, amount) { amount = (amount === 0) ? 0 : (amount || 50); var rgb1 = tinycolor(color1).toRgb(); var rgb2 = tinycolor(color2).toRgb(); var p = amount / 100; var rgba = { r: ((rgb2.r - rgb1.r) * p) + rgb1.r, g: ((rgb2.g - rgb1.g) * p) + rgb1.g, b: ((rgb2.b - rgb1.b) * p) + rgb1.b, a: ((rgb2.a - rgb1.a) * p) + rgb1.a }; return tinycolor(rgba); }; // Readability Functions // --------------------- // false // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false tinycolor.isReadable = function(color1, color2, wcag2) { var readability = tinycolor.readability(color1, color2); var wcag2Parms, out; out = false; wcag2Parms = validateWCAG2Parms(wcag2); switch (wcag2Parms.level + wcag2Parms.size) { case "AAsmall": case "AAAlarge": out = readability >= 4.5; break; case "AAlarge": out = readability >= 3; break; case "AAAsmall": out = readability >= 7; break; } return out; }; // `mostReadable` // Given a base color and a list of possible foreground or background // colors for that base, returns the most readable color. // Optionally returns Black or White if the most readable color is unreadable. // *Example* // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" tinycolor.mostReadable = function(baseColor, colorList, args) { var bestColor = null; var bestScore = 0; var readability; var includeFallbackColors, level, size ; args = args || {}; includeFallbackColors = args.includeFallbackColors ; level = args.level; size = args.size; for (var i= 0; i < colorList.length ; i++) { readability = tinycolor.readability(baseColor, colorList[i]); if (readability > bestScore) { bestScore = readability; bestColor = tinycolor(colorList[i]); } } if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { return bestColor; } else { args.includeFallbackColors=false; return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); } }; // Big List of Colors // ------------------ // var names = tinycolor.names = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "0ff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "00f", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", burntsienna: "ea7e5d", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "0ff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "f0f", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" }; // Make it easy to access colors via `hexNames[hex]` var hexNames = tinycolor.hexNames = flip(names); // Utilities // --------- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` function flip(o) { var flipped = { }; for (var i in o) { if (o.hasOwnProperty(i)) { flipped[o[i]] = i; } } return flipped; } // Return a valid alpha value [0,1] with all invalid values being set to 1 function boundAlpha(a) { a = parseFloat(a); if (isNaN(a) || a < 0 || a > 1) { a = 1; } return a; } // Take input from [0, n] and return it as [0, 1] function bound01(n, max) { if (isOnePointZero(n)) { n = "100%"; } var processPercent = isPercentage(n); n = mathMin(max, mathMax(0, parseFloat(n))); // Automatically convert percentage into number if (processPercent) { n = parseInt(n * max, 10) / 100; } // Handle floating point rounding errors if ((Math.abs(n - max) < 0.000001)) { return 1; } // Convert into [0, 1] range if it isn't already return (n % max) / parseFloat(max); } // Force a number between 0 and 1 function clamp01(val) { return mathMin(1, mathMax(0, val)); } // Parse a base-16 hex value into a base-10 integer function parseIntFromHex(val) { return parseInt(val, 16); } // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 // function isOnePointZero(n) { return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; } // Check to see if string passed in is a percentage function isPercentage(n) { return typeof n === "string" && n.indexOf('%') != -1; } // Force a hex value to have 2 characters function pad2(c) { return c.length == 1 ? '0' + c : '' + c; } // Replace a decimal with it's percentage value function convertToPercentage(n) { if (n <= 1) { n = (n * 100) + "%"; } return n; } // Converts a decimal to a hex value function convertDecimalToHex(d) { return Math.round(parseFloat(d) * 255).toString(16); } // Converts a hex value to a decimal function convertHexToDecimal(h) { return (parseIntFromHex(h) / 255); } var matchers = (function() { // var CSS_INTEGER = "[-\\+]?\\d+%?"; // var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; // Actual matching. // Parentheses and commas are optional, but not required. // Whitespace can take the place of commas or opening paren var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; return { CSS_UNIT: new RegExp(CSS_UNIT), rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ }; })(); // `isValidCSSUnit` // Take in a single string / number and check to see if it looks like a CSS unit // (see `matchers` above for definition). function isValidCSSUnit(color) { return !!matchers.CSS_UNIT.exec(color); } // `stringInputToObject` // Permissive string parsing. Take in a number of formats, and output an object // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` function stringInputToObject(color) { color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); var named = false; if (names[color]) { color = names[color]; named = true; } else if (color == 'transparent') { return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } // Try to match string input using regular expressions. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] // Just return an object and let the conversion functions handle that. // This way the result will be the same whether the tinycolor is initialized with string or object. var match; if ((match = matchers.rgb.exec(color))) { return { r: match[1], g: match[2], b: match[3] }; } if ((match = matchers.rgba.exec(color))) { return { r: match[1], g: match[2], b: match[3], a: match[4] }; } if ((match = matchers.hsl.exec(color))) { return { h: match[1], s: match[2], l: match[3] }; } if ((match = matchers.hsla.exec(color))) { return { h: match[1], s: match[2], l: match[3], a: match[4] }; } if ((match = matchers.hsv.exec(color))) { return { h: match[1], s: match[2], v: match[3] }; } if ((match = matchers.hsva.exec(color))) { return { h: match[1], s: match[2], v: match[3], a: match[4] }; } if ((match = matchers.hex8.exec(color))) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), a: convertHexToDecimal(match[4]), format: named ? "name" : "hex8" }; } if ((match = matchers.hex6.exec(color))) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), format: named ? "name" : "hex" }; } if ((match = matchers.hex4.exec(color))) { return { r: parseIntFromHex(match[1] + '' + match[1]), g: parseIntFromHex(match[2] + '' + match[2]), b: parseIntFromHex(match[3] + '' + match[3]), a: convertHexToDecimal(match[4] + '' + match[4]), format: named ? "name" : "hex8" }; } if ((match = matchers.hex3.exec(color))) { return { r: parseIntFromHex(match[1] + '' + match[1]), g: parseIntFromHex(match[2] + '' + match[2]), b: parseIntFromHex(match[3] + '' + match[3]), format: named ? "name" : "hex" }; } return false; } function validateWCAG2Parms(parms) { // return valid WCAG2 parms for isReadable. // If input parms are invalid, return {"level":"AA", "size":"small"} var level, size; parms = parms || {"level":"AA", "size":"small"}; level = (parms.level || "AA").toUpperCase(); size = (parms.size || "small").toLowerCase(); if (level !== "AA" && level !== "AAA") { level = "AA"; } if (size !== "small" && size !== "large") { size = "small"; } return {"level":level, "size":size}; } // Node: Export function if ( true && module.exports) { module.exports = tinycolor; } // AMD/requirejs: Define the module else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {return tinycolor;}).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // Browser: Expose to window else {} })(Math); /***/ }), /***/ "66db": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var subTypes = __webpack_require__("de81"); var handleMarkerDefaults = __webpack_require__("5047"); var handleLineDefaults = __webpack_require__("59be"); var handleLineShapeDefaults = __webpack_require__("eb07"); var handleTextDefaults = __webpack_require__("e9f7"); var handleFillColorDefaults = __webpack_require__("3802"); var PTS_LINESONLY = __webpack_require__("de69").PTS_LINESONLY; var attributes = __webpack_require__("8a6e"); 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.hasLines(traceOut)) { handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce); handleLineShapeDefaults(traceIn, traceOut, coerce); coerce('connectgaps'); } if(subTypes.hasMarkers(traceOut)) { handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } 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'); 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 }; /***/ }), /***/ "6726": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * @module parenthesis */ function parse (str, opts) { // pretend non-string parsed per-se if (typeof str !== 'string') return [str] var res = [str] if (typeof opts === 'string' || Array.isArray(opts)) { opts = {brackets: opts} } else if (!opts) opts = {} var brackets = opts.brackets ? (Array.isArray(opts.brackets) ? opts.brackets : [opts.brackets]) : ['{}', '[]', '()'] var escape = opts.escape || '___' var flat = !!opts.flat brackets.forEach(function (bracket) { // create parenthesis regex var pRE = new RegExp(['\\', bracket[0], '[^\\', bracket[0], '\\', bracket[1], ']*\\', bracket[1]].join('')) var ids = [] function replaceToken(token, idx, str){ // save token to res var refId = res.push(token.slice(bracket[0].length, -bracket[1].length)) - 1 ids.push(refId) return escape + refId + escape } res.forEach(function (str, i) { var prevStr // replace paren tokens till there’s none var a = 0 while (str != prevStr) { prevStr = str str = str.replace(pRE, replaceToken) if (a++ > 10e3) throw Error('References have circular dependency. Please, check them.') } res[i] = str }) // wrap found refs to brackets ids = ids.reverse() res = res.map(function (str) { ids.forEach(function (id) { str = str.replace(new RegExp('(\\' + escape + id + '\\' + escape + ')', 'g'), bracket[0] + '$1' + bracket[1]) }) return str }) }) var re = new RegExp('\\' + escape + '([0-9]+)' + '\\' + escape) // transform references to tree function nest (str, refs, escape) { var res = [], match var a = 0 while (match = re.exec(str)) { if (a++ > 10e3) throw Error('Circular references in parenthesis') res.push(str.slice(0, match.index)) res.push(nest(refs[match[1]], refs)) str = str.slice(match.index + match[0].length) } res.push(str) return res } return flat ? res : nest(res[0], res) } function stringify (arg, opts) { if (opts && opts.flat) { var escape = opts && opts.escape || '___' var str = arg[0], prevStr // pretend bad string stringified with no parentheses if (!str) return '' var re = new RegExp('\\' + escape + '([0-9]+)' + '\\' + escape) var a = 0 while (str != prevStr) { if (a++ > 10e3) throw Error('Circular references in ' + arg) prevStr = str str = str.replace(re, replaceRef) } return str } return arg.reduce(function f (prev, curr) { if (Array.isArray(curr)) { curr = curr.reduce(f, '') } return prev + curr }, '') function replaceRef(match, idx){ if (arg[idx] == null) throw Error('Reference ' + idx + 'is undefined') return arg[idx] } } function parenthesis (arg, opts) { if (Array.isArray(arg)) { return stringify(arg, opts) } else { return parse(arg, opts) } } parenthesis.parse = parse parenthesis.stringify = stringify module.exports = parenthesis /***/ }), /***/ "67c4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var axesAttrs = __webpack_require__("d798"); var fontAttrs = __webpack_require__("9845"); var extendFlat = __webpack_require__("9092").extendFlat; var overrideAll = __webpack_require__("cb34").overrideAll; module.exports = overrideAll({ // TODO: only right is supported currently // orient: { // valType: 'enumerated', // // values: ['left', 'right', 'top', 'bottom'], // dflt: 'right', // // }, 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', dflt: 1.02, min: -2, max: 3, }, xanchor: { valType: 'enumerated', values: ['left', 'center', 'right'], dflt: 'left', }, xpad: { valType: 'number', min: 0, dflt: 10, }, y: { valType: 'number', dflt: 0.5, min: -2, max: 3, }, yanchor: { valType: 'enumerated', values: ['top', 'middle', 'bottom'], dflt: 'middle', }, 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.tickmode, nticks: axesAttrs.nticks, tick0: axesAttrs.tick0, dtick: axesAttrs.dtick, tickvals: axesAttrs.tickvals, ticktext: axesAttrs.ticktext, ticks: extendFlat({}, axesAttrs.ticks, {dflt: ''}), ticklen: axesAttrs.ticklen, tickwidth: axesAttrs.tickwidth, tickcolor: axesAttrs.tickcolor, showticklabels: axesAttrs.showticklabels, 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, showexponent: axesAttrs.showexponent, title: { text: { valType: 'string', }, font: fontAttrs({ }), side: { valType: 'enumerated', values: ['right', 'top', 'bottom'], dflt: 'top', } }, _deprecated: { title: { valType: 'string', }, titlefont: fontAttrs({ }), titleside: { valType: 'enumerated', values: ['right', 'top', 'bottom'], dflt: 'top', } } }, 'colorbars', 'from-root'); /***/ }), /***/ "67f2": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var subTypes = __webpack_require__("de81"); var handleMarkerDefaults = __webpack_require__("5047"); var handleLineDefaults = __webpack_require__("59be"); var handleTextDefaults = __webpack_require__("e9f7"); var handleFillColorDefaults = __webpack_require__("3802"); var attributes = __webpack_require__("74b4"); module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { return Lib.coerce(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.hasLines(traceOut)) { handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true}); coerce('connectgaps'); } if(subTypes.hasMarkers(traceOut)) { handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true}); // 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.hasText(traceOut)) { handleTextDefaults(traceIn, traceOut, layout, coerce, {noSelect: true}); } 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; } /***/ }), /***/ "6833": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var tinycolor = __webpack_require__("66cb"); var isArrayOrTypedArray = __webpack_require__("fc26").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(!Array.isArray(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; }; /***/ }), /***/ "6858": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__("cecf")("forEach"); /***/ }), /***/ "68e6": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isObject = __webpack_require__("2160"); module.exports = function (value) { if (!isObject(value)) throw new TypeError(value + " is not an Object"); return value; }; /***/ }), /***/ "6921": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var baseAttributes = __webpack_require__("a876"); var baseLayoutAttributes = __webpack_require__("a685"); var frameAttributes = __webpack_require__("a9cb"); var animationAttributes = __webpack_require__("5b68"); var configAttributes = __webpack_require__("3ff5").configAttributes; // polar attributes are not part of the Registry yet var polarAreaAttrs = __webpack_require__("fa06"); var polarAxisAttrs = __webpack_require__("b7b8"); var editTypes = __webpack_require__("cb34"); var extendFlat = Lib.extendFlat; 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.concat('area').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 if(trace.type === 'area') { valObject = polarAreaAttrs[head]; } 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]; // Polar doesn't populate _modules or _basePlotModules // just fall back on these when the others fail if(head === 'radialaxis' || head === 'angularaxis') { return polarAxisAttrs[head]; } return polarAxisAttrs.layout[head] || 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; if(type === 'area') { _module = { attributes: polarAreaAttrs }; basePlotModule = {}; } else { _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); } } // polar layout attributes layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // 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]; } } } 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.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; // all 'data_array' attrs have a corresponding 'src' attr attrs[attrName + 'src'] = makeSrcAttr(attrName); } else if(attr.arrayOk === true) { // all 'arrayOk' 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 assignPolarLayoutAttrs(layoutAttributes) { extendFlat(layoutAttributes, { radialaxis: polarAxisAttrs.radialaxis, angularaxis: polarAxisAttrs.angularaxis }); extendFlat(layoutAttributes, polarAxisAttrs.layout); return layoutAttributes; } 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)); } /***/ }), /***/ "692b": /***/ (function(module, exports, __webpack_require__) { "use strict"; var objToString = Object.prototype.toString, id = objToString.call(""); module.exports = function (value) { return ( typeof value === "string" || (value && typeof value === "object" && (value instanceof String || objToString.call(value) === id)) || false ); }; /***/ }), /***/ "6954": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var Drawing = __webpack_require__("83d1"); var Colorscale = __webpack_require__("c258"); var svgTextUtils = __webpack_require__("0379"); var Axes = __webpack_require__("0642"); var setConvert = __webpack_require__("1a40"); var heatmapPlot = __webpack_require__("fa8a"); var makeCrossings = __webpack_require__("da89"); var findAllPaths = __webpack_require__("f50a"); var emptyPathinfo = __webpack_require__("3511"); var convertToConstraints = __webpack_require__("849d"); var closeBoundaries = __webpack_require__("c997"); var constants = __webpack_require__("8e43"); 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 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); 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) { 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', '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', '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; if(contours.labelformat) { return fullLayout._d3locale.numberFormat(contours.labelformat); } else { var formatAxis; var cOpts = Colorscale.extractOpts(trace); if(cOpts && cOpts.colorbar && cOpts.colorbar._axis) { formatAxis = cOpts.colorbar._axis; } else { formatAxis = { type: 'linear', _id: 'ycontour', showexponent: 'all', exponentformat: 'B' }; if(contours.type === 'constraint') { var value = contours.value; if(Array.isArray(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 bBox = Drawing.bBox(dummyText.node(), true); return { text: text, width: bBox.width, height: bBox.height, 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 halfWidth = textOpts.width / 2; var halfHeight = textOpts.height / 2; var x = loc.x; var y = loc.y; var theta = loc.theta; var sin = Math.sin(theta); var cos = Math.cos(theta); var dxw = halfWidth * cos; var dxh = halfHeight * sin; var dyw = halfWidth * sin; var dyh = -halfHeight * cos; var bBoxPts = [ [x - dxw - dxh, y - dyw - dyh], [x + dxw - dxh, y + dyw - dyh], [x + dxw + dxh, y + dyw + dyh], [x - dxw + dxh, y - dyw + dyh], ]; labelData.push({ text: textOpts.text, x: x, y: y, dy: textOpts.dy, theta: theta, level: textOpts.level, width: textOpts.width, height: textOpts.height }); 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; } /***/ }), /***/ "6962": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Registry = __webpack_require__("371e"); var appendArrayPointValue = __webpack_require__("c4c7").appendArrayPointValue; var Fx = __webpack_require__("a5c4"); var Lib = __webpack_require__("fc26"); var Events = __webpack_require__("8741"); var helpers = __webpack_require__("fb56"); var pieHelpers = __webpack_require__("59e0"); 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 isTreemap = trace.type === 'treemap'; // 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; 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(isTreemap) { 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); } var hoverItems = { trace: traceNow, y: hoverCenterY, 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'), nameLength: _cast('hoverlabel.namelength'), textAlign: _cast('hoverlabel.align'), hovertemplate: hovertemplate, hovertemplateLabels: hoverPt, eventData: [makeEventData(pt, traceNow, opts.eventDataKeys)] }; 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(isTreemap) { hoverItems.x = hoverCenterX; hoverItems.idealAlign = hoverCenterX < 0 ? 'left' : 'right'; } Fx.loneHover(hoverItems, { container: fullLayoutNow._hoverlayer.node(), outerContainer: fullLayoutNow._paper.node(), gd: gd }); trace._hasHoverLabel = true; } if(isTreemap) { var slice = sliceTop.select('path.surface'); opts.styleOne(slice, pt, traceNow, { hovered: true }); } trace._hasHoverEvent = true; gd.emit('plotly_hover', { points: [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(isTreemap) { var slice = sliceTop.select('path.surface'); opts.styleOne(slice, pt, traceNow, { 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; } /***/ }), /***/ "69f1": /***/ (function(module, exports) { // transliterated from the python snippet here: // http://en.wikipedia.org/wiki/Lanczos_approximation var g = 7; var p = [ 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7 ]; var g_ln = 607/128; var p_ln = [ 0.99999999999999709182, 57.156235665862923517, -59.597960355475491248, 14.136097974741747174, -0.49191381609762019978, 0.33994649984811888699e-4, 0.46523628927048575665e-4, -0.98374475304879564677e-4, 0.15808870322491248884e-3, -0.21026444172410488319e-3, 0.21743961811521264320e-3, -0.16431810653676389022e-3, 0.84418223983852743293e-4, -0.26190838401581408670e-4, 0.36899182659531622704e-5 ]; // Spouge approximation (suitable for large arguments) function lngamma(z) { if(z < 0) return Number('0/0'); var x = p_ln[0]; for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i); var t = z + g_ln + 0.5; return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z); } module.exports = function gamma (z) { if (z < 0.5) { return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z)); } else if(z > 100) return Math.exp(lngamma(z)); else { z -= 1; var x = p[0]; for (var i = 1; i < g + 2; i++) { x += p[i] / (z + i); } var t = z + g + 0.5; return Math.sqrt(2 * Math.PI) * Math.pow(t, z + 0.5) * Math.exp(-t) * x ; } }; module.exports.log = lngamma; /***/ }), /***/ "69f3": /***/ (function(module, exports, __webpack_require__) { var NATIVE_WEAK_MAP = __webpack_require__("7f9a"); var global = __webpack_require__("da84"); var isObject = __webpack_require__("861d"); var createNonEnumerableProperty = __webpack_require__("9112"); var objectHas = __webpack_require__("5135"); var sharedKey = __webpack_require__("f772"); var hiddenKeys = __webpack_require__("d012"); var WeakMap = global.WeakMap; var set, get, has; var enforce = function (it) { return has(it) ? get(it) : set(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (NATIVE_WEAK_MAP) { var store = new WeakMap(); var wmget = store.get; var wmhas = store.has; var wmset = store.set; set = function (it, metadata) { wmset.call(store, it, metadata); return metadata; }; get = function (it) { return wmget.call(store, it) || {}; }; has = function (it) { return wmhas.call(store, it); }; } else { var STATE = sharedKey('state'); hiddenKeys[STATE] = true; set = function (it, metadata) { createNonEnumerableProperty(it, STATE, metadata); return metadata; }; get = function (it) { return objectHas(it, STATE) ? it[STATE] : {}; }; has = function (it) { return objectHas(it, STATE); }; } module.exports = { set: set, get: get, has: has, enforce: enforce, getterFor: getterFor }; /***/ }), /***/ "6a08": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Requirements // ============ var wrap = __webpack_require__("0a3e").wrap; var hasColorscale = __webpack_require__("215c").hasColorscale; var colorscaleCalc = __webpack_require__("3aa8"); var filterUnique = __webpack_require__("5567"); var Drawing = __webpack_require__("83d1"); var Lib = __webpack_require__("fc26"); /** * 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 so we can order them // Should we check for numbers as sort numerically? categoryValues = filterUnique(dim.values).sort(); 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; } /***/ }), /***/ "6a25": /***/ (function(module, exports) { module.exports = [ '<<=' , '>>=' , '++' , '--' , '<<' , '>>' , '<=' , '>=' , '==' , '!=' , '&&' , '||' , '+=' , '-=' , '*=' , '/=' , '%=' , '&=' , '^^' , '^=' , '|=' , '(' , ')' , '[' , ']' , '.' , '!' , '~' , '*' , '/' , '%' , '+' , '-' , '<' , '>' , '&' , '^' , '|' , '?' , ':' , '=' , ',' , ';' , '{' , '}' ] /***/ }), /***/ "6a77": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Axes = __webpack_require__("0642"); var Lib = __webpack_require__("fc26"); var BADNUM = __webpack_require__("e806").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; if(trace.orientation === 'h') { valAxis = xa; valLetter = 'x'; posAxis = ya; posLetter = 'y'; } else { valAxis = ya; valLetter = 'y'; posAxis = xa; posLetter = 'x'; } var posArray = getPos(trace, posLetter, posAxis, fullLayout[numKey]); var dv = Lib.distinctVals(posArray); 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; 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); 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); } } 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' ? _(gd, 'mean ± σ:') : _(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 getPos(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)) { return posAxis.makeCalcdata(trace, posLetter); } 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); } /***/ }), /***/ "6aa3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var wrap = __webpack_require__("0a3e").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({}); }; /***/ }), /***/ "6add": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var id2name = __webpack_require__("3c1c").id2name; var scaleZoom = __webpack_require__("9759"); var makePadFn = __webpack_require__("ce56").makePadFn; var concatExtremes = __webpack_require__("ce56").concatExtremes; var ALMOST_EQUAL = __webpack_require__("e806").ALMOST_EQUAL; var FROM_BL = __webpack_require__("63dc").FROM_BL; exports.handleConstraintDefaults = function(containerIn, containerOut, coerce, opts) { var allAxisIds = opts.allAxisIds; var layoutOut = opts.layoutOut; var scaleanchorDflt = opts.scaleanchorDflt; var constrainDflt = opts.constrainDflt; var constraintGroups = layoutOut._axisConstraintGroups; var matchGroups = layoutOut._axisMatchGroups; var axId = containerOut._id; var axLetter = axId.charAt(0); var splomStash = ((layoutOut._splomAxes || {})[axLetter] || {})[axId] || {}; var thisID = containerOut._id; var letter = thisID.charAt(0); // coerce the constraint mechanics even if this axis has no scaleanchor // because it may be the anchor of another axis. var constrain = coerce('constrain', constrainDflt); Lib.coerce(containerIn, containerOut, { constraintoward: { valType: 'enumerated', values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], dflt: letter === 'x' ? 'center' : 'middle' } }, 'constraintoward'); var matches, matchOpts; if((containerIn.matches || splomStash.matches) && !containerOut.fixedrange) { matchOpts = getConstraintOpts(matchGroups, thisID, allAxisIds, layoutOut); matches = Lib.coerce(containerIn, containerOut, { matches: { valType: 'enumerated', values: matchOpts.linkableAxes || [], dflt: splomStash.matches } }, 'matches'); } // 'matches' wins over 'scaleanchor' (for now) var scaleanchor, scaleOpts; if(!matches && !(containerOut.fixedrange && constrain !== 'domain') && (containerIn.scaleanchor || scaleanchorDflt) ) { scaleOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut, constrain); scaleanchor = Lib.coerce(containerIn, containerOut, { scaleanchor: { valType: 'enumerated', values: scaleOpts.linkableAxes || [] } }, 'scaleanchor', scaleanchorDflt); } if(matches) { delete containerOut.constrain; updateConstraintGroups(matchGroups, matchOpts.thisGroup, thisID, matches, 1); } else if(allAxisIds.indexOf(containerIn.matches) !== -1) { Lib.warn('ignored ' + containerOut._name + '.matches: "' + containerIn.matches + '" to avoid either an infinite loop ' + 'or because the target axis has fixed range.'); } 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 = containerOut.scaleratio = 1; updateConstraintGroups(constraintGroups, scaleOpts.thisGroup, thisID, scaleanchor, scaleratio); } else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { Lib.warn('ignored ' + containerOut._name + '.scaleanchor: "' + containerIn.scaleanchor + '" to avoid either an infinite loop ' + 'and possibly inconsistent scaleratios, or because the target ' + 'axis has fixed range or this axis declares a *matches* constraint.'); } }; // 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 allAxisIds to enforce this, also matching axis types. function getConstraintOpts(groups, thisID, allAxisIds, layoutOut, constrain) { var doesNotConstrainRange = constrain !== 'range'; var thisType = layoutOut[id2name(thisID)].type; var i, j, idj, axj; var linkableAxes = []; for(j = 0; j < allAxisIds.length; j++) { idj = allAxisIds[j]; if(idj === thisID) continue; axj = layoutOut[id2name(idj)]; if(axj.type === thisType) { if(!axj.fixedrange) { linkableAxes.push(idj); } else if(doesNotConstrainRange && axj.anchor) { // allow domain constraints on subplots where // BOTH axes have fixedrange:true and constrain:domain var counterAxj = layoutOut[id2name(axj.anchor)]; if(counterAxj.fixedrange) { linkableAxes.push(idj); } } } } for(i = 0; i < groups.length; i++) { if(groups[i][thisID]) { var thisGroup = groups[i]; var linkableAxesNoLoops = []; for(j = 0; j < linkableAxes.length; j++) { idj = linkableAxes[j]; if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); } return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; } } return {linkableAxes: linkableAxes, thisGroup: null}; } /* * Add this axis to the axis constraint groups, which is the collection * of axes that are all constrained together on scale. * * 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 * scaleanchor: the id of the axis to scale it with * scaleratio: the ratio of this axis to the scaleanchor axis */ function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor, scaleratio) { var i, j, groupi, keyj, thisGroupIndex; 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 scaleanchor axis. If it is, we need to merge the groups. for(i = 0; i < constraintGroups.length; i++) { groupi = constraintGroups[i]; if(i !== thisGroupIndex && groupi[scaleanchor]) { var baseScale = groupi[scaleanchor]; for(j = 0; j < thisGroupKeys.length; j++) { keyj = thisGroupKeys[j]; groupi[keyj] = baseScale * scaleratio * thisGroup[keyj]; } constraintGroups.splice(thisGroupIndex, 1); return; } } // otherwise, we insert the new scaleanchor 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++) { thisGroup[thisGroupKeys[j]] *= scaleratio; } } thisGroup[scaleanchor] = 1; } exports.enforce = function enforce(gd) { var fullLayout = gd._fullLayout; var constraintGroups = fullLayout._axisConstraintGroups || []; var i, j, axisID, ax, normScale, mode, factor; for(i = 0; i < constraintGroups.length; i++) { var group = constraintGroups[i]; 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 getPad = makePadFn(ax); updateDomain(ax, factor); var m = Math.abs(ax._m); var extremes = 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 - getPad(minArray[k]) / m; if(newVal > outerMin && newVal < rangeMin) { rangeMin = newVal; } } for(k = 0; k < maxArray.length; k++) { newVal = maxArray[k].val + getPad(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); } } } } }; // 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(); } /***/ }), /***/ "6af8": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isArray = Array.isArray; // IE9 fallbacks var ab = (typeof ArrayBuffer === 'undefined' || !ArrayBuffer.isView) ? {isView: function() { return false; }} : ArrayBuffer; var dv = (typeof DataView === 'undefined') ? function() {} : 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; }; /* * 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; } /***/ }), /***/ "6b10": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Template = __webpack_require__("a651"); var axisIds = __webpack_require__("3c1c"); var attributes = __webpack_require__("8f38"); var oppAxisAttrs = __webpack_require__("5844"); 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; }; /***/ }), /***/ "6b38": /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/** @module gl-util/context */ var pick = __webpack_require__("b7d1") module.exports = function setContext (o) { if (!o) o = {} else if (typeof o === 'string') o = {container: o} // HTMLCanvasElement if (isCanvas(o)) { o = {container: o} } // HTMLElement else if (isElement(o)) { o = {container: o} } // WebGLContext else if (isContext(o)) { o = {gl: o} } // options object else { o = pick(o, { container: 'container target element el canvas holder parent parentNode wrapper use ref root node', gl: 'gl context webgl glContext', attrs: 'attributes attrs contextAttributes', pixelRatio: 'pixelRatio pxRatio px ratio pxratio pixelratio', width: 'w width', height: 'h height' }, true) } if (!o.pixelRatio) o.pixelRatio = global.pixelRatio || 1 // make sure there is container and canvas if (o.gl) { return o.gl } if (o.canvas) { o.container = o.canvas.parentNode } if (o.container) { if (typeof o.container === 'string') { var c = document.querySelector(o.container) if (!c) throw Error('Element ' + o.container + ' is not found') o.container = c } if (isCanvas(o.container)) { o.canvas = o.container o.container = o.canvas.parentNode } else if (!o.canvas) { o.canvas = createCanvas() o.container.appendChild(o.canvas) resize(o) } } // blank new canvas else if (!o.canvas) { if (typeof document !== 'undefined') { o.container = document.body || document.documentElement o.canvas = createCanvas() o.container.appendChild(o.canvas) resize(o) } else { throw Error('Not DOM environment. Use headless-gl.') } } // make sure there is context if (!o.gl) { try { o.gl = o.canvas.getContext('webgl', o.attrs) } catch (e) { try { o.gl = o.canvas.getContext('experimental-webgl', o.attrs) } catch (e) { o.gl = o.canvas.getContext('webgl-experimental', o.attrs) } } } return o.gl } function resize (o) { if (o.container) { if (o.container == document.body) { if (!document.body.style.width) o.canvas.width = o.width || (o.pixelRatio * global.innerWidth) if (!document.body.style.height) o.canvas.height = o.height || (o.pixelRatio * global.innerHeight) } else { var bounds = o.container.getBoundingClientRect() o.canvas.width = o.width || (bounds.right - bounds.left) o.canvas.height = o.height || (bounds.bottom - bounds.top) } } } function isCanvas (e) { return typeof e.getContext === 'function' && 'width' in e && 'height' in e } function isElement (e) { return typeof e.nodeName === 'string' && typeof e.appendChild === 'function' && typeof e.getBoundingClientRect === 'function' } function isContext (e) { return typeof e.drawArrays === 'function' || typeof e.drawElements === 'function' } function createCanvas () { var canvas = document.createElement('canvas') canvas.style.position = 'absolute' canvas.style.top = 0 canvas.style.left = 0 return canvas } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("c8ba"))) /***/ }), /***/ "6b3c": /***/ (function(module, exports, __webpack_require__) { "use strict"; var createShader = __webpack_require__("28dd") var createBuffer = __webpack_require__("efce") var createVAO = __webpack_require__("b205") var createTexture = __webpack_require__("1d5b") var multiply = __webpack_require__("1417") var invert = __webpack_require__("9343") var ndarray = __webpack_require__("b5bb") var colormap = __webpack_require__("595c") var IDENTITY = [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] function VectorMesh(gl , texture , triShader , pickShader , trianglePositions , triangleVectors , triangleIds , triangleColors , triangleUVs , triangleVAO , traceType) { this.gl = gl this.pixelRatio = 1 this.cells = [] this.positions = [] this.intensity = [] this.texture = texture this.dirty = true this.triShader = triShader this.pickShader = pickShader this.trianglePositions = trianglePositions this.triangleVectors = triangleVectors this.triangleColors = triangleColors this.triangleUVs = triangleUVs this.triangleIds = triangleIds this.triangleVAO = triangleVAO this.triangleCount = 0 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 this.traceType = traceType this.tubeScale = 1 // used in streamtube this.coneScale = 2 // used in cone this.vectorScale = 1 // used in cone this.coneOffset = 0.25 // used in cone this._model = IDENTITY this._view = IDENTITY this._projection = IDENTITY this._resolution = [1,1] } var proto = VectorMesh.prototype proto.isOpaque = function() { return this.opacity >= 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; i 0) { 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 /***/ }), /***/ "6b50": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorScaleAttrs = __webpack_require__("f4e9"); var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var surfaceAttrs = __webpack_require__("02ea"); var baseAttrs = __webpack_require__("a876"); var extendFlat = __webpack_require__("9092").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'}), 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}) }); /***/ }), /***/ "6b5f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var plots = __webpack_require__("bb71"); 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); }; /***/ }), /***/ "6b78": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; } }; /***/ }), /***/ "6bd5": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Colorscale = __webpack_require__("c258"); var heatmapCalc = __webpack_require__("0625"); var setContours = __webpack_require__("8a7d"); var endPlus = __webpack_require__("bc6b"); // 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; }; /***/ }), /***/ "6c5a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * 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) ); }; /***/ }), /***/ "6c77": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='], COMPARISON_OPS2: ['=', '<', '>=', '>', '<='], INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['], SET_OPS: ['{}', '}{'], CONSTRAINT_REDUCTION: { // for contour constraints, open/closed endpoints are equivalent '=': '=', '<': '<', '<=': '<', '>': '>', '>=': '>', '[]': '[]', '()': '[]', '[)': '[]', '(]': '[]', '][': '][', ')(': '][', '](': '][', ')[': '][' } }; /***/ }), /***/ "6ca5": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("89ab"); /***/ }), /***/ "6ceb": /***/ (function(module, exports, __webpack_require__) { var getContext = __webpack_require__("fda9") module.exports = function getWebGLContext (opt) { return getContext('webgl', opt) } /***/ }), /***/ "6d08": /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {// Generated by CoffeeScript 1.12.2 (function() { var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; if ((typeof performance !== "undefined" && performance !== null) && performance.now) { module.exports = function() { return performance.now(); }; } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { module.exports = function() { return (getNanoSeconds() - nodeLoadTime) / 1e6; }; hrtime = process.hrtime; getNanoSeconds = function() { var hr; hr = hrtime(); return hr[0] * 1e9 + hr[1]; }; moduleLoadTime = getNanoSeconds(); upTime = process.uptime() * 1e9; nodeLoadTime = moduleLoadTime - upTime; } else if (Date.now) { module.exports = function() { return Date.now() - loadTime; }; loadTime = Date.now(); } else { module.exports = function() { return new Date().getTime() - loadTime; }; loadTime = new Date().getTime(); } }).call(this); //# sourceMappingURL=performance-now.js.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("4362"))) /***/ }), /***/ "6d0a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("c7c2"); /***/ }), /***/ "6dcc": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); 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; } }; /***/ }), /***/ "6dd0": /***/ (function(module) { module.exports = JSON.parse("[\"caption\",\"icon\",\"menu\",\"message-box\",\"small-caption\",\"status-bar\"]"); /***/ }), /***/ "6dea": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorscaleCalc = __webpack_require__("3aa8"); module.exports = function calc(gd, trace) { if(trace.intensity) { colorscaleCalc(gd, trace, { vals: trace.intensity, containerStr: '', cLetter: 'c' }); } }; /***/ }), /***/ "6e1f": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = segmentsIntersect var orient = __webpack_require__("92ba")[3] function checkCollinear(a0, a1, b0, b1) { for(var d=0; d<2; ++d) { var x0 = a0[d] var y0 = a1[d] var l0 = Math.min(x0, y0) var h0 = Math.max(x0, y0) var x1 = b0[d] var y1 = b1[d] var l1 = Math.min(x1, y1) var h1 = Math.max(x1, y1) if(h1 < l0 || h0 < l1) { return false } } return true } function segmentsIntersect(a0, a1, b0, b1) { var x0 = orient(a0, b0, b1) var y0 = orient(a1, b0, b1) if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { return false } var x1 = orient(b0, a0, a1) var y1 = orient(b1, a0, a1) if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { return false } //Check for degenerate collinear case if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) { return checkCollinear(a0, a1, b0, b1) } return true } /***/ }), /***/ "6e40": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var modModule = __webpack_require__("d3dc"); 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 }; /***/ }), /***/ "6e58": /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;!function() { var d3 = { version: "3.5.17" }; var d3_arraySlice = [].slice, d3_array = function(list) { return d3_arraySlice.call(list); }; var d3_document = this.document; function d3_documentElement(node) { return node && (node.ownerDocument || node.document || node).documentElement; } function d3_window(node) { return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView); } if (d3_document) { try { d3_array(d3_document.documentElement.childNodes)[0].nodeType; } catch (e) { d3_array = function(list) { var i = list.length, array = new Array(i); while (i--) array[i] = list[i]; return array; }; } } if (!Date.now) Date.now = function() { return +new Date(); }; if (d3_document) { try { d3_document.createElement("DIV").style.setProperty("opacity", 0, ""); } catch (error) { var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; d3_element_prototype.setAttribute = function(name, value) { d3_element_setAttribute.call(this, name, value + ""); }; d3_element_prototype.setAttributeNS = function(space, local, value) { d3_element_setAttributeNS.call(this, space, local, value + ""); }; d3_style_prototype.setProperty = function(name, value, priority) { d3_style_setProperty.call(this, name, value + "", priority); }; } } d3.ascending = d3_ascending; function d3_ascending(a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; } d3.descending = function(a, b) { return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; }; d3.min = function(array, f) { var i = -1, n = array.length, a, b; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = b; break; } while (++i < n) if ((b = array[i]) != null && a > b) a = b; } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; } return a; }; d3.max = function(array, f) { var i = -1, n = array.length, a, b; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = b; break; } while (++i < n) if ((b = array[i]) != null && b > a) a = b; } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; } return a; }; d3.extent = function(array, f) { var i = -1, n = array.length, a, b, c; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = c = b; break; } while (++i < n) if ((b = array[i]) != null) { if (a > b) a = b; if (c < b) c = b; } } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = c = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null) { if (a > b) a = b; if (c < b) c = b; } } return [ a, c ]; }; function d3_number(x) { return x === null ? NaN : +x; } function d3_numeric(x) { return !isNaN(x); } d3.sum = function(array, f) { var s = 0, n = array.length, a, i = -1; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = +array[i])) s += a; } else { while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; } return s; }; d3.mean = function(array, f) { var s = 0, n = array.length, a, i = -1, j = n; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; } else { while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; } if (j) return s / j; }; d3.quantile = function(values, p) { var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; return e ? v + e * (values[h] - v) : v; }; d3.median = function(array, f) { var numbers = [], n = array.length, a, i = -1; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); } else { while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); } if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); }; d3.variance = function(array, f) { var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; if (arguments.length === 1) { while (++i < n) { if (d3_numeric(a = d3_number(array[i]))) { d = a - m; m += d / ++j; s += d * (a - m); } } } else { while (++i < n) { if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { d = a - m; m += d / ++j; s += d * (a - m); } } } if (j > 1) return s / (j - 1); }; d3.deviation = function() { var v = d3.variance.apply(this, arguments); return v ? Math.sqrt(v) : v; }; function d3_bisector(compare) { return { left: function(a, x, lo, hi) { if (arguments.length < 3) lo = 0; if (arguments.length < 4) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; } return lo; }, right: function(a, x, lo, hi) { if (arguments.length < 3) lo = 0; if (arguments.length < 4) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; } return lo; } }; } var d3_bisect = d3_bisector(d3_ascending); d3.bisectLeft = d3_bisect.left; d3.bisect = d3.bisectRight = d3_bisect.right; d3.bisector = function(f) { return d3_bisector(f.length === 1 ? function(d, x) { return d3_ascending(f(d), x); } : f); }; d3.shuffle = function(array, i0, i1) { if ((m = arguments.length) < 3) { i1 = array.length; if (m < 2) i0 = 0; } var m = i1 - i0, t, i; while (m) { i = Math.random() * m-- | 0; t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; } return array; }; d3.permute = function(array, indexes) { var i = indexes.length, permutes = new Array(i); while (i--) permutes[i] = array[indexes[i]]; return permutes; }; d3.pairs = function(array) { var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; return pairs; }; d3.transpose = function(matrix) { if (!(n = matrix.length)) return []; for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { row[j] = matrix[j][i]; } } return transpose; }; function d3_transposeLength(d) { return d.length; } d3.zip = function() { return d3.transpose(arguments); }; d3.keys = function(map) { var keys = []; for (var key in map) keys.push(key); return keys; }; d3.values = function(map) { var values = []; for (var key in map) values.push(map[key]); return values; }; d3.entries = function(map) { var entries = []; for (var key in map) entries.push({ key: key, value: map[key] }); return entries; }; d3.merge = function(arrays) { var n = arrays.length, m, i = -1, j = 0, merged, array; while (++i < n) j += arrays[i].length; merged = new Array(j); while (--n >= 0) { array = arrays[n]; m = array.length; while (--m >= 0) { merged[--j] = array[m]; } } return merged; }; var abs = Math.abs; d3.range = function(start, stop, step) { if (arguments.length < 3) { step = 1; if (arguments.length < 2) { stop = start; start = 0; } } if ((stop - start) / step === Infinity) throw new Error("infinite range"); var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; start *= k, stop *= k, step *= k; if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); return range; }; function d3_range_integerScale(x) { var k = 1; while (x * k % 1) k *= 10; return k; } function d3_class(ctor, properties) { for (var key in properties) { Object.defineProperty(ctor.prototype, key, { value: properties[key], enumerable: false }); } } d3.map = function(object, f) { var map = new d3_Map(); if (object instanceof d3_Map) { object.forEach(function(key, value) { map.set(key, value); }); } else if (Array.isArray(object)) { var i = -1, n = object.length, o; if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); } else { for (var key in object) map.set(key, object[key]); } return map; }; function d3_Map() { this._ = Object.create(null); } var d3_map_proto = "__proto__", d3_map_zero = "\x00"; d3_class(d3_Map, { has: d3_map_has, get: function(key) { return this._[d3_map_escape(key)]; }, set: function(key, value) { return this._[d3_map_escape(key)] = value; }, remove: d3_map_remove, keys: d3_map_keys, values: function() { var values = []; for (var key in this._) values.push(this._[key]); return values; }, entries: function() { var entries = []; for (var key in this._) entries.push({ key: d3_map_unescape(key), value: this._[key] }); return entries; }, size: d3_map_size, empty: d3_map_empty, forEach: function(f) { for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); } }); function d3_map_escape(key) { return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; } function d3_map_unescape(key) { return (key += "")[0] === d3_map_zero ? key.slice(1) : key; } function d3_map_has(key) { return d3_map_escape(key) in this._; } function d3_map_remove(key) { return (key = d3_map_escape(key)) in this._ && delete this._[key]; } function d3_map_keys() { var keys = []; for (var key in this._) keys.push(d3_map_unescape(key)); return keys; } function d3_map_size() { var size = 0; for (var key in this._) ++size; return size; } function d3_map_empty() { for (var key in this._) return false; return true; } d3.nest = function() { var nest = {}, keys = [], sortKeys = [], sortValues, rollup; function map(mapType, array, depth) { if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; while (++i < n) { if (values = valuesByKey.get(keyValue = key(object = array[i]))) { values.push(object); } else { valuesByKey.set(keyValue, [ object ]); } } if (mapType) { object = mapType(); setter = function(keyValue, values) { object.set(keyValue, map(mapType, values, depth)); }; } else { object = {}; setter = function(keyValue, values) { object[keyValue] = map(mapType, values, depth); }; } valuesByKey.forEach(setter); return object; } function entries(map, depth) { if (depth >= keys.length) return map; var array = [], sortKey = sortKeys[depth++]; map.forEach(function(key, keyMap) { array.push({ key: key, values: entries(keyMap, depth) }); }); return sortKey ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array; } nest.map = function(array, mapType) { return map(mapType, array, 0); }; nest.entries = function(array) { return entries(map(d3.map, array, 0), 0); }; nest.key = function(d) { keys.push(d); return nest; }; nest.sortKeys = function(order) { sortKeys[keys.length - 1] = order; return nest; }; nest.sortValues = function(order) { sortValues = order; return nest; }; nest.rollup = function(f) { rollup = f; return nest; }; return nest; }; d3.set = function(array) { var set = new d3_Set(); if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); return set; }; function d3_Set() { this._ = Object.create(null); } d3_class(d3_Set, { has: d3_map_has, add: function(key) { this._[d3_map_escape(key += "")] = true; return key; }, remove: d3_map_remove, values: d3_map_keys, size: d3_map_size, empty: d3_map_empty, forEach: function(f) { for (var key in this._) f.call(this, d3_map_unescape(key)); } }); d3.behavior = {}; function d3_identity(d) { return d; } d3.rebind = function(target, source) { var i = 1, n = arguments.length, method; while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); return target; }; function d3_rebind(target, source, method) { return function() { var value = method.apply(source, arguments); return value === source ? target : value; }; } function d3_vendorSymbol(object, name) { if (name in object) return name; name = name.charAt(0).toUpperCase() + name.slice(1); for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { var prefixName = d3_vendorPrefixes[i] + name; if (prefixName in object) return prefixName; } } var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; function d3_noop() {} d3.dispatch = function() { var dispatch = new d3_dispatch(), i = -1, n = arguments.length; while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); return dispatch; }; function d3_dispatch() {} d3_dispatch.prototype.on = function(type, listener) { var i = type.indexOf("."), name = ""; if (i >= 0) { name = type.slice(i + 1); type = type.slice(0, i); } if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); if (arguments.length === 2) { if (listener == null) for (type in this) { if (this.hasOwnProperty(type)) this[type].on(name, null); } return this; } }; function d3_dispatch_event(dispatch) { var listeners = [], listenerByName = new d3_Map(); function event() { var z = listeners, i = -1, n = z.length, l; while (++i < n) if (l = z[i].on) l.apply(this, arguments); return dispatch; } event.on = function(name, listener) { var l = listenerByName.get(name), i; if (arguments.length < 2) return l && l.on; if (l) { l.on = null; listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); listenerByName.remove(name); } if (listener) listeners.push(listenerByName.set(name, { on: listener })); return dispatch; }; return event; } d3.event = null; function d3_eventPreventDefault() { d3.event.preventDefault(); } function d3_eventSource() { var e = d3.event, s; while (s = e.sourceEvent) e = s; return e; } function d3_eventDispatch(target) { var dispatch = new d3_dispatch(), i = 0, n = arguments.length; while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); dispatch.of = function(thiz, argumentz) { return function(e1) { try { var e0 = e1.sourceEvent = d3.event; e1.target = target; d3.event = e1; dispatch[e1.type].apply(thiz, argumentz); } finally { d3.event = e0; } }; }; return dispatch; } d3.requote = function(s) { return s.replace(d3_requote_re, "\\$&"); }; var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; var d3_subclass = {}.__proto__ ? function(object, prototype) { object.__proto__ = prototype; } : function(object, prototype) { for (var property in prototype) object[property] = prototype[property]; }; function d3_selection(groups) { d3_subclass(groups, d3_selectionPrototype); return groups; } var d3_select = function(s, n) { return n.querySelector(s); }, d3_selectAll = function(s, n) { return n.querySelectorAll(s); }, d3_selectMatches = function(n, s) { var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; d3_selectMatches = function(n, s) { return d3_selectMatcher.call(n, s); }; return d3_selectMatches(n, s); }; if (typeof Sizzle === "function") { d3_select = function(s, n) { return Sizzle(s, n)[0] || null; }; d3_selectAll = Sizzle; d3_selectMatches = Sizzle.matchesSelector; } d3.selection = function() { return d3.select(d3_document.documentElement); }; var d3_selectionPrototype = d3.selection.prototype = []; d3_selectionPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, group, node; selector = d3_selection_selector(selector); for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); subgroup.parentNode = (group = this[j]).parentNode; for (var i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroup.push(subnode = selector.call(node, node.__data__, i, j)); if (subnode && "__data__" in node) subnode.__data__ = node.__data__; } else { subgroup.push(null); } } } return d3_selection(subgroups); }; function d3_selection_selector(selector) { return typeof selector === "function" ? selector : function() { return d3_select(selector, this); }; } d3_selectionPrototype.selectAll = function(selector) { var subgroups = [], subgroup, node; selector = d3_selection_selectorAll(selector); for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); subgroup.parentNode = node; } } } return d3_selection(subgroups); }; function d3_selection_selectorAll(selector) { return typeof selector === "function" ? selector : function() { return d3_selectAll(selector, this); }; } var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; var d3_nsPrefix = { svg: "http://www.w3.org/2000/svg", xhtml: d3_nsXhtml, xlink: "http://www.w3.org/1999/xlink", xml: "http://www.w3.org/XML/1998/namespace", xmlns: "http://www.w3.org/2000/xmlns/" }; d3.ns = { prefix: d3_nsPrefix, qualify: function(name) { var i = name.indexOf(":"), prefix = name; if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); return d3_nsPrefix.hasOwnProperty(prefix) ? { space: d3_nsPrefix[prefix], local: name } : name; } }; d3_selectionPrototype.attr = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { var node = this.node(); name = d3.ns.qualify(name); return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); } for (value in name) this.each(d3_selection_attr(value, name[value])); return this; } return this.each(d3_selection_attr(name, value)); }; function d3_selection_attr(name, value) { name = d3.ns.qualify(name); function attrNull() { this.removeAttribute(name); } function attrNullNS() { this.removeAttributeNS(name.space, name.local); } function attrConstant() { this.setAttribute(name, value); } function attrConstantNS() { this.setAttributeNS(name.space, name.local, value); } function attrFunction() { var x = value.apply(this, arguments); if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); } function attrFunctionNS() { var x = value.apply(this, arguments); if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); } return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; } function d3_collapse(s) { return s.trim().replace(/\s+/g, " "); } d3_selectionPrototype.classed = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; if (value = node.classList) { while (++i < n) if (!value.contains(name[i])) return false; } else { value = node.getAttribute("class"); while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; } return true; } for (value in name) this.each(d3_selection_classed(value, name[value])); return this; } return this.each(d3_selection_classed(name, value)); }; function d3_selection_classedRe(name) { return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); } function d3_selection_classes(name) { return (name + "").trim().split(/^|\s+/); } function d3_selection_classed(name, value) { name = d3_selection_classes(name).map(d3_selection_classedName); var n = name.length; function classedConstant() { var i = -1; while (++i < n) name[i](this, value); } function classedFunction() { var i = -1, x = value.apply(this, arguments); while (++i < n) name[i](this, x); } return typeof value === "function" ? classedFunction : classedConstant; } function d3_selection_classedName(name) { var re = d3_selection_classedRe(name); return function(node, value) { if (c = node.classList) return value ? c.add(name) : c.remove(name); var c = node.getAttribute("class") || ""; if (value) { re.lastIndex = 0; if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); } else { node.setAttribute("class", d3_collapse(c.replace(re, " "))); } }; } d3_selectionPrototype.style = function(name, value, priority) { var n = arguments.length; if (n < 3) { if (typeof name !== "string") { if (n < 2) value = ""; for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); return this; } if (n < 2) { var node = this.node(); return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); } priority = ""; } return this.each(d3_selection_style(name, value, priority)); }; function d3_selection_style(name, value, priority) { function styleNull() { this.style.removeProperty(name); } function styleConstant() { this.style.setProperty(name, value, priority); } function styleFunction() { var x = value.apply(this, arguments); if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); } return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; } d3_selectionPrototype.property = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") return this.node()[name]; for (value in name) this.each(d3_selection_property(value, name[value])); return this; } return this.each(d3_selection_property(name, value)); }; function d3_selection_property(name, value) { function propertyNull() { delete this[name]; } function propertyConstant() { this[name] = value; } function propertyFunction() { var x = value.apply(this, arguments); if (x == null) delete this[name]; else this[name] = x; } return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; } d3_selectionPrototype.text = function(value) { return arguments.length ? this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.textContent = v == null ? "" : v; } : value == null ? function() { this.textContent = ""; } : function() { this.textContent = value; }) : this.node().textContent; }; d3_selectionPrototype.html = function(value) { return arguments.length ? this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.innerHTML = v == null ? "" : v; } : value == null ? function() { this.innerHTML = ""; } : function() { this.innerHTML = value; }) : this.node().innerHTML; }; d3_selectionPrototype.append = function(name) { name = d3_selection_creator(name); return this.select(function() { return this.appendChild(name.apply(this, arguments)); }); }; function d3_selection_creator(name) { function create() { var document = this.ownerDocument, namespace = this.namespaceURI; return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name); } function createNS() { return this.ownerDocument.createElementNS(name.space, name.local); } return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; } d3_selectionPrototype.insert = function(name, before) { name = d3_selection_creator(name); before = d3_selection_selector(before); return this.select(function() { return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); }); }; d3_selectionPrototype.remove = function() { return this.each(d3_selectionRemove); }; function d3_selectionRemove() { var parent = this.parentNode; if (parent) parent.removeChild(this); } d3_selectionPrototype.data = function(value, key) { var i = -1, n = this.length, group, node; if (!arguments.length) { value = new Array(n = (group = this[0]).length); while (++i < n) { if (node = group[i]) { value[i] = node.__data__; } } return value; } function bind(group, groupData) { var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; if (key) { var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; for (i = -1; ++i < n; ) { if (node = group[i]) { if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) { exitNodes[i] = node; } else { nodeByKeyValue.set(keyValue, node); } keyValues[i] = keyValue; } } for (i = -1; ++i < m; ) { if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { enterNodes[i] = d3_selection_dataNode(nodeData); } else if (node !== true) { updateNodes[i] = node; node.__data__ = nodeData; } nodeByKeyValue.set(keyValue, true); } for (i = -1; ++i < n; ) { if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) { exitNodes[i] = group[i]; } } } else { for (i = -1; ++i < n0; ) { node = group[i]; nodeData = groupData[i]; if (node) { node.__data__ = nodeData; updateNodes[i] = node; } else { enterNodes[i] = d3_selection_dataNode(nodeData); } } for (;i < m; ++i) { enterNodes[i] = d3_selection_dataNode(groupData[i]); } for (;i < n; ++i) { exitNodes[i] = group[i]; } } enterNodes.update = updateNodes; enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; enter.push(enterNodes); update.push(updateNodes); exit.push(exitNodes); } var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); if (typeof value === "function") { while (++i < n) { bind(group = this[i], value.call(group, group.parentNode.__data__, i)); } } else { while (++i < n) { bind(group = this[i], value); } } update.enter = function() { return enter; }; update.exit = function() { return exit; }; return update; }; function d3_selection_dataNode(data) { return { __data__: data }; } d3_selectionPrototype.datum = function(value) { return arguments.length ? this.property("__data__", value) : this.property("__data__"); }; d3_selectionPrototype.filter = function(filter) { var subgroups = [], subgroup, group, node; if (typeof filter !== "function") filter = d3_selection_filter(filter); for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); subgroup.parentNode = (group = this[j]).parentNode; for (var i = 0, n = group.length; i < n; i++) { if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { subgroup.push(node); } } } return d3_selection(subgroups); }; function d3_selection_filter(selector) { return function() { return d3_selectMatches(this, selector); }; } d3_selectionPrototype.order = function() { for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { if (node = group[i]) { if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); next = node; } } } return this; }; d3_selectionPrototype.sort = function(comparator) { comparator = d3_selection_sortComparator.apply(this, arguments); for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); return this.order(); }; function d3_selection_sortComparator(comparator) { if (!arguments.length) comparator = d3_ascending; return function(a, b) { return a && b ? comparator(a.__data__, b.__data__) : !a - !b; }; } d3_selectionPrototype.each = function(callback) { return d3_selection_each(this, function(node, i, j) { callback.call(node, node.__data__, i, j); }); }; function d3_selection_each(groups, callback) { for (var j = 0, m = groups.length; j < m; j++) { for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { if (node = group[i]) callback(node, i, j); } } return groups; } d3_selectionPrototype.call = function(callback) { var args = d3_array(arguments); callback.apply(args[0] = this, args); return this; }; d3_selectionPrototype.empty = function() { return !this.node(); }; d3_selectionPrototype.node = function() { for (var j = 0, m = this.length; j < m; j++) { for (var group = this[j], i = 0, n = group.length; i < n; i++) { var node = group[i]; if (node) return node; } } return null; }; d3_selectionPrototype.size = function() { var n = 0; d3_selection_each(this, function() { ++n; }); return n; }; function d3_selection_enter(selection) { d3_subclass(selection, d3_selection_enterPrototype); return selection; } var d3_selection_enterPrototype = []; d3.selection.enter = d3_selection_enter; d3.selection.enter.prototype = d3_selection_enterPrototype; d3_selection_enterPrototype.append = d3_selectionPrototype.append; d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; d3_selection_enterPrototype.node = d3_selectionPrototype.node; d3_selection_enterPrototype.call = d3_selectionPrototype.call; d3_selection_enterPrototype.size = d3_selectionPrototype.size; d3_selection_enterPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, upgroup, group, node; for (var j = -1, m = this.length; ++j < m; ) { upgroup = (group = this[j]).update; subgroups.push(subgroup = []); subgroup.parentNode = group.parentNode; for (var i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); subnode.__data__ = node.__data__; } else { subgroup.push(null); } } } return d3_selection(subgroups); }; d3_selection_enterPrototype.insert = function(name, before) { if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); return d3_selectionPrototype.insert.call(this, name, before); }; function d3_selection_enterInsertBefore(enter) { var i0, j0; return function(d, i, j) { var group = enter[j].update, n = group.length, node; if (j != j0) j0 = j, i0 = 0; if (i >= i0) i0 = i + 1; while (!(node = group[i0]) && ++i0 < n) ; return node; }; } d3.select = function(node) { var group; if (typeof node === "string") { group = [ d3_select(node, d3_document) ]; group.parentNode = d3_document.documentElement; } else { group = [ node ]; group.parentNode = d3_documentElement(node); } return d3_selection([ group ]); }; d3.selectAll = function(nodes) { var group; if (typeof nodes === "string") { group = d3_array(d3_selectAll(nodes, d3_document)); group.parentNode = d3_document.documentElement; } else { group = d3_array(nodes); group.parentNode = null; } return d3_selection([ group ]); }; d3_selectionPrototype.on = function(type, listener, capture) { var n = arguments.length; if (n < 3) { if (typeof type !== "string") { if (n < 2) listener = false; for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); return this; } if (n < 2) return (n = this.node()["__on" + type]) && n._; capture = false; } return this.each(d3_selection_on(type, listener, capture)); }; function d3_selection_on(type, listener, capture) { var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; if (i > 0) type = type.slice(0, i); var filter = d3_selection_onFilters.get(type); if (filter) type = filter, wrap = d3_selection_onFilter; function onRemove() { var l = this[name]; if (l) { this.removeEventListener(type, l, l.$); delete this[name]; } } function onAdd() { var l = wrap(listener, d3_array(arguments)); onRemove.call(this); this.addEventListener(type, this[name] = l, l.$ = capture); l._ = listener; } function removeAll() { var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; for (var name in this) { if (match = name.match(re)) { var l = this[name]; this.removeEventListener(match[1], l, l.$); delete this[name]; } } } return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; } var d3_selection_onFilters = d3.map({ mouseenter: "mouseover", mouseleave: "mouseout" }); if (d3_document) { d3_selection_onFilters.forEach(function(k) { if ("on" + k in d3_document) d3_selection_onFilters.remove(k); }); } function d3_selection_onListener(listener, argumentz) { return function(e) { var o = d3.event; d3.event = e; argumentz[0] = this.__data__; try { listener.apply(this, argumentz); } finally { d3.event = o; } }; } function d3_selection_onFilter(listener, argumentz) { var l = d3_selection_onListener(listener, argumentz); return function(e) { var target = this, related = e.relatedTarget; if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { l.call(target, e); } }; } var d3_event_dragSelect, d3_event_dragId = 0; function d3_event_dragSuppress(node) { var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); if (d3_event_dragSelect == null) { d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); } if (d3_event_dragSelect) { var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; style[d3_event_dragSelect] = "none"; } return function(suppressClick) { w.on(name, null); if (d3_event_dragSelect) style[d3_event_dragSelect] = select; if (suppressClick) { var off = function() { w.on(click, null); }; w.on(click, function() { d3_eventPreventDefault(); off(); }, true); setTimeout(off, 0); } }; } d3.mouse = function(container) { return d3_mousePoint(container, d3_eventSource()); }; var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; function d3_mousePoint(container, e) { if (e.changedTouches) e = e.changedTouches[0]; var svg = container.ownerSVGElement || container; if (svg.createSVGPoint) { var point = svg.createSVGPoint(); if (d3_mouse_bug44083 < 0) { var window = d3_window(container); if (window.scrollX || window.scrollY) { svg = d3.select("body").append("svg").style({ position: "absolute", top: 0, left: 0, margin: 0, padding: 0, border: "none" }, "important"); var ctm = svg[0][0].getScreenCTM(); d3_mouse_bug44083 = !(ctm.f || ctm.e); svg.remove(); } } if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, point.y = e.clientY; point = point.matrixTransform(container.getScreenCTM().inverse()); return [ point.x, point.y ]; } var rect = container.getBoundingClientRect(); return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; } d3.touch = function(container, touches, identifier) { if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { if ((touch = touches[i]).identifier === identifier) { return d3_mousePoint(container, touch); } } }; d3.behavior.drag = function() { var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); function drag() { this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); } function dragstart(id, position, subject, move, end) { return function() { var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); if (origin) { dragOffset = origin.apply(that, arguments); dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; } else { dragOffset = [ 0, 0 ]; } dispatch({ type: "dragstart" }); function moved() { var position1 = position(parent, dragId), dx, dy; if (!position1) return; dx = position1[0] - position0[0]; dy = position1[1] - position0[1]; dragged |= dx | dy; position0 = position1; dispatch({ type: "drag", x: position1[0] + dragOffset[0], y: position1[1] + dragOffset[1], dx: dx, dy: dy }); } function ended() { if (!position(parent, dragId)) return; dragSubject.on(move + dragName, null).on(end + dragName, null); dragRestore(dragged); dispatch({ type: "dragend" }); } }; } drag.origin = function(x) { if (!arguments.length) return origin; origin = x; return drag; }; return d3.rebind(drag, event, "on"); }; function d3_behavior_dragTouchId() { return d3.event.changedTouches[0].identifier; } d3.touches = function(container, touches) { if (arguments.length < 2) touches = d3_eventSource().touches; return touches ? d3_array(touches).map(function(touch) { var point = d3_mousePoint(container, touch); point.identifier = touch.identifier; return point; }) : []; }; var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; function d3_sgn(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } function d3_cross2d(a, b, c) { return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); } function d3_acos(x) { return x > 1 ? 0 : x < -1 ? π : Math.acos(x); } function d3_asin(x) { return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); } function d3_sinh(x) { return ((x = Math.exp(x)) - 1 / x) / 2; } function d3_cosh(x) { return ((x = Math.exp(x)) + 1 / x) / 2; } function d3_tanh(x) { return ((x = Math.exp(2 * x)) - 1) / (x + 1); } function d3_haversin(x) { return (x = Math.sin(x / 2)) * x; } var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; d3.interpolateZoom = function(p0, p1) { var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; if (d2 < ε2) { S = Math.log(w1 / w0) / ρ; i = function(t) { return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; }; } else { var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); S = (r1 - r0) / ρ; i = function(t) { var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; }; } i.duration = S * 1e3; return i; }; d3.behavior.zoom = function() { var view = { x: 0, y: 0, k: 1 }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; if (!d3_behavior_zoomWheel) { d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { return d3.event.wheelDelta; }, "mousewheel") : (d3_behavior_zoomDelta = function() { return -d3.event.detail; }, "MozMousePixelScroll"); } function zoom(g) { g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); } zoom.event = function(g) { g.each(function() { var dispatch = event.of(this, arguments), view1 = view; if (d3_transitionInheritId) { d3.select(this).transition().each("start.zoom", function() { view = this.__chart__ || { x: 0, y: 0, k: 1 }; zoomstarted(dispatch); }).tween("zoom:zoom", function() { var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); return function(t) { var l = i(t), k = dx / l[2]; this.__chart__ = view = { x: cx - l[0] * k, y: cy - l[1] * k, k: k }; zoomed(dispatch); }; }).each("interrupt.zoom", function() { zoomended(dispatch); }).each("end.zoom", function() { zoomended(dispatch); }); } else { this.__chart__ = view; zoomstarted(dispatch); zoomed(dispatch); zoomended(dispatch); } }); }; zoom.translate = function(_) { if (!arguments.length) return [ view.x, view.y ]; view = { x: +_[0], y: +_[1], k: view.k }; rescale(); return zoom; }; zoom.scale = function(_) { if (!arguments.length) return view.k; view = { x: view.x, y: view.y, k: null }; scaleTo(+_); rescale(); return zoom; }; zoom.scaleExtent = function(_) { if (!arguments.length) return scaleExtent; scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; return zoom; }; zoom.center = function(_) { if (!arguments.length) return center; center = _ && [ +_[0], +_[1] ]; return zoom; }; zoom.size = function(_) { if (!arguments.length) return size; size = _ && [ +_[0], +_[1] ]; return zoom; }; zoom.duration = function(_) { if (!arguments.length) return duration; duration = +_; return zoom; }; zoom.x = function(z) { if (!arguments.length) return x1; x1 = z; x0 = z.copy(); view = { x: 0, y: 0, k: 1 }; return zoom; }; zoom.y = function(z) { if (!arguments.length) return y1; y1 = z; y0 = z.copy(); view = { x: 0, y: 0, k: 1 }; return zoom; }; function location(p) { return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; } function point(l) { return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; } function scaleTo(s) { view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); } function translateTo(p, l) { l = point(l); view.x += p[0] - l[0]; view.y += p[1] - l[1]; } function zoomTo(that, p, l, k) { that.__chart__ = { x: view.x, y: view.y, k: view.k }; scaleTo(Math.pow(2, k)); translateTo(center0 = p, l); that = d3.select(that); if (duration > 0) that = that.transition().duration(duration); that.call(zoom.event); } function rescale() { if (x1) x1.domain(x0.range().map(function(x) { return (x - view.x) / view.k; }).map(x0.invert)); if (y1) y1.domain(y0.range().map(function(y) { return (y - view.y) / view.k; }).map(y0.invert)); } function zoomstarted(dispatch) { if (!zooming++) dispatch({ type: "zoomstart" }); } function zoomed(dispatch) { rescale(); dispatch({ type: "zoom", scale: view.k, translate: [ view.x, view.y ] }); } function zoomended(dispatch) { if (!--zooming) dispatch({ type: "zoomend" }), center0 = null; } function mousedowned() { var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); d3_selection_interrupt.call(that); zoomstarted(dispatch); function moved() { dragged = 1; translateTo(d3.mouse(that), location0); zoomed(dispatch); } function ended() { subject.on(mousemove, null).on(mouseup, null); dragRestore(dragged); zoomended(dispatch); } } function touchstarted() { var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); started(); zoomstarted(dispatch); subject.on(mousedown, null).on(touchstart, started); function relocate() { var touches = d3.touches(that); scale0 = view.k; touches.forEach(function(t) { if (t.identifier in locations0) locations0[t.identifier] = location(t); }); return touches; } function started() { var target = d3.event.target; d3.select(target).on(touchmove, moved).on(touchend, ended); targets.push(target); var changed = d3.event.changedTouches; for (var i = 0, n = changed.length; i < n; ++i) { locations0[changed[i].identifier] = null; } var touches = relocate(), now = Date.now(); if (touches.length === 1) { if (now - touchtime < 500) { var p = touches[0]; zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); d3_eventPreventDefault(); } touchtime = now; } else if (touches.length > 1) { var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; distance0 = dx * dx + dy * dy; } } function moved() { var touches = d3.touches(that), p0, l0, p1, l1; d3_selection_interrupt.call(that); for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { p1 = touches[i]; if (l1 = locations0[p1.identifier]) { if (l0) break; p0 = p1, l0 = l1; } } if (l1) { var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; scaleTo(scale1 * scale0); } touchtime = null; translateTo(p0, l0); zoomed(dispatch); } function ended() { if (d3.event.touches.length) { var changed = d3.event.changedTouches; for (var i = 0, n = changed.length; i < n; ++i) { delete locations0[changed[i].identifier]; } for (var identifier in locations0) { return void relocate(); } } d3.selectAll(targets).on(zoomName, null); subject.on(mousedown, mousedowned).on(touchstart, touchstarted); dragRestore(); zoomended(dispatch); } } function mousewheeled() { var dispatch = event.of(this, arguments); if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch); mousewheelTimer = setTimeout(function() { mousewheelTimer = null; zoomended(dispatch); }, 50); d3_eventPreventDefault(); scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); translateTo(center0, translate0); zoomed(dispatch); } function dblclicked() { var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); } return d3.rebind(zoom, event, "on"); }; var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; d3.color = d3_color; function d3_color() {} d3_color.prototype.toString = function() { return this.rgb() + ""; }; d3.hsl = d3_hsl; function d3_hsl(h, s, l) { return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); } var d3_hslPrototype = d3_hsl.prototype = new d3_color(); d3_hslPrototype.brighter = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_hsl(this.h, this.s, this.l / k); }; d3_hslPrototype.darker = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_hsl(this.h, this.s, k * this.l); }; d3_hslPrototype.rgb = function() { return d3_hsl_rgb(this.h, this.s, this.l); }; function d3_hsl_rgb(h, s, l) { var m1, m2; h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; l = l < 0 ? 0 : l > 1 ? 1 : l; m2 = l <= .5 ? l * (1 + s) : l + s - l * s; m1 = 2 * l - m2; function v(h) { if (h > 360) h -= 360; else if (h < 0) h += 360; if (h < 60) return m1 + (m2 - m1) * h / 60; if (h < 180) return m2; if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; return m1; } function vv(h) { return Math.round(v(h) * 255); } return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); } d3.hcl = d3_hcl; function d3_hcl(h, c, l) { return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); } var d3_hclPrototype = d3_hcl.prototype = new d3_color(); d3_hclPrototype.brighter = function(k) { return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); }; d3_hclPrototype.darker = function(k) { return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); }; d3_hclPrototype.rgb = function() { return d3_hcl_lab(this.h, this.c, this.l).rgb(); }; function d3_hcl_lab(h, c, l) { if (isNaN(h)) h = 0; if (isNaN(c)) c = 0; return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); } d3.lab = d3_lab; function d3_lab(l, a, b) { return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); } var d3_lab_K = 18; var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; var d3_labPrototype = d3_lab.prototype = new d3_color(); d3_labPrototype.brighter = function(k) { return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); }; d3_labPrototype.darker = function(k) { return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); }; d3_labPrototype.rgb = function() { return d3_lab_rgb(this.l, this.a, this.b); }; function d3_lab_rgb(l, a, b) { var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; x = d3_lab_xyz(x) * d3_lab_X; y = d3_lab_xyz(y) * d3_lab_Y; z = d3_lab_xyz(z) * d3_lab_Z; return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); } function d3_lab_hcl(l, a, b) { return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); } function d3_lab_xyz(x) { return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; } function d3_xyz_lab(x) { return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; } function d3_xyz_rgb(r) { return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); } d3.rgb = d3_rgb; function d3_rgb(r, g, b) { return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); } function d3_rgbNumber(value) { return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); } function d3_rgbString(value) { return d3_rgbNumber(value) + ""; } var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); d3_rgbPrototype.brighter = function(k) { k = Math.pow(.7, arguments.length ? k : 1); var r = this.r, g = this.g, b = this.b, i = 30; if (!r && !g && !b) return new d3_rgb(i, i, i); if (r && r < i) r = i; if (g && g < i) g = i; if (b && b < i) b = i; return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); }; d3_rgbPrototype.darker = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_rgb(k * this.r, k * this.g, k * this.b); }; d3_rgbPrototype.hsl = function() { return d3_rgb_hsl(this.r, this.g, this.b); }; d3_rgbPrototype.toString = function() { return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); }; function d3_rgb_hex(v) { return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); } function d3_rgb_parse(format, rgb, hsl) { var r = 0, g = 0, b = 0, m1, m2, color; m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase()); if (m1) { m2 = m1[2].split(","); switch (m1[1]) { case "hsl": { return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); } case "rgb": { return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); } } } if (color = d3_rgb_names.get(format)) { return rgb(color.r, color.g, color.b); } if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { if (format.length === 4) { r = (color & 3840) >> 4; r = r >> 4 | r; g = color & 240; g = g >> 4 | g; b = color & 15; b = b << 4 | b; } else if (format.length === 7) { r = (color & 16711680) >> 16; g = (color & 65280) >> 8; b = color & 255; } } return rgb(r, g, b); } function d3_rgb_hsl(r, g, b) { var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; if (d) { s = l < .5 ? d / (max + min) : d / (2 - max - min); if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; h *= 60; } else { h = NaN; s = l > 0 && l < 1 ? 0 : h; } return new d3_hsl(h, s, l); } function d3_rgb_lab(r, g, b) { r = d3_rgb_xyz(r); g = d3_rgb_xyz(g); b = d3_rgb_xyz(b); var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); } function d3_rgb_xyz(r) { return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); } function d3_rgb_parseNumber(c) { var f = parseFloat(c); return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; } var d3_rgb_names = d3.map({ aliceblue: 15792383, antiquewhite: 16444375, aqua: 65535, aquamarine: 8388564, azure: 15794175, beige: 16119260, bisque: 16770244, black: 0, blanchedalmond: 16772045, blue: 255, blueviolet: 9055202, brown: 10824234, burlywood: 14596231, cadetblue: 6266528, chartreuse: 8388352, chocolate: 13789470, coral: 16744272, cornflowerblue: 6591981, cornsilk: 16775388, crimson: 14423100, cyan: 65535, darkblue: 139, darkcyan: 35723, darkgoldenrod: 12092939, darkgray: 11119017, darkgreen: 25600, darkgrey: 11119017, darkkhaki: 12433259, darkmagenta: 9109643, darkolivegreen: 5597999, darkorange: 16747520, darkorchid: 10040012, darkred: 9109504, darksalmon: 15308410, darkseagreen: 9419919, darkslateblue: 4734347, darkslategray: 3100495, darkslategrey: 3100495, darkturquoise: 52945, darkviolet: 9699539, deeppink: 16716947, deepskyblue: 49151, dimgray: 6908265, dimgrey: 6908265, dodgerblue: 2003199, firebrick: 11674146, floralwhite: 16775920, forestgreen: 2263842, fuchsia: 16711935, gainsboro: 14474460, ghostwhite: 16316671, gold: 16766720, goldenrod: 14329120, gray: 8421504, green: 32768, greenyellow: 11403055, grey: 8421504, honeydew: 15794160, hotpink: 16738740, indianred: 13458524, indigo: 4915330, ivory: 16777200, khaki: 15787660, lavender: 15132410, lavenderblush: 16773365, lawngreen: 8190976, lemonchiffon: 16775885, lightblue: 11393254, lightcoral: 15761536, lightcyan: 14745599, lightgoldenrodyellow: 16448210, lightgray: 13882323, lightgreen: 9498256, lightgrey: 13882323, lightpink: 16758465, lightsalmon: 16752762, lightseagreen: 2142890, lightskyblue: 8900346, lightslategray: 7833753, lightslategrey: 7833753, lightsteelblue: 11584734, lightyellow: 16777184, lime: 65280, limegreen: 3329330, linen: 16445670, magenta: 16711935, maroon: 8388608, mediumaquamarine: 6737322, mediumblue: 205, mediumorchid: 12211667, mediumpurple: 9662683, mediumseagreen: 3978097, mediumslateblue: 8087790, mediumspringgreen: 64154, mediumturquoise: 4772300, mediumvioletred: 13047173, midnightblue: 1644912, mintcream: 16121850, mistyrose: 16770273, moccasin: 16770229, navajowhite: 16768685, navy: 128, oldlace: 16643558, olive: 8421376, olivedrab: 7048739, orange: 16753920, orangered: 16729344, orchid: 14315734, palegoldenrod: 15657130, palegreen: 10025880, paleturquoise: 11529966, palevioletred: 14381203, papayawhip: 16773077, peachpuff: 16767673, peru: 13468991, pink: 16761035, plum: 14524637, powderblue: 11591910, purple: 8388736, rebeccapurple: 6697881, red: 16711680, rosybrown: 12357519, royalblue: 4286945, saddlebrown: 9127187, salmon: 16416882, sandybrown: 16032864, seagreen: 3050327, seashell: 16774638, sienna: 10506797, silver: 12632256, skyblue: 8900331, slateblue: 6970061, slategray: 7372944, slategrey: 7372944, snow: 16775930, springgreen: 65407, steelblue: 4620980, tan: 13808780, teal: 32896, thistle: 14204888, tomato: 16737095, turquoise: 4251856, violet: 15631086, wheat: 16113331, white: 16777215, whitesmoke: 16119285, yellow: 16776960, yellowgreen: 10145074 }); d3_rgb_names.forEach(function(key, value) { d3_rgb_names.set(key, d3_rgbNumber(value)); }); function d3_functor(v) { return typeof v === "function" ? v : function() { return v; }; } d3.functor = d3_functor; d3.xhr = d3_xhrType(d3_identity); function d3_xhrType(response) { return function(url, mimeType, callback) { if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, mimeType = null; return d3_xhr(url, mimeType, response, callback); }; } function d3_xhr(url, mimeType, response, callback) { var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { request.readyState > 3 && respond(); }; function respond() { var status = request.status, result; if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { try { result = response.call(xhr, request); } catch (e) { dispatch.error.call(xhr, e); return; } dispatch.load.call(xhr, result); } else { dispatch.error.call(xhr, request); } } request.onprogress = function(event) { var o = d3.event; d3.event = event; try { dispatch.progress.call(xhr, request); } finally { d3.event = o; } }; xhr.header = function(name, value) { name = (name + "").toLowerCase(); if (arguments.length < 2) return headers[name]; if (value == null) delete headers[name]; else headers[name] = value + ""; return xhr; }; xhr.mimeType = function(value) { if (!arguments.length) return mimeType; mimeType = value == null ? null : value + ""; return xhr; }; xhr.responseType = function(value) { if (!arguments.length) return responseType; responseType = value; return xhr; }; xhr.response = function(value) { response = value; return xhr; }; [ "get", "post" ].forEach(function(method) { xhr[method] = function() { return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); }; }); xhr.send = function(method, data, callback) { if (arguments.length === 2 && typeof data === "function") callback = data, data = null; request.open(method, url, true); if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); if (responseType != null) request.responseType = responseType; if (callback != null) xhr.on("error", callback).on("load", function(request) { callback(null, request); }); dispatch.beforesend.call(xhr, request); request.send(data == null ? null : data); return xhr; }; xhr.abort = function() { request.abort(); return xhr; }; d3.rebind(xhr, dispatch, "on"); return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); } function d3_xhr_fixCallback(callback) { return callback.length === 1 ? function(error, request) { callback(error == null ? request : null); } : callback; } function d3_xhrHasResponse(request) { var type = request.responseType; return type && type !== "text" ? request.response : request.responseText; } d3.dsv = function(delimiter, mimeType) { var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); function dsv(url, row, callback) { if (arguments.length < 3) callback = row, row = null; var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); xhr.row = function(_) { return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; }; return xhr; } function response(request) { return dsv.parse(request.responseText); } function typedResponse(f) { return function(request) { return dsv.parse(request.responseText, f); }; } dsv.parse = function(text, f) { var o; return dsv.parseRows(text, function(row, i) { if (o) return o(row, i - 1); var a = new Function("d", "return {" + row.map(function(name, i) { return JSON.stringify(name) + ": d[" + i + "]"; }).join(",") + "}"); o = f ? function(row, i) { return f(a(row), i); } : a; }); }; dsv.parseRows = function(text, f) { var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; function token() { if (I >= N) return EOF; if (eol) return eol = false, EOL; var j = I; if (text.charCodeAt(j) === 34) { var i = j; while (i++ < N) { if (text.charCodeAt(i) === 34) { if (text.charCodeAt(i + 1) !== 34) break; ++i; } } I = i + 2; var c = text.charCodeAt(i + 1); if (c === 13) { eol = true; if (text.charCodeAt(i + 2) === 10) ++I; } else if (c === 10) { eol = true; } return text.slice(j + 1, i).replace(/""/g, '"'); } while (I < N) { var c = text.charCodeAt(I++), k = 1; if (c === 10) eol = true; else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } else if (c !== delimiterCode) continue; return text.slice(j, I - k); } return text.slice(j); } while ((t = token()) !== EOF) { var a = []; while (t !== EOL && t !== EOF) { a.push(t); t = token(); } if (f && (a = f(a, n++)) == null) continue; rows.push(a); } return rows; }; dsv.format = function(rows) { if (Array.isArray(rows[0])) return dsv.formatRows(rows); var fieldSet = new d3_Set(), fields = []; rows.forEach(function(row) { for (var field in row) { if (!fieldSet.has(field)) { fields.push(fieldSet.add(field)); } } }); return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { return fields.map(function(field) { return formatValue(row[field]); }).join(delimiter); })).join("\n"); }; dsv.formatRows = function(rows) { return rows.map(formatRow).join("\n"); }; function formatRow(row) { return row.map(formatValue).join(delimiter); } function formatValue(text) { return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; } return dsv; }; d3.csv = d3.dsv(",", "text/csv"); d3.tsv = d3.dsv(" ", "text/tab-separated-values"); var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { setTimeout(callback, 17); }; d3.timer = function() { d3_timer.apply(this, arguments); }; function d3_timer(callback, delay, then) { var n = arguments.length; if (n < 2) delay = 0; if (n < 3) then = Date.now(); var time = then + delay, timer = { c: callback, t: time, n: null }; if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; d3_timer_queueTail = timer; if (!d3_timer_interval) { d3_timer_timeout = clearTimeout(d3_timer_timeout); d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } return timer; } function d3_timer_step() { var now = d3_timer_mark(), delay = d3_timer_sweep() - now; if (delay > 24) { if (isFinite(delay)) { clearTimeout(d3_timer_timeout); d3_timer_timeout = setTimeout(d3_timer_step, delay); } d3_timer_interval = 0; } else { d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } } d3.timer.flush = function() { d3_timer_mark(); d3_timer_sweep(); }; function d3_timer_mark() { var now = Date.now(), timer = d3_timer_queueHead; while (timer) { if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; timer = timer.n; } return now; } function d3_timer_sweep() { var t0, t1 = d3_timer_queueHead, time = Infinity; while (t1) { if (t1.c) { if (t1.t < time) time = t1.t; t1 = (t0 = t1).n; } else { t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; } } d3_timer_queueTail = t0; return time; } function d3_format_precision(x, p) { return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); } d3.round = function(x, n) { return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); }; var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); d3.formatPrefix = function(value, precision) { var i = 0; if (value = +value) { if (value < 0) value *= -1; if (precision) value = d3.round(value, d3_format_precision(value, precision)); i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); } return d3_formatPrefixes[8 + i / 3]; }; function d3_formatPrefix(d, i) { var k = Math.pow(10, abs(8 - i) * 3); return { scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; }, symbol: d }; } function d3_locale_numberFormat(locale) { var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; while (i > 0 && g > 0) { if (length + g + 1 > width) g = Math.max(1, width - length); t.push(value.substring(i -= g, i + g)); if ((length += g + 1) > width) break; g = locale_grouping[j = (j + 1) % locale_grouping.length]; } return t.reverse().join(locale_thousands); } : d3_identity; return function(specifier) { var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; if (precision) precision = +precision.substring(1); if (zfill || fill === "0" && align === "=") { zfill = fill = "0"; align = "="; } switch (type) { case "n": comma = true; type = "g"; break; case "%": scale = 100; suffix = "%"; type = "f"; break; case "p": scale = 100; suffix = "%"; type = "r"; break; case "b": case "o": case "x": case "X": if (symbol === "#") prefix = "0" + type.toLowerCase(); case "c": exponent = false; case "d": integer = true; precision = 0; break; case "s": scale = -1; type = "r"; break; } if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; if (type == "r" && !precision) type = "g"; if (precision != null) { if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); } type = d3_format_types.get(type) || d3_format_typeDefault; var zcomma = zfill && comma; return function(value) { var fullSuffix = suffix; if (integer && value % 1) return ""; var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; if (scale < 0) { var unit = d3.formatPrefix(value, precision); value = unit.scale(value); fullSuffix = unit.symbol + suffix; } else { value *= scale; } value = type(value, precision); var i = value.lastIndexOf("."), before, after; if (i < 0) { var j = exponent ? value.lastIndexOf("e") : -1; if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); } else { before = value.substring(0, i); after = locale_decimal + value.substring(i + 1); } if (!zfill && comma) before = formatGroup(before, Infinity); var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); negative += prefix; value = before + after; return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; }; }; } var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; var d3_format_types = d3.map({ b: function(x) { return x.toString(2); }, c: function(x) { return String.fromCharCode(x); }, o: function(x) { return x.toString(8); }, x: function(x) { return x.toString(16); }, X: function(x) { return x.toString(16).toUpperCase(); }, g: function(x, p) { return x.toPrecision(p); }, e: function(x, p) { return x.toExponential(p); }, f: function(x, p) { return x.toFixed(p); }, r: function(x, p) { return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); } }); function d3_format_typeDefault(x) { return x + ""; } var d3_time = d3.time = {}, d3_date = Date; function d3_date_utc() { this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); } d3_date_utc.prototype = { getDate: function() { return this._.getUTCDate(); }, getDay: function() { return this._.getUTCDay(); }, getFullYear: function() { return this._.getUTCFullYear(); }, getHours: function() { return this._.getUTCHours(); }, getMilliseconds: function() { return this._.getUTCMilliseconds(); }, getMinutes: function() { return this._.getUTCMinutes(); }, getMonth: function() { return this._.getUTCMonth(); }, getSeconds: function() { return this._.getUTCSeconds(); }, getTime: function() { return this._.getTime(); }, getTimezoneOffset: function() { return 0; }, valueOf: function() { return this._.valueOf(); }, setDate: function() { d3_time_prototype.setUTCDate.apply(this._, arguments); }, setDay: function() { d3_time_prototype.setUTCDay.apply(this._, arguments); }, setFullYear: function() { d3_time_prototype.setUTCFullYear.apply(this._, arguments); }, setHours: function() { d3_time_prototype.setUTCHours.apply(this._, arguments); }, setMilliseconds: function() { d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); }, setMinutes: function() { d3_time_prototype.setUTCMinutes.apply(this._, arguments); }, setMonth: function() { d3_time_prototype.setUTCMonth.apply(this._, arguments); }, setSeconds: function() { d3_time_prototype.setUTCSeconds.apply(this._, arguments); }, setTime: function() { d3_time_prototype.setTime.apply(this._, arguments); } }; var d3_time_prototype = Date.prototype; function d3_time_interval(local, step, number) { function round(date) { var d0 = local(date), d1 = offset(d0, 1); return date - d0 < d1 - date ? d0 : d1; } function ceil(date) { step(date = local(new d3_date(date - 1)), 1); return date; } function offset(date, k) { step(date = new d3_date(+date), k); return date; } function range(t0, t1, dt) { var time = ceil(t0), times = []; if (dt > 1) { while (time < t1) { if (!(number(time) % dt)) times.push(new Date(+time)); step(time, 1); } } else { while (time < t1) times.push(new Date(+time)), step(time, 1); } return times; } function range_utc(t0, t1, dt) { try { d3_date = d3_date_utc; var utc = new d3_date_utc(); utc._ = t0; return range(utc, t1, dt); } finally { d3_date = Date; } } local.floor = local; local.round = round; local.ceil = ceil; local.offset = offset; local.range = range; var utc = local.utc = d3_time_interval_utc(local); utc.floor = utc; utc.round = d3_time_interval_utc(round); utc.ceil = d3_time_interval_utc(ceil); utc.offset = d3_time_interval_utc(offset); utc.range = range_utc; return local; } function d3_time_interval_utc(method) { return function(date, k) { try { d3_date = d3_date_utc; var utc = new d3_date_utc(); utc._ = date; return method(utc, k)._; } finally { d3_date = Date; } }; } d3_time.year = d3_time_interval(function(date) { date = d3_time.day(date); date.setMonth(0, 1); return date; }, function(date, offset) { date.setFullYear(date.getFullYear() + offset); }, function(date) { return date.getFullYear(); }); d3_time.years = d3_time.year.range; d3_time.years.utc = d3_time.year.utc.range; d3_time.day = d3_time_interval(function(date) { var day = new d3_date(2e3, 0); day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); return day; }, function(date, offset) { date.setDate(date.getDate() + offset); }, function(date) { return date.getDate() - 1; }); d3_time.days = d3_time.day.range; d3_time.days.utc = d3_time.day.utc.range; d3_time.dayOfYear = function(date) { var year = d3_time.year(date); return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); }; [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { i = 7 - i; var interval = d3_time[day] = d3_time_interval(function(date) { (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); return date; }, function(date, offset) { date.setDate(date.getDate() + Math.floor(offset) * 7); }, function(date) { var day = d3_time.year(date).getDay(); return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); }); d3_time[day + "s"] = interval.range; d3_time[day + "s"].utc = interval.utc.range; d3_time[day + "OfYear"] = function(date) { var day = d3_time.year(date).getDay(); return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); }; }); d3_time.week = d3_time.sunday; d3_time.weeks = d3_time.sunday.range; d3_time.weeks.utc = d3_time.sunday.utc.range; d3_time.weekOfYear = d3_time.sundayOfYear; function d3_locale_timeFormat(locale) { var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; function d3_time_format(template) { var n = template.length; function format(date) { var string = [], i = -1, j = 0, c, p, f; while (++i < n) { if (template.charCodeAt(i) === 37) { string.push(template.slice(j, i)); if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); string.push(c); j = i + 1; } } string.push(template.slice(j, i)); return string.join(""); } format.parse = function(string) { var d = { y: 1900, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0, Z: null }, i = d3_time_parse(d, template, string, 0); if (i != string.length) return null; if ("p" in d) d.H = d.H % 12 + d.p * 12; var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) { if (!("w" in d)) d.w = "W" in d ? 1 : 0; date.setFullYear(d.y, 0, 1); date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); } else date.setFullYear(d.y, d.m, d.d); date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); return localZ ? date._ : date; }; format.toString = function() { return template; }; return format; } function d3_time_parse(date, template, string, j) { var c, p, t, i = 0, n = template.length, m = string.length; while (i < n) { if (j >= m) return -1; c = template.charCodeAt(i++); if (c === 37) { t = template.charAt(i++); p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; if (!p || (j = p(date, string, j)) < 0) return -1; } else if (c != string.charCodeAt(j++)) { return -1; } } return j; } d3_time_format.utc = function(template) { var local = d3_time_format(template); function format(date) { try { d3_date = d3_date_utc; var utc = new d3_date(); utc._ = date; return local(utc); } finally { d3_date = Date; } } format.parse = function(string) { try { d3_date = d3_date_utc; var date = local.parse(string); return date && date._; } finally { d3_date = Date; } }; format.toString = local.toString; return format; }; d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); locale_periods.forEach(function(p, i) { d3_time_periodLookup.set(p.toLowerCase(), i); }); var d3_time_formats = { a: function(d) { return locale_shortDays[d.getDay()]; }, A: function(d) { return locale_days[d.getDay()]; }, b: function(d) { return locale_shortMonths[d.getMonth()]; }, B: function(d) { return locale_months[d.getMonth()]; }, c: d3_time_format(locale_dateTime), d: function(d, p) { return d3_time_formatPad(d.getDate(), p, 2); }, e: function(d, p) { return d3_time_formatPad(d.getDate(), p, 2); }, H: function(d, p) { return d3_time_formatPad(d.getHours(), p, 2); }, I: function(d, p) { return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); }, j: function(d, p) { return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); }, L: function(d, p) { return d3_time_formatPad(d.getMilliseconds(), p, 3); }, m: function(d, p) { return d3_time_formatPad(d.getMonth() + 1, p, 2); }, M: function(d, p) { return d3_time_formatPad(d.getMinutes(), p, 2); }, p: function(d) { return locale_periods[+(d.getHours() >= 12)]; }, S: function(d, p) { return d3_time_formatPad(d.getSeconds(), p, 2); }, U: function(d, p) { return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); }, w: function(d) { return d.getDay(); }, W: function(d, p) { return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); }, x: d3_time_format(locale_date), X: d3_time_format(locale_time), y: function(d, p) { return d3_time_formatPad(d.getFullYear() % 100, p, 2); }, Y: function(d, p) { return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); }, Z: d3_time_zone, "%": function() { return "%"; } }; var d3_time_parsers = { a: d3_time_parseWeekdayAbbrev, A: d3_time_parseWeekday, b: d3_time_parseMonthAbbrev, B: d3_time_parseMonth, c: d3_time_parseLocaleFull, d: d3_time_parseDay, e: d3_time_parseDay, H: d3_time_parseHour24, I: d3_time_parseHour24, j: d3_time_parseDayOfYear, L: d3_time_parseMilliseconds, m: d3_time_parseMonthNumber, M: d3_time_parseMinutes, p: d3_time_parseAmPm, S: d3_time_parseSeconds, U: d3_time_parseWeekNumberSunday, w: d3_time_parseWeekdayNumber, W: d3_time_parseWeekNumberMonday, x: d3_time_parseLocaleDate, X: d3_time_parseLocaleTime, y: d3_time_parseYear, Y: d3_time_parseFullYear, Z: d3_time_parseZone, "%": d3_time_parseLiteralPercent }; function d3_time_parseWeekdayAbbrev(date, string, i) { d3_time_dayAbbrevRe.lastIndex = 0; var n = d3_time_dayAbbrevRe.exec(string.slice(i)); return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseWeekday(date, string, i) { d3_time_dayRe.lastIndex = 0; var n = d3_time_dayRe.exec(string.slice(i)); return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseMonthAbbrev(date, string, i) { d3_time_monthAbbrevRe.lastIndex = 0; var n = d3_time_monthAbbrevRe.exec(string.slice(i)); return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseMonth(date, string, i) { d3_time_monthRe.lastIndex = 0; var n = d3_time_monthRe.exec(string.slice(i)); return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseLocaleFull(date, string, i) { return d3_time_parse(date, d3_time_formats.c.toString(), string, i); } function d3_time_parseLocaleDate(date, string, i) { return d3_time_parse(date, d3_time_formats.x.toString(), string, i); } function d3_time_parseLocaleTime(date, string, i) { return d3_time_parse(date, d3_time_formats.X.toString(), string, i); } function d3_time_parseAmPm(date, string, i) { var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); return n == null ? -1 : (date.p = n, i); } return d3_time_format; } var d3_time_formatPads = { "-": "", _: " ", "0": "0" }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; function d3_time_formatPad(value, fill, width) { var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); } function d3_time_formatRe(names) { return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); } function d3_time_formatLookup(names) { var map = new d3_Map(), i = -1, n = names.length; while (++i < n) map.set(names[i].toLowerCase(), i); return map; } function d3_time_parseWeekdayNumber(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 1)); return n ? (date.w = +n[0], i + n[0].length) : -1; } function d3_time_parseWeekNumberSunday(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i)); return n ? (date.U = +n[0], i + n[0].length) : -1; } function d3_time_parseWeekNumberMonday(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i)); return n ? (date.W = +n[0], i + n[0].length) : -1; } function d3_time_parseFullYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 4)); return n ? (date.y = +n[0], i + n[0].length) : -1; } function d3_time_parseYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; } function d3_time_parseZone(date, string, i) { return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, i + 5) : -1; } function d3_time_expandYear(d) { return d + (d > 68 ? 1900 : 2e3); } function d3_time_parseMonthNumber(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.m = n[0] - 1, i + n[0].length) : -1; } function d3_time_parseDay(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.d = +n[0], i + n[0].length) : -1; } function d3_time_parseDayOfYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 3)); return n ? (date.j = +n[0], i + n[0].length) : -1; } function d3_time_parseHour24(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.H = +n[0], i + n[0].length) : -1; } function d3_time_parseMinutes(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.M = +n[0], i + n[0].length) : -1; } function d3_time_parseSeconds(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.S = +n[0], i + n[0].length) : -1; } function d3_time_parseMilliseconds(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 3)); return n ? (date.L = +n[0], i + n[0].length) : -1; } function d3_time_zone(d) { var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); } function d3_time_parseLiteralPercent(date, string, i) { d3_time_percentRe.lastIndex = 0; var n = d3_time_percentRe.exec(string.slice(i, i + 1)); return n ? i + n[0].length : -1; } function d3_time_formatMulti(formats) { var n = formats.length, i = -1; while (++i < n) formats[i][0] = this(formats[i][0]); return function(date) { var i = 0, f = formats[i]; while (!f[1](date)) f = formats[++i]; return f[0](date); }; } d3.locale = function(locale) { return { numberFormat: d3_locale_numberFormat(locale), timeFormat: d3_locale_timeFormat(locale) }; }; var d3_locale_enUS = d3.locale({ decimal: ".", thousands: ",", grouping: [ 3 ], currency: [ "$", "" ], dateTime: "%a %b %e %X %Y", date: "%m/%d/%Y", time: "%H:%M:%S", periods: [ "AM", "PM" ], days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }); d3.format = d3_locale_enUS.numberFormat; d3.geo = {}; function d3_adder() {} d3_adder.prototype = { s: 0, t: 0, add: function(y) { d3_adderSum(y, this.t, d3_adderTemp); d3_adderSum(d3_adderTemp.s, this.s, this); if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; }, reset: function() { this.s = this.t = 0; }, valueOf: function() { return this.s; } }; var d3_adderTemp = new d3_adder(); function d3_adderSum(a, b, o) { var x = o.s = a + b, bv = x - a, av = x - bv; o.t = a - av + (b - bv); } d3.geo.stream = function(object, listener) { if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { d3_geo_streamObjectType[object.type](object, listener); } else { d3_geo_streamGeometry(object, listener); } }; function d3_geo_streamGeometry(geometry, listener) { if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { d3_geo_streamGeometryType[geometry.type](geometry, listener); } } var d3_geo_streamObjectType = { Feature: function(feature, listener) { d3_geo_streamGeometry(feature.geometry, listener); }, FeatureCollection: function(object, listener) { var features = object.features, i = -1, n = features.length; while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); } }; var d3_geo_streamGeometryType = { Sphere: function(object, listener) { listener.sphere(); }, Point: function(object, listener) { object = object.coordinates; listener.point(object[0], object[1], object[2]); }, MultiPoint: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); }, LineString: function(object, listener) { d3_geo_streamLine(object.coordinates, listener, 0); }, MultiLineString: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); }, Polygon: function(object, listener) { d3_geo_streamPolygon(object.coordinates, listener); }, MultiPolygon: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); }, GeometryCollection: function(object, listener) { var geometries = object.geometries, i = -1, n = geometries.length; while (++i < n) d3_geo_streamGeometry(geometries[i], listener); } }; function d3_geo_streamLine(coordinates, listener, closed) { var i = -1, n = coordinates.length - closed, coordinate; listener.lineStart(); while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); listener.lineEnd(); } function d3_geo_streamPolygon(coordinates, listener) { var i = -1, n = coordinates.length; listener.polygonStart(); while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); listener.polygonEnd(); } d3.geo.area = function(object) { d3_geo_areaSum = 0; d3.geo.stream(object, d3_geo_area); return d3_geo_areaSum; }; var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); var d3_geo_area = { sphere: function() { d3_geo_areaSum += 4 * π; }, point: d3_noop, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: function() { d3_geo_areaRingSum.reset(); d3_geo_area.lineStart = d3_geo_areaRingStart; }, polygonEnd: function() { var area = 2 * d3_geo_areaRingSum; d3_geo_areaSum += area < 0 ? 4 * π + area : area; d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; } }; function d3_geo_areaRingStart() { var λ00, φ00, λ0, cosφ0, sinφ0; d3_geo_area.point = function(λ, φ) { d3_geo_area.point = nextPoint; λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), sinφ0 = Math.sin(φ); }; function nextPoint(λ, φ) { λ *= d3_radians; φ = φ * d3_radians / 2 + π / 4; var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); d3_geo_areaRingSum.add(Math.atan2(v, u)); λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; } d3_geo_area.lineEnd = function() { nextPoint(λ00, φ00); }; } function d3_geo_cartesian(spherical) { var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; } function d3_geo_cartesianDot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } function d3_geo_cartesianCross(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] ]; } function d3_geo_cartesianAdd(a, b) { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; } function d3_geo_cartesianScale(vector, k) { return [ vector[0] * k, vector[1] * k, vector[2] * k ]; } function d3_geo_cartesianNormalize(d) { var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); d[0] /= l; d[1] /= l; d[2] /= l; } function d3_geo_spherical(cartesian) { return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; } function d3_geo_sphericalEqual(a, b) { return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; } d3.geo.bounds = function() { var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; var bound = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { bound.point = ringPoint; bound.lineStart = ringStart; bound.lineEnd = ringEnd; dλSum = 0; d3_geo_area.polygonStart(); }, polygonEnd: function() { d3_geo_area.polygonEnd(); bound.point = point; bound.lineStart = lineStart; bound.lineEnd = lineEnd; if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; range[0] = λ0, range[1] = λ1; } }; function point(λ, φ) { ranges.push(range = [ λ0 = λ, λ1 = λ ]); if (φ < φ0) φ0 = φ; if (φ > φ1) φ1 = φ; } function linePoint(λ, φ) { var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); if (p0) { var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); d3_geo_cartesianNormalize(inflection); inflection = d3_geo_spherical(inflection); var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { var φi = inflection[1] * d3_degrees; if (φi > φ1) φ1 = φi; } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { var φi = -inflection[1] * d3_degrees; if (φi < φ0) φ0 = φi; } else { if (φ < φ0) φ0 = φ; if (φ > φ1) φ1 = φ; } if (antimeridian) { if (λ < λ_) { if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; } else { if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } } else { if (λ1 >= λ0) { if (λ < λ0) λ0 = λ; if (λ > λ1) λ1 = λ; } else { if (λ > λ_) { if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; } else { if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } } } } else { point(λ, φ); } p0 = p, λ_ = λ; } function lineStart() { bound.point = linePoint; } function lineEnd() { range[0] = λ0, range[1] = λ1; bound.point = point; p0 = null; } function ringPoint(λ, φ) { if (p0) { var dλ = λ - λ_; dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; } else λ__ = λ, φ__ = φ; d3_geo_area.point(λ, φ); linePoint(λ, φ); } function ringStart() { d3_geo_area.lineStart(); } function ringEnd() { ringPoint(λ__, φ__); d3_geo_area.lineEnd(); if (abs(dλSum) > ε) λ0 = -(λ1 = 180); range[0] = λ0, range[1] = λ1; p0 = null; } function angle(λ0, λ1) { return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; } function compareRanges(a, b) { return a[0] - b[0]; } function withinRange(x, range) { return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; } return function(feature) { φ1 = λ1 = -(λ0 = φ0 = Infinity); ranges = []; d3.geo.stream(feature, bound); var n = ranges.length; if (n) { ranges.sort(compareRanges); for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { b = ranges[i]; if (withinRange(b[0], a) || withinRange(b[1], a)) { if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; } else { merged.push(a = b); } } var best = -Infinity, dλ; for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { b = merged[i]; if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; } } ranges = range = null; return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; }; }(); d3.geo.centroid = function(object) { d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; d3.geo.stream(object, d3_geo_centroid); var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; if (m < ε2) { x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; m = x * x + y * y + z * z; if (m < ε2) return [ NaN, NaN ]; } return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; }; var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; var d3_geo_centroid = { sphere: d3_noop, point: d3_geo_centroidPoint, lineStart: d3_geo_centroidLineStart, lineEnd: d3_geo_centroidLineEnd, polygonStart: function() { d3_geo_centroid.lineStart = d3_geo_centroidRingStart; }, polygonEnd: function() { d3_geo_centroid.lineStart = d3_geo_centroidLineStart; } }; function d3_geo_centroidPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); } function d3_geo_centroidPointXYZ(x, y, z) { ++d3_geo_centroidW0; d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; } function d3_geo_centroidLineStart() { var x0, y0, z0; d3_geo_centroid.point = function(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); x0 = cosφ * Math.cos(λ); y0 = cosφ * Math.sin(λ); z0 = Math.sin(φ); d3_geo_centroid.point = nextPoint; d3_geo_centroidPointXYZ(x0, y0, z0); }; function nextPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); d3_geo_centroidW1 += w; d3_geo_centroidX1 += w * (x0 + (x0 = x)); d3_geo_centroidY1 += w * (y0 + (y0 = y)); d3_geo_centroidZ1 += w * (z0 + (z0 = z)); d3_geo_centroidPointXYZ(x0, y0, z0); } } function d3_geo_centroidLineEnd() { d3_geo_centroid.point = d3_geo_centroidPoint; } function d3_geo_centroidRingStart() { var λ00, φ00, x0, y0, z0; d3_geo_centroid.point = function(λ, φ) { λ00 = λ, φ00 = φ; d3_geo_centroid.point = nextPoint; λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); x0 = cosφ * Math.cos(λ); y0 = cosφ * Math.sin(λ); z0 = Math.sin(φ); d3_geo_centroidPointXYZ(x0, y0, z0); }; d3_geo_centroid.lineEnd = function() { nextPoint(λ00, φ00); d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; d3_geo_centroid.point = d3_geo_centroidPoint; }; function nextPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); d3_geo_centroidX2 += v * cx; d3_geo_centroidY2 += v * cy; d3_geo_centroidZ2 += v * cz; d3_geo_centroidW1 += w; d3_geo_centroidX1 += w * (x0 + (x0 = x)); d3_geo_centroidY1 += w * (y0 + (y0 = y)); d3_geo_centroidZ1 += w * (z0 + (z0 = z)); d3_geo_centroidPointXYZ(x0, y0, z0); } } function d3_geo_compose(a, b) { function compose(x, y) { return x = a(x, y), b(x[0], x[1]); } if (a.invert && b.invert) compose.invert = function(x, y) { return x = b.invert(x, y), x && a.invert(x[0], x[1]); }; return compose; } function d3_true() { return true; } function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { var subject = [], clip = []; segments.forEach(function(segment) { if ((n = segment.length - 1) <= 0) return; var n, p0 = segment[0], p1 = segment[n]; if (d3_geo_sphericalEqual(p0, p1)) { listener.lineStart(); for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); listener.lineEnd(); return; } var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); a.o = b; subject.push(a); clip.push(b); a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); b = new d3_geo_clipPolygonIntersection(p1, null, a, true); a.o = b; subject.push(a); clip.push(b); }); clip.sort(compare); d3_geo_clipPolygonLinkCircular(subject); d3_geo_clipPolygonLinkCircular(clip); if (!subject.length) return; for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { clip[i].e = entry = !entry; } var start = subject[0], points, point; while (1) { var current = start, isSubject = true; while (current.v) if ((current = current.n) === start) return; points = current.z; listener.lineStart(); do { current.v = current.o.v = true; if (current.e) { if (isSubject) { for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); } else { interpolate(current.x, current.n.x, 1, listener); } current = current.n; } else { if (isSubject) { points = current.p.z; for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); } else { interpolate(current.x, current.p.x, -1, listener); } current = current.p; } current = current.o; points = current.z; isSubject = !isSubject; } while (!current.v); listener.lineEnd(); } } function d3_geo_clipPolygonLinkCircular(array) { if (!(n = array.length)) return; var n, i = 0, a = array[0], b; while (++i < n) { a.n = b = array[i]; b.p = a; a = b; } a.n = b = array[0]; b.p = a; } function d3_geo_clipPolygonIntersection(point, points, other, entry) { this.x = point; this.z = points; this.o = other; this.e = entry; this.v = false; this.n = this.p = null; } function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { return function(rotate, listener) { var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); var clip = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { clip.point = pointRing; clip.lineStart = ringStart; clip.lineEnd = ringEnd; segments = []; polygon = []; }, polygonEnd: function() { clip.point = point; clip.lineStart = lineStart; clip.lineEnd = lineEnd; segments = d3.merge(segments); var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); if (segments.length) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); } else if (clipStartInside) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); } if (polygonStarted) listener.polygonEnd(), polygonStarted = false; segments = polygon = null; }, sphere: function() { listener.polygonStart(); listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); listener.polygonEnd(); } }; function point(λ, φ) { var point = rotate(λ, φ); if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); } function pointLine(λ, φ) { var point = rotate(λ, φ); line.point(point[0], point[1]); } function lineStart() { clip.point = pointLine; line.lineStart(); } function lineEnd() { clip.point = point; line.lineEnd(); } var segments; var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; function pointRing(λ, φ) { ring.push([ λ, φ ]); var point = rotate(λ, φ); ringListener.point(point[0], point[1]); } function ringStart() { ringListener.lineStart(); ring = []; } function ringEnd() { pointRing(ring[0][0], ring[0][1]); ringListener.lineEnd(); var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; ring.pop(); polygon.push(ring); ring = null; if (!n) return; if (clean & 1) { segment = ringSegments[0]; var n = segment.length - 1, i = -1, point; if (n > 0) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; listener.lineStart(); while (++i < n) listener.point((point = segment[i])[0], point[1]); listener.lineEnd(); } return; } if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); } return clip; }; } function d3_geo_clipSegmentLength1(segment) { return segment.length > 1; } function d3_geo_clipBufferListener() { var lines = [], line; return { lineStart: function() { lines.push(line = []); }, point: function(λ, φ) { line.push([ λ, φ ]); }, lineEnd: d3_noop, buffer: function() { var buffer = lines; lines = []; line = null; return buffer; }, rejoin: function() { if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); } }; } function d3_geo_clipSort(a, b) { return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); } var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); function d3_geo_clipAntimeridianLine(listener) { var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; return { lineStart: function() { listener.lineStart(); clean = 1; }, point: function(λ1, φ1) { var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); if (abs(dλ - π) < ε) { listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); listener.point(sλ0, φ0); listener.lineEnd(); listener.lineStart(); listener.point(sλ1, φ0); listener.point(λ1, φ0); clean = 0; } else if (sλ0 !== sλ1 && dλ >= π) { if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); listener.point(sλ0, φ0); listener.lineEnd(); listener.lineStart(); listener.point(sλ1, φ0); clean = 0; } listener.point(λ0 = λ1, φ0 = φ1); sλ0 = sλ1; }, lineEnd: function() { listener.lineEnd(); λ0 = φ0 = NaN; }, clean: function() { return 2 - clean; } }; } function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; } function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { var φ; if (from == null) { φ = direction * halfπ; listener.point(-π, φ); listener.point(0, φ); listener.point(π, φ); listener.point(π, 0); listener.point(π, -φ); listener.point(0, -φ); listener.point(-π, -φ); listener.point(-π, 0); listener.point(-π, φ); } else if (abs(from[0] - to[0]) > ε) { var s = from[0] < to[0] ? π : -π; φ = direction * s / 2; listener.point(-s, φ); listener.point(0, φ); listener.point(s, φ); } else { listener.point(to[0], to[1]); } } function d3_geo_pointInPolygon(point, polygon) { var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; d3_geo_areaRingSum.reset(); for (var i = 0, n = polygon.length; i < n; ++i) { var ring = polygon[i], m = ring.length; if (!m) continue; var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; while (true) { if (j === m) j = 0; point = ring[j]; var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); polarAngle += antimeridian ? dλ + sdλ * τ : dλ; if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); d3_geo_cartesianNormalize(arc); var intersection = d3_geo_cartesianCross(meridianNormal, arc); d3_geo_cartesianNormalize(intersection); var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { winding += antimeridian ^ dλ >= 0 ? 1 : -1; } } if (!j++) break; λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; } } return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1; } function d3_geo_clipCircle(radius) { var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); function visible(λ, φ) { return Math.cos(λ) * Math.cos(φ) > cr; } function clipLine(listener) { var point0, c0, v0, v00, clean; return { lineStart: function() { v00 = v0 = false; clean = 1; }, point: function(λ, φ) { var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; if (!point0 && (v00 = v0 = v)) listener.lineStart(); if (v !== v0) { point2 = intersect(point0, point1); if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { point1[0] += ε; point1[1] += ε; v = visible(point1[0], point1[1]); } } if (v !== v0) { clean = 0; if (v) { listener.lineStart(); point2 = intersect(point1, point0); listener.point(point2[0], point2[1]); } else { point2 = intersect(point0, point1); listener.point(point2[0], point2[1]); listener.lineEnd(); } point0 = point2; } else if (notHemisphere && point0 && smallRadius ^ v) { var t; if (!(c & c0) && (t = intersect(point1, point0, true))) { clean = 0; if (smallRadius) { listener.lineStart(); listener.point(t[0][0], t[0][1]); listener.point(t[1][0], t[1][1]); listener.lineEnd(); } else { listener.point(t[1][0], t[1][1]); listener.lineEnd(); listener.lineStart(); listener.point(t[0][0], t[0][1]); } } } if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { listener.point(point1[0], point1[1]); } point0 = point1, v0 = v, c0 = c; }, lineEnd: function() { if (v0) listener.lineEnd(); point0 = null; }, clean: function() { return clean | (v00 && v0) << 1; } }; } function intersect(a, b, two) { var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; if (!determinant) return !two && a; var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); d3_geo_cartesianAdd(A, B); var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); if (t2 < 0) return; var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); d3_geo_cartesianAdd(q, A); q = d3_geo_spherical(q); if (!two) return q; var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); d3_geo_cartesianAdd(q1, A); return [ q, d3_geo_spherical(q1) ]; } } function code(λ, φ) { var r = smallRadius ? radius : π - radius, code = 0; if (λ < -r) code |= 1; else if (λ > r) code |= 2; if (φ < -r) code |= 4; else if (φ > r) code |= 8; return code; } } function d3_geom_clipLine(x0, y0, x1, y1) { return function(line) { var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; r = x0 - ax; if (!dx && r > 0) return; r /= dx; if (dx < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dx > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = x1 - ax; if (!dx && r < 0) return; r /= dx; if (dx < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dx > 0) { if (r < t0) return; if (r < t1) t1 = r; } r = y0 - ay; if (!dy && r > 0) return; r /= dy; if (dy < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dy > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = y1 - ay; if (!dy && r < 0) return; r /= dy; if (dy < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dy > 0) { if (r < t0) return; if (r < t1) t1 = r; } if (t0 > 0) line.a = { x: ax + t0 * dx, y: ay + t0 * dy }; if (t1 < 1) line.b = { x: ax + t1 * dx, y: ay + t1 * dy }; return line; }; } var d3_geo_clipExtentMAX = 1e9; d3.geo.clipExtent = function() { var x0, y0, x1, y1, stream, clip, clipExtent = { stream: function(output) { if (stream) stream.valid = false; stream = clip(output); stream.valid = true; return stream; }, extent: function(_) { if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); if (stream) stream.valid = false, stream = null; return clipExtent; } }; return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); }; function d3_geo_clipExtent(x0, y0, x1, y1) { return function(listener) { var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; var clip = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { listener = bufferListener; segments = []; polygon = []; clean = true; }, polygonEnd: function() { listener = listener_; segments = d3.merge(segments); var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; if (inside || visible) { listener.polygonStart(); if (inside) { listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); } if (visible) { d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); } listener.polygonEnd(); } segments = polygon = ring = null; } }; function insidePolygon(p) { var wn = 0, n = polygon.length, y = p[1]; for (var i = 0; i < n; ++i) { for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { b = v[j]; if (a[1] <= y) { if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; } else { if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; } a = b; } } return wn !== 0; } function interpolate(from, to, direction, listener) { var a = 0, a1 = 0; if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { do { listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); } while ((a = (a + direction + 4) % 4) !== a1); } else { listener.point(to[0], to[1]); } } function pointVisible(x, y) { return x0 <= x && x <= x1 && y0 <= y && y <= y1; } function point(x, y) { if (pointVisible(x, y)) listener.point(x, y); } var x__, y__, v__, x_, y_, v_, first, clean; function lineStart() { clip.point = linePoint; if (polygon) polygon.push(ring = []); first = true; v_ = false; x_ = y_ = NaN; } function lineEnd() { if (segments) { linePoint(x__, y__); if (v__ && v_) bufferListener.rejoin(); segments.push(bufferListener.buffer()); } clip.point = point; if (v_) listener.lineEnd(); } function linePoint(x, y) { x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); var v = pointVisible(x, y); if (polygon) ring.push([ x, y ]); if (first) { x__ = x, y__ = y, v__ = v; first = false; if (v) { listener.lineStart(); listener.point(x, y); } } else { if (v && v_) listener.point(x, y); else { var l = { a: { x: x_, y: y_ }, b: { x: x, y: y } }; if (clipLine(l)) { if (!v_) { listener.lineStart(); listener.point(l.a.x, l.a.y); } listener.point(l.b.x, l.b.y); if (!v) listener.lineEnd(); clean = false; } else if (v) { listener.lineStart(); listener.point(x, y); clean = false; } } } x_ = x, y_ = y, v_ = v; } return clip; }; function corner(p, direction) { return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; } function compare(a, b) { return comparePoints(a.x, b.x); } function comparePoints(a, b) { var ca = corner(a, 1), cb = corner(b, 1); return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; } } function d3_geo_conic(projectAt) { var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); p.parallels = function(_) { if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); }; return p; } function d3_geo_conicEqualArea(φ0, φ1) { var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; function forward(λ, φ) { var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; } forward.invert = function(x, y) { var ρ0_y = ρ0 - y; return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; }; return forward; } (d3.geo.conicEqualArea = function() { return d3_geo_conic(d3_geo_conicEqualArea); }).raw = d3_geo_conicEqualArea; d3.geo.albers = function() { return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); }; d3.geo.albersUsa = function() { var lower48 = d3.geo.albers(); var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); var point, pointStream = { point: function(x, y) { point = [ x, y ]; } }, lower48Point, alaskaPoint, hawaiiPoint; function albersUsa(coordinates) { var x = coordinates[0], y = coordinates[1]; point = null; (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); return point; } albersUsa.invert = function(coordinates) { var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); }; albersUsa.stream = function(stream) { var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); return { point: function(x, y) { lower48Stream.point(x, y); alaskaStream.point(x, y); hawaiiStream.point(x, y); }, sphere: function() { lower48Stream.sphere(); alaskaStream.sphere(); hawaiiStream.sphere(); }, lineStart: function() { lower48Stream.lineStart(); alaskaStream.lineStart(); hawaiiStream.lineStart(); }, lineEnd: function() { lower48Stream.lineEnd(); alaskaStream.lineEnd(); hawaiiStream.lineEnd(); }, polygonStart: function() { lower48Stream.polygonStart(); alaskaStream.polygonStart(); hawaiiStream.polygonStart(); }, polygonEnd: function() { lower48Stream.polygonEnd(); alaskaStream.polygonEnd(); hawaiiStream.polygonEnd(); } }; }; albersUsa.precision = function(_) { if (!arguments.length) return lower48.precision(); lower48.precision(_); alaska.precision(_); hawaii.precision(_); return albersUsa; }; albersUsa.scale = function(_) { if (!arguments.length) return lower48.scale(); lower48.scale(_); alaska.scale(_ * .35); hawaii.scale(_); return albersUsa.translate(lower48.translate()); }; albersUsa.translate = function(_) { if (!arguments.length) return lower48.translate(); var k = lower48.scale(), x = +_[0], y = +_[1]; lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; return albersUsa; }; return albersUsa.scale(1070); }; var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { point: d3_noop, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: function() { d3_geo_pathAreaPolygon = 0; d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; }, polygonEnd: function() { d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); } }; function d3_geo_pathAreaRingStart() { var x00, y00, x0, y0; d3_geo_pathArea.point = function(x, y) { d3_geo_pathArea.point = nextPoint; x00 = x0 = x, y00 = y0 = y; }; function nextPoint(x, y) { d3_geo_pathAreaPolygon += y0 * x - x0 * y; x0 = x, y0 = y; } d3_geo_pathArea.lineEnd = function() { nextPoint(x00, y00); }; } var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; var d3_geo_pathBounds = { point: d3_geo_pathBoundsPoint, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: d3_noop, polygonEnd: d3_noop }; function d3_geo_pathBoundsPoint(x, y) { if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; } function d3_geo_pathBuffer() { var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; var stream = { point: point, lineStart: function() { stream.point = pointLineStart; }, lineEnd: lineEnd, polygonStart: function() { stream.lineEnd = lineEndPolygon; }, polygonEnd: function() { stream.lineEnd = lineEnd; stream.point = point; }, pointRadius: function(_) { pointCircle = d3_geo_pathBufferCircle(_); return stream; }, result: function() { if (buffer.length) { var result = buffer.join(""); buffer = []; return result; } } }; function point(x, y) { buffer.push("M", x, ",", y, pointCircle); } function pointLineStart(x, y) { buffer.push("M", x, ",", y); stream.point = pointLine; } function pointLine(x, y) { buffer.push("L", x, ",", y); } function lineEnd() { stream.point = point; } function lineEndPolygon() { buffer.push("Z"); } return stream; } function d3_geo_pathBufferCircle(radius) { return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; } var d3_geo_pathCentroid = { point: d3_geo_pathCentroidPoint, lineStart: d3_geo_pathCentroidLineStart, lineEnd: d3_geo_pathCentroidLineEnd, polygonStart: function() { d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; }, polygonEnd: function() { d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; } }; function d3_geo_pathCentroidPoint(x, y) { d3_geo_centroidX0 += x; d3_geo_centroidY0 += y; ++d3_geo_centroidZ0; } function d3_geo_pathCentroidLineStart() { var x0, y0; d3_geo_pathCentroid.point = function(x, y) { d3_geo_pathCentroid.point = nextPoint; d3_geo_pathCentroidPoint(x0 = x, y0 = y); }; function nextPoint(x, y) { var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); d3_geo_centroidX1 += z * (x0 + x) / 2; d3_geo_centroidY1 += z * (y0 + y) / 2; d3_geo_centroidZ1 += z; d3_geo_pathCentroidPoint(x0 = x, y0 = y); } } function d3_geo_pathCentroidLineEnd() { d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; } function d3_geo_pathCentroidRingStart() { var x00, y00, x0, y0; d3_geo_pathCentroid.point = function(x, y) { d3_geo_pathCentroid.point = nextPoint; d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); }; function nextPoint(x, y) { var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); d3_geo_centroidX1 += z * (x0 + x) / 2; d3_geo_centroidY1 += z * (y0 + y) / 2; d3_geo_centroidZ1 += z; z = y0 * x - x0 * y; d3_geo_centroidX2 += z * (x0 + x); d3_geo_centroidY2 += z * (y0 + y); d3_geo_centroidZ2 += z * 3; d3_geo_pathCentroidPoint(x0 = x, y0 = y); } d3_geo_pathCentroid.lineEnd = function() { nextPoint(x00, y00); }; } function d3_geo_pathContext(context) { var pointRadius = 4.5; var stream = { point: point, lineStart: function() { stream.point = pointLineStart; }, lineEnd: lineEnd, polygonStart: function() { stream.lineEnd = lineEndPolygon; }, polygonEnd: function() { stream.lineEnd = lineEnd; stream.point = point; }, pointRadius: function(_) { pointRadius = _; return stream; }, result: d3_noop }; function point(x, y) { context.moveTo(x + pointRadius, y); context.arc(x, y, pointRadius, 0, τ); } function pointLineStart(x, y) { context.moveTo(x, y); stream.point = pointLine; } function pointLine(x, y) { context.lineTo(x, y); } function lineEnd() { stream.point = point; } function lineEndPolygon() { context.closePath(); } return stream; } function d3_geo_resample(project) { var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; function resample(stream) { return (maxDepth ? resampleRecursive : resampleNone)(stream); } function resampleNone(stream) { return d3_geo_transformPoint(stream, function(x, y) { x = project(x, y); stream.point(x[0], x[1]); }); } function resampleRecursive(stream) { var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; var resample = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { stream.polygonStart(); resample.lineStart = ringStart; }, polygonEnd: function() { stream.polygonEnd(); resample.lineStart = lineStart; } }; function point(x, y) { x = project(x, y); stream.point(x[0], x[1]); } function lineStart() { x0 = NaN; resample.point = linePoint; stream.lineStart(); } function linePoint(λ, φ) { var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); stream.point(x0, y0); } function lineEnd() { resample.point = point; stream.lineEnd(); } function ringStart() { lineStart(); resample.point = ringPoint; resample.lineEnd = ringEnd; } function ringPoint(λ, φ) { linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; resample.point = linePoint; } function ringEnd() { resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); resample.lineEnd = lineEnd; lineEnd(); } return resample; } function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; if (d2 > 4 * δ2 && depth--) { var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); stream.point(x2, y2); resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); } } } resample.precision = function(_) { if (!arguments.length) return Math.sqrt(δ2); maxDepth = (δ2 = _ * _) > 0 && 16; return resample; }; return resample; } d3.geo.path = function() { var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; function path(object) { if (object) { if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); d3.geo.stream(object, cacheStream); } return contextStream.result(); } path.area = function(object) { d3_geo_pathAreaSum = 0; d3.geo.stream(object, projectStream(d3_geo_pathArea)); return d3_geo_pathAreaSum; }; path.centroid = function(object) { d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; }; path.bounds = function(object) { d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); d3.geo.stream(object, projectStream(d3_geo_pathBounds)); return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; }; path.projection = function(_) { if (!arguments.length) return projection; projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; return reset(); }; path.context = function(_) { if (!arguments.length) return context; contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); return reset(); }; path.pointRadius = function(_) { if (!arguments.length) return pointRadius; pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); return path; }; function reset() { cacheStream = null; return path; } return path.projection(d3.geo.albersUsa()).context(null); }; function d3_geo_pathProjectStream(project) { var resample = d3_geo_resample(function(x, y) { return project([ x * d3_degrees, y * d3_degrees ]); }); return function(stream) { return d3_geo_projectionRadians(resample(stream)); }; } d3.geo.transform = function(methods) { return { stream: function(stream) { var transform = new d3_geo_transform(stream); for (var k in methods) transform[k] = methods[k]; return transform; } }; }; function d3_geo_transform(stream) { this.stream = stream; } d3_geo_transform.prototype = { point: function(x, y) { this.stream.point(x, y); }, sphere: function() { this.stream.sphere(); }, lineStart: function() { this.stream.lineStart(); }, lineEnd: function() { this.stream.lineEnd(); }, polygonStart: function() { this.stream.polygonStart(); }, polygonEnd: function() { this.stream.polygonEnd(); } }; function d3_geo_transformPoint(stream, point) { return { point: point, sphere: function() { stream.sphere(); }, lineStart: function() { stream.lineStart(); }, lineEnd: function() { stream.lineEnd(); }, polygonStart: function() { stream.polygonStart(); }, polygonEnd: function() { stream.polygonEnd(); } }; } d3.geo.projection = d3_geo_projection; d3.geo.projectionMutator = d3_geo_projectionMutator; function d3_geo_projection(project) { return d3_geo_projectionMutator(function() { return project; })(); } function d3_geo_projectionMutator(projectAt) { var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { x = project(x, y); return [ x[0] * k + δx, δy - x[1] * k ]; }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; function projection(point) { point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); return [ point[0] * k + δx, δy - point[1] * k ]; } function invert(point) { point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; } projection.stream = function(output) { if (stream) stream.valid = false; stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); stream.valid = true; return stream; }; projection.clipAngle = function(_) { if (!arguments.length) return clipAngle; preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); return invalidate(); }; projection.clipExtent = function(_) { if (!arguments.length) return clipExtent; clipExtent = _; postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; return invalidate(); }; projection.scale = function(_) { if (!arguments.length) return k; k = +_; return reset(); }; projection.translate = function(_) { if (!arguments.length) return [ x, y ]; x = +_[0]; y = +_[1]; return reset(); }; projection.center = function(_) { if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; λ = _[0] % 360 * d3_radians; φ = _[1] % 360 * d3_radians; return reset(); }; projection.rotate = function(_) { if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; δλ = _[0] % 360 * d3_radians; δφ = _[1] % 360 * d3_radians; δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; return reset(); }; d3.rebind(projection, projectResample, "precision"); function reset() { projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); var center = project(λ, φ); δx = x - center[0] * k; δy = y + center[1] * k; return invalidate(); } function invalidate() { if (stream) stream.valid = false, stream = null; return projection; } return function() { project = projectAt.apply(this, arguments); projection.invert = project.invert && invert; return reset(); }; } function d3_geo_projectionRadians(stream) { return d3_geo_transformPoint(stream, function(x, y) { stream.point(x * d3_radians, y * d3_radians); }); } function d3_geo_equirectangular(λ, φ) { return [ λ, φ ]; } (d3.geo.equirectangular = function() { return d3_geo_projection(d3_geo_equirectangular); }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; d3.geo.rotation = function(rotate) { rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); function forward(coordinates) { coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; } forward.invert = function(coordinates) { coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; }; return forward; }; function d3_geo_identityRotation(λ, φ) { return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; } d3_geo_identityRotation.invert = d3_geo_equirectangular; function d3_geo_rotation(δλ, δφ, δγ) { return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; } function d3_geo_forwardRotationλ(δλ) { return function(λ, φ) { return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; }; } function d3_geo_rotationλ(δλ) { var rotation = d3_geo_forwardRotationλ(δλ); rotation.invert = d3_geo_forwardRotationλ(-δλ); return rotation; } function d3_geo_rotationφγ(δφ, δγ) { var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); function rotation(λ, φ) { var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; } rotation.invert = function(λ, φ) { var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; }; return rotation; } d3.geo.circle = function() { var origin = [ 0, 0 ], angle, precision = 6, interpolate; function circle() { var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; interpolate(null, null, 1, { point: function(x, y) { ring.push(x = rotate(x, y)); x[0] *= d3_degrees, x[1] *= d3_degrees; } }); return { type: "Polygon", coordinates: [ ring ] }; } circle.origin = function(x) { if (!arguments.length) return origin; origin = x; return circle; }; circle.angle = function(x) { if (!arguments.length) return angle; interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); return circle; }; circle.precision = function(_) { if (!arguments.length) return precision; interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); return circle; }; return circle.angle(90); }; function d3_geo_circleInterpolate(radius, precision) { var cr = Math.cos(radius), sr = Math.sin(radius); return function(from, to, direction, listener) { var step = direction * precision; if (from != null) { from = d3_geo_circleAngle(cr, from); to = d3_geo_circleAngle(cr, to); if (direction > 0 ? from < to : from > to) from += direction * τ; } else { from = radius + direction * τ; to = radius - .5 * step; } for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); } }; } function d3_geo_circleAngle(cr, point) { var a = d3_geo_cartesian(point); a[0] -= cr; d3_geo_cartesianNormalize(a); var angle = d3_acos(-a[1]); return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); } d3.geo.distance = function(a, b) { var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); }; d3.geo.graticule = function() { var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; function graticule() { return { type: "MultiLineString", coordinates: lines() }; } function lines() { return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return abs(x % DX) > ε; }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return abs(y % DY) > ε; }).map(y)); } graticule.lines = function() { return lines().map(function(coordinates) { return { type: "LineString", coordinates: coordinates }; }); }; graticule.outline = function() { return { type: "Polygon", coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] }; }; graticule.extent = function(_) { if (!arguments.length) return graticule.minorExtent(); return graticule.majorExtent(_).minorExtent(_); }; graticule.majorExtent = function(_) { if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; X0 = +_[0][0], X1 = +_[1][0]; Y0 = +_[0][1], Y1 = +_[1][1]; if (X0 > X1) _ = X0, X0 = X1, X1 = _; if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; return graticule.precision(precision); }; graticule.minorExtent = function(_) { if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; x0 = +_[0][0], x1 = +_[1][0]; y0 = +_[0][1], y1 = +_[1][1]; if (x0 > x1) _ = x0, x0 = x1, x1 = _; if (y0 > y1) _ = y0, y0 = y1, y1 = _; return graticule.precision(precision); }; graticule.step = function(_) { if (!arguments.length) return graticule.minorStep(); return graticule.majorStep(_).minorStep(_); }; graticule.majorStep = function(_) { if (!arguments.length) return [ DX, DY ]; DX = +_[0], DY = +_[1]; return graticule; }; graticule.minorStep = function(_) { if (!arguments.length) return [ dx, dy ]; dx = +_[0], dy = +_[1]; return graticule; }; graticule.precision = function(_) { if (!arguments.length) return precision; precision = +_; x = d3_geo_graticuleX(y0, y1, 90); y = d3_geo_graticuleY(x0, x1, precision); X = d3_geo_graticuleX(Y0, Y1, 90); Y = d3_geo_graticuleY(X0, X1, precision); return graticule; }; return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); }; function d3_geo_graticuleX(y0, y1, dy) { var y = d3.range(y0, y1 - ε, dy).concat(y1); return function(x) { return y.map(function(y) { return [ x, y ]; }); }; } function d3_geo_graticuleY(x0, x1, dx) { var x = d3.range(x0, x1 - ε, dx).concat(x1); return function(y) { return x.map(function(x) { return [ x, y ]; }); }; } function d3_source(d) { return d.source; } function d3_target(d) { return d.target; } d3.geo.greatArc = function() { var source = d3_source, source_, target = d3_target, target_; function greatArc() { return { type: "LineString", coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] }; } greatArc.distance = function() { return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); }; greatArc.source = function(_) { if (!arguments.length) return source; source = _, source_ = typeof _ === "function" ? null : _; return greatArc; }; greatArc.target = function(_) { if (!arguments.length) return target; target = _, target_ = typeof _ === "function" ? null : _; return greatArc; }; greatArc.precision = function() { return arguments.length ? greatArc : 0; }; return greatArc; }; d3.geo.interpolate = function(source, target) { return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); }; function d3_geo_interpolate(x0, y0, x1, y1) { var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); var interpolate = d ? function(t) { var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; } : function() { return [ x0 * d3_degrees, y0 * d3_degrees ]; }; interpolate.distance = d; return interpolate; } d3.geo.length = function(object) { d3_geo_lengthSum = 0; d3.geo.stream(object, d3_geo_length); return d3_geo_lengthSum; }; var d3_geo_lengthSum; var d3_geo_length = { sphere: d3_noop, point: d3_noop, lineStart: d3_geo_lengthLineStart, lineEnd: d3_noop, polygonStart: d3_noop, polygonEnd: d3_noop }; function d3_geo_lengthLineStart() { var λ0, sinφ0, cosφ0; d3_geo_length.point = function(λ, φ) { λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); d3_geo_length.point = nextPoint; }; d3_geo_length.lineEnd = function() { d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; }; function nextPoint(λ, φ) { var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; } } function d3_geo_azimuthal(scale, angle) { function azimuthal(λ, φ) { var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; } azimuthal.invert = function(x, y) { var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; }; return azimuthal; } var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { return Math.sqrt(2 / (1 + cosλcosφ)); }, function(ρ) { return 2 * Math.asin(ρ / 2); }); (d3.geo.azimuthalEqualArea = function() { return d3_geo_projection(d3_geo_azimuthalEqualArea); }).raw = d3_geo_azimuthalEqualArea; var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { var c = Math.acos(cosλcosφ); return c && c / Math.sin(c); }, d3_identity); (d3.geo.azimuthalEquidistant = function() { return d3_geo_projection(d3_geo_azimuthalEquidistant); }).raw = d3_geo_azimuthalEquidistant; function d3_geo_conicConformal(φ0, φ1) { var cosφ0 = Math.cos(φ0), t = function(φ) { return Math.tan(π / 4 + φ / 2); }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; if (!n) return d3_geo_mercator; function forward(λ, φ) { if (F > 0) { if (φ < -halfπ + ε) φ = -halfπ + ε; } else { if (φ > halfπ - ε) φ = halfπ - ε; } var ρ = F / Math.pow(t(φ), n); return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; } forward.invert = function(x, y) { var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; }; return forward; } (d3.geo.conicConformal = function() { return d3_geo_conic(d3_geo_conicConformal); }).raw = d3_geo_conicConformal; function d3_geo_conicEquidistant(φ0, φ1) { var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; if (abs(n) < ε) return d3_geo_equirectangular; function forward(λ, φ) { var ρ = G - φ; return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; } forward.invert = function(x, y) { var ρ0_y = G - y; return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; }; return forward; } (d3.geo.conicEquidistant = function() { return d3_geo_conic(d3_geo_conicEquidistant); }).raw = d3_geo_conicEquidistant; var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { return 1 / cosλcosφ; }, Math.atan); (d3.geo.gnomonic = function() { return d3_geo_projection(d3_geo_gnomonic); }).raw = d3_geo_gnomonic; function d3_geo_mercator(λ, φ) { return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; } d3_geo_mercator.invert = function(x, y) { return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; }; function d3_geo_mercatorProjection(project) { var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; m.scale = function() { var v = scale.apply(m, arguments); return v === m ? clipAuto ? m.clipExtent(null) : m : v; }; m.translate = function() { var v = translate.apply(m, arguments); return v === m ? clipAuto ? m.clipExtent(null) : m : v; }; m.clipExtent = function(_) { var v = clipExtent.apply(m, arguments); if (v === m) { if (clipAuto = _ == null) { var k = π * scale(), t = translate(); clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); } } else if (clipAuto) { v = null; } return v; }; return m.clipExtent(null); } (d3.geo.mercator = function() { return d3_geo_mercatorProjection(d3_geo_mercator); }).raw = d3_geo_mercator; var d3_geo_orthographic = d3_geo_azimuthal(function() { return 1; }, Math.asin); (d3.geo.orthographic = function() { return d3_geo_projection(d3_geo_orthographic); }).raw = d3_geo_orthographic; var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { return 1 / (1 + cosλcosφ); }, function(ρ) { return 2 * Math.atan(ρ); }); (d3.geo.stereographic = function() { return d3_geo_projection(d3_geo_stereographic); }).raw = d3_geo_stereographic; function d3_geo_transverseMercator(λ, φ) { return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; } d3_geo_transverseMercator.invert = function(x, y) { return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; }; (d3.geo.transverseMercator = function() { var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; projection.center = function(_) { return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); }; projection.rotate = function(_) { return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), [ _[0], _[1], _[2] - 90 ]); }; return rotate([ 0, 0, 90 ]); }).raw = d3_geo_transverseMercator; d3.geom = {}; function d3_geom_pointX(d) { return d[0]; } function d3_geom_pointY(d) { return d[1]; } d3.geom.hull = function(vertices) { var x = d3_geom_pointX, y = d3_geom_pointY; if (arguments.length) return hull(vertices); function hull(data) { if (data.length < 3) return []; var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; for (i = 0; i < n; i++) { points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); } points.sort(d3_geom_hullOrder); for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); return polygon; } hull.x = function(_) { return arguments.length ? (x = _, hull) : x; }; hull.y = function(_) { return arguments.length ? (y = _, hull) : y; }; return hull; }; function d3_geom_hullUpper(points) { var n = points.length, hull = [ 0, 1 ], hs = 2; for (var i = 2; i < n; i++) { while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; hull[hs++] = i; } return hull.slice(0, hs); } function d3_geom_hullOrder(a, b) { return a[0] - b[0] || a[1] - b[1]; } d3.geom.polygon = function(coordinates) { d3_subclass(coordinates, d3_geom_polygonPrototype); return coordinates; }; var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; d3_geom_polygonPrototype.area = function() { var i = -1, n = this.length, a, b = this[n - 1], area = 0; while (++i < n) { a = b; b = this[i]; area += a[1] * b[0] - a[0] * b[1]; } return area * .5; }; d3_geom_polygonPrototype.centroid = function(k) { var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; if (!arguments.length) k = -1 / (6 * this.area()); while (++i < n) { a = b; b = this[i]; c = a[0] * b[1] - b[0] * a[1]; x += (a[0] + b[0]) * c; y += (a[1] + b[1]) * c; } return [ x * k, y * k ]; }; d3_geom_polygonPrototype.clip = function(subject) { var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; while (++i < n) { input = subject.slice(); subject.length = 0; b = this[i]; c = input[(m = input.length - closed) - 1]; j = -1; while (++j < m) { d = input[j]; if (d3_geom_polygonInside(d, a, b)) { if (!d3_geom_polygonInside(c, a, b)) { subject.push(d3_geom_polygonIntersect(c, d, a, b)); } subject.push(d); } else if (d3_geom_polygonInside(c, a, b)) { subject.push(d3_geom_polygonIntersect(c, d, a, b)); } c = d; } if (closed) subject.push(subject[0]); a = b; } return subject; }; function d3_geom_polygonInside(p, a, b) { return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); } function d3_geom_polygonIntersect(c, d, a, b) { var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); return [ x1 + ua * x21, y1 + ua * y21 ]; } function d3_geom_polygonClosed(coordinates) { var a = coordinates[0], b = coordinates[coordinates.length - 1]; return !(a[0] - b[0] || a[1] - b[1]); } var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; function d3_geom_voronoiBeach() { d3_geom_voronoiRedBlackNode(this); this.edge = this.site = this.circle = null; } function d3_geom_voronoiCreateBeach(site) { var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); beach.site = site; return beach; } function d3_geom_voronoiDetachBeach(beach) { d3_geom_voronoiDetachCircle(beach); d3_geom_voronoiBeaches.remove(beach); d3_geom_voronoiBeachPool.push(beach); d3_geom_voronoiRedBlackNode(beach); } function d3_geom_voronoiRemoveBeach(beach) { var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { x: x, y: y }, previous = beach.P, next = beach.N, disappearing = [ beach ]; d3_geom_voronoiDetachBeach(beach); var lArc = previous; while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { previous = lArc.P; disappearing.unshift(lArc); d3_geom_voronoiDetachBeach(lArc); lArc = previous; } disappearing.unshift(lArc); d3_geom_voronoiDetachCircle(lArc); var rArc = next; while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { next = rArc.N; disappearing.push(rArc); d3_geom_voronoiDetachBeach(rArc); rArc = next; } disappearing.push(rArc); d3_geom_voronoiDetachCircle(rArc); var nArcs = disappearing.length, iArc; for (iArc = 1; iArc < nArcs; ++iArc) { rArc = disappearing[iArc]; lArc = disappearing[iArc - 1]; d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); } lArc = disappearing[0]; rArc = disappearing[nArcs - 1]; rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); } function d3_geom_voronoiAddBeach(site) { var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; while (node) { dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; if (dxl > ε) node = node.L; else { dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); if (dxr > ε) { if (!node.R) { lArc = node; break; } node = node.R; } else { if (dxl > -ε) { lArc = node.P; rArc = node; } else if (dxr > -ε) { lArc = node; rArc = node.N; } else { lArc = rArc = node; } break; } } } var newArc = d3_geom_voronoiCreateBeach(site); d3_geom_voronoiBeaches.insert(lArc, newArc); if (!lArc && !rArc) return; if (lArc === rArc) { d3_geom_voronoiDetachCircle(lArc); rArc = d3_geom_voronoiCreateBeach(lArc.site); d3_geom_voronoiBeaches.insert(newArc, rArc); newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); return; } if (!rArc) { newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); return; } d3_geom_voronoiDetachCircle(lArc); d3_geom_voronoiDetachCircle(rArc); var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { x: (cy * hb - by * hc) / d + ax, y: (bx * hc - cx * hb) / d + ay }; d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); } function d3_geom_voronoiLeftBreakPoint(arc, directrix) { var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; if (!pby2) return rfocx; var lArc = arc.P; if (!lArc) return -Infinity; site = lArc.site; var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; if (!plby2) return lfocx; var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; return (rfocx + lfocx) / 2; } function d3_geom_voronoiRightBreakPoint(arc, directrix) { var rArc = arc.N; if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); var site = arc.site; return site.y === directrix ? site.x : Infinity; } function d3_geom_voronoiCell(site) { this.site = site; this.edges = []; } d3_geom_voronoiCell.prototype.prepare = function() { var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; while (iHalfEdge--) { edge = halfEdges[iHalfEdge].edge; if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); } halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); return halfEdges.length; }; function d3_geom_voronoiCloseCells(extent) { var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; while (iCell--) { cell = cells[iCell]; if (!cell || !cell.prepare()) continue; halfEdges = cell.edges; nHalfEdges = halfEdges.length; iHalfEdge = 0; while (iHalfEdge < nHalfEdges) { end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { x: x0, y: abs(x2 - x0) < ε ? y2 : y1 } : abs(y3 - y1) < ε && x1 - x3 > ε ? { x: abs(y2 - y1) < ε ? x2 : x1, y: y1 } : abs(x3 - x1) < ε && y3 - y0 > ε ? { x: x1, y: abs(x2 - x1) < ε ? y2 : y0 } : abs(y3 - y0) < ε && x3 - x0 > ε ? { x: abs(y2 - y0) < ε ? x2 : x0, y: y0 } : null), cell.site, null)); ++nHalfEdges; } } } } function d3_geom_voronoiHalfEdgeOrder(a, b) { return b.angle - a.angle; } function d3_geom_voronoiCircle() { d3_geom_voronoiRedBlackNode(this); this.x = this.y = this.arc = this.site = this.cy = null; } function d3_geom_voronoiAttachCircle(arc) { var lArc = arc.P, rArc = arc.N; if (!lArc || !rArc) return; var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; if (lSite === rSite) return; var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; var d = 2 * (ax * cy - ay * cx); if (d >= -ε2) return; var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); circle.arc = arc; circle.site = cSite; circle.x = x + bx; circle.y = cy + Math.sqrt(x * x + y * y); circle.cy = cy; arc.circle = circle; var before = null, node = d3_geom_voronoiCircles._; while (node) { if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { if (node.L) node = node.L; else { before = node.P; break; } } else { if (node.R) node = node.R; else { before = node; break; } } } d3_geom_voronoiCircles.insert(before, circle); if (!before) d3_geom_voronoiFirstCircle = circle; } function d3_geom_voronoiDetachCircle(arc) { var circle = arc.circle; if (circle) { if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; d3_geom_voronoiCircles.remove(circle); d3_geom_voronoiCirclePool.push(circle); d3_geom_voronoiRedBlackNode(circle); arc.circle = null; } } function d3_geom_voronoiClipEdges(extent) { var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; while (i--) { e = edges[i]; if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { e.a = e.b = null; edges.splice(i, 1); } } } function d3_geom_voronoiConnectEdge(edge, extent) { var vb = edge.b; if (vb) return true; var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; if (ry === ly) { if (fx < x0 || fx >= x1) return; if (lx > rx) { if (!va) va = { x: fx, y: y0 }; else if (va.y >= y1) return; vb = { x: fx, y: y1 }; } else { if (!va) va = { x: fx, y: y1 }; else if (va.y < y0) return; vb = { x: fx, y: y0 }; } } else { fm = (lx - rx) / (ry - ly); fb = fy - fm * fx; if (fm < -1 || fm > 1) { if (lx > rx) { if (!va) va = { x: (y0 - fb) / fm, y: y0 }; else if (va.y >= y1) return; vb = { x: (y1 - fb) / fm, y: y1 }; } else { if (!va) va = { x: (y1 - fb) / fm, y: y1 }; else if (va.y < y0) return; vb = { x: (y0 - fb) / fm, y: y0 }; } } else { if (ly < ry) { if (!va) va = { x: x0, y: fm * x0 + fb }; else if (va.x >= x1) return; vb = { x: x1, y: fm * x1 + fb }; } else { if (!va) va = { x: x1, y: fm * x1 + fb }; else if (va.x < x0) return; vb = { x: x0, y: fm * x0 + fb }; } } } edge.a = va; edge.b = vb; return true; } function d3_geom_voronoiEdge(lSite, rSite) { this.l = lSite; this.r = rSite; this.a = this.b = null; } function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { var edge = new d3_geom_voronoiEdge(lSite, rSite); d3_geom_voronoiEdges.push(edge); if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); return edge; } function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { var edge = new d3_geom_voronoiEdge(lSite, null); edge.a = va; edge.b = vb; d3_geom_voronoiEdges.push(edge); return edge; } function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { if (!edge.a && !edge.b) { edge.a = vertex; edge.l = lSite; edge.r = rSite; } else if (edge.l === rSite) { edge.b = vertex; } else { edge.a = vertex; } } function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { var va = edge.a, vb = edge.b; this.edge = edge; this.site = lSite; this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); } d3_geom_voronoiHalfEdge.prototype = { start: function() { return this.edge.l === this.site ? this.edge.a : this.edge.b; }, end: function() { return this.edge.l === this.site ? this.edge.b : this.edge.a; } }; function d3_geom_voronoiRedBlackTree() { this._ = null; } function d3_geom_voronoiRedBlackNode(node) { node.U = node.C = node.L = node.R = node.P = node.N = null; } d3_geom_voronoiRedBlackTree.prototype = { insert: function(after, node) { var parent, grandpa, uncle; if (after) { node.P = after; node.N = after.N; if (after.N) after.N.P = node; after.N = node; if (after.R) { after = after.R; while (after.L) after = after.L; after.L = node; } else { after.R = node; } parent = after; } else if (this._) { after = d3_geom_voronoiRedBlackFirst(this._); node.P = null; node.N = after; after.P = after.L = node; parent = after; } else { node.P = node.N = null; this._ = node; parent = null; } node.L = node.R = null; node.U = parent; node.C = true; after = node; while (parent && parent.C) { grandpa = parent.U; if (parent === grandpa.L) { uncle = grandpa.R; if (uncle && uncle.C) { parent.C = uncle.C = false; grandpa.C = true; after = grandpa; } else { if (after === parent.R) { d3_geom_voronoiRedBlackRotateLeft(this, parent); after = parent; parent = after.U; } parent.C = false; grandpa.C = true; d3_geom_voronoiRedBlackRotateRight(this, grandpa); } } else { uncle = grandpa.L; if (uncle && uncle.C) { parent.C = uncle.C = false; grandpa.C = true; after = grandpa; } else { if (after === parent.L) { d3_geom_voronoiRedBlackRotateRight(this, parent); after = parent; parent = after.U; } parent.C = false; grandpa.C = true; d3_geom_voronoiRedBlackRotateLeft(this, grandpa); } } parent = after.U; } this._.C = false; }, remove: function(node) { if (node.N) node.N.P = node.P; if (node.P) node.P.N = node.N; node.N = node.P = null; var parent = node.U, sibling, left = node.L, right = node.R, next, red; if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); if (parent) { if (parent.L === node) parent.L = next; else parent.R = next; } else { this._ = next; } if (left && right) { red = next.C; next.C = node.C; next.L = left; left.U = next; if (next !== right) { parent = next.U; next.U = node.U; node = next.R; parent.L = node; next.R = right; right.U = next; } else { next.U = parent; parent = next; node = next.R; } } else { red = node.C; node = next; } if (node) node.U = parent; if (red) return; if (node && node.C) { node.C = false; return; } do { if (node === this._) break; if (node === parent.L) { sibling = parent.R; if (sibling.C) { sibling.C = false; parent.C = true; d3_geom_voronoiRedBlackRotateLeft(this, parent); sibling = parent.R; } if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { if (!sibling.R || !sibling.R.C) { sibling.L.C = false; sibling.C = true; d3_geom_voronoiRedBlackRotateRight(this, sibling); sibling = parent.R; } sibling.C = parent.C; parent.C = sibling.R.C = false; d3_geom_voronoiRedBlackRotateLeft(this, parent); node = this._; break; } } else { sibling = parent.L; if (sibling.C) { sibling.C = false; parent.C = true; d3_geom_voronoiRedBlackRotateRight(this, parent); sibling = parent.L; } if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { if (!sibling.L || !sibling.L.C) { sibling.R.C = false; sibling.C = true; d3_geom_voronoiRedBlackRotateLeft(this, sibling); sibling = parent.L; } sibling.C = parent.C; parent.C = sibling.L.C = false; d3_geom_voronoiRedBlackRotateRight(this, parent); node = this._; break; } } sibling.C = true; node = parent; parent = parent.U; } while (!node.C); if (node) node.C = false; } }; function d3_geom_voronoiRedBlackRotateLeft(tree, node) { var p = node, q = node.R, parent = p.U; if (parent) { if (parent.L === p) parent.L = q; else parent.R = q; } else { tree._ = q; } q.U = parent; p.U = q; p.R = q.L; if (p.R) p.R.U = p; q.L = p; } function d3_geom_voronoiRedBlackRotateRight(tree, node) { var p = node, q = node.L, parent = p.U; if (parent) { if (parent.L === p) parent.L = q; else parent.R = q; } else { tree._ = q; } q.U = parent; p.U = q; p.L = q.R; if (p.L) p.L.U = p; q.R = p; } function d3_geom_voronoiRedBlackFirst(node) { while (node.L) node = node.L; return node; } function d3_geom_voronoi(sites, bbox) { var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; d3_geom_voronoiEdges = []; d3_geom_voronoiCells = new Array(sites.length); d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); while (true) { circle = d3_geom_voronoiFirstCircle; if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { if (site.x !== x0 || site.y !== y0) { d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); d3_geom_voronoiAddBeach(site); x0 = site.x, y0 = site.y; } site = sites.pop(); } else if (circle) { d3_geom_voronoiRemoveBeach(circle.arc); } else { break; } } if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); var diagram = { cells: d3_geom_voronoiCells, edges: d3_geom_voronoiEdges }; d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; return diagram; } function d3_geom_voronoiVertexOrder(a, b) { return b.y - a.y || b.x - a.x; } d3.geom.voronoi = function(points) { var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; if (points) return voronoi(points); function voronoi(data) { var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { var s = e.start(); return [ s.x, s.y ]; }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; polygon.point = data[i]; }); return polygons; } function sites(data) { return data.map(function(d, i) { return { x: Math.round(fx(d, i) / ε) * ε, y: Math.round(fy(d, i) / ε) * ε, i: i }; }); } voronoi.links = function(data) { return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { return edge.l && edge.r; }).map(function(edge) { return { source: data[edge.l.i], target: data[edge.r.i] }; }); }; voronoi.triangles = function(data) { var triangles = []; d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; while (++j < m) { e0 = e1; s0 = s1; e1 = edges[j].edge; s1 = e1.l === site ? e1.r : e1.l; if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { triangles.push([ data[i], data[s0.i], data[s1.i] ]); } } }); return triangles; }; voronoi.x = function(_) { return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; }; voronoi.y = function(_) { return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; }; voronoi.clipExtent = function(_) { if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; return voronoi; }; voronoi.size = function(_) { if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); }; return voronoi; }; var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; function d3_geom_voronoiTriangleArea(a, b, c) { return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); } d3.geom.delaunay = function(vertices) { return d3.geom.voronoi().triangles(vertices); }; d3.geom.quadtree = function(points, x1, y1, x2, y2) { var x = d3_geom_pointX, y = d3_geom_pointY, compat; if (compat = arguments.length) { x = d3_geom_quadtreeCompatX; y = d3_geom_quadtreeCompatY; if (compat === 3) { y2 = y1; x2 = x1; y1 = x1 = 0; } return quadtree(points); } function quadtree(data) { var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; if (x1 != null) { x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; } else { x2_ = y2_ = -(x1_ = y1_ = Infinity); xs = [], ys = []; n = data.length; if (compat) for (i = 0; i < n; ++i) { d = data[i]; if (d.x < x1_) x1_ = d.x; if (d.y < y1_) y1_ = d.y; if (d.x > x2_) x2_ = d.x; if (d.y > y2_) y2_ = d.y; xs.push(d.x); ys.push(d.y); } else for (i = 0; i < n; ++i) { var x_ = +fx(d = data[i], i), y_ = +fy(d, i); if (x_ < x1_) x1_ = x_; if (y_ < y1_) y1_ = y_; if (x_ > x2_) x2_ = x_; if (y_ > y2_) y2_ = y_; xs.push(x_); ys.push(y_); } } var dx = x2_ - x1_, dy = y2_ - y1_; if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; function insert(n, d, x, y, x1, y1, x2, y2) { if (isNaN(x) || isNaN(y)) return; if (n.leaf) { var nx = n.x, ny = n.y; if (nx != null) { if (abs(nx - x) + abs(ny - y) < .01) { insertChild(n, d, x, y, x1, y1, x2, y2); } else { var nPoint = n.point; n.x = n.y = n.point = null; insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); insertChild(n, d, x, y, x1, y1, x2, y2); } } else { n.x = x, n.y = y, n.point = d; } } else { insertChild(n, d, x, y, x1, y1, x2, y2); } } function insertChild(n, d, x, y, x1, y1, x2, y2) { var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; n.leaf = false; n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); if (right) x1 = xm; else x2 = xm; if (below) y1 = ym; else y2 = ym; insert(n, d, x, y, x1, y1, x2, y2); } var root = d3_geom_quadtreeNode(); root.add = function(d) { insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); }; root.visit = function(f) { d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); }; root.find = function(point) { return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); }; i = -1; if (x1 == null) { while (++i < n) { insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); } --i; } else data.forEach(root.add); xs = ys = data = d = null; return root; } quadtree.x = function(_) { return arguments.length ? (x = _, quadtree) : x; }; quadtree.y = function(_) { return arguments.length ? (y = _, quadtree) : y; }; quadtree.extent = function(_) { if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], y2 = +_[1][1]; return quadtree; }; quadtree.size = function(_) { if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; return quadtree; }; return quadtree; }; function d3_geom_quadtreeCompatX(d) { return d.x; } function d3_geom_quadtreeCompatY(d) { return d.y; } function d3_geom_quadtreeNode() { return { leaf: true, nodes: [], point: null, x: null, y: null }; } function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { if (!f(node, x1, y1, x2, y2)) { var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); } } function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { var minDistance2 = Infinity, closestPoint; (function find(node, x1, y1, x2, y2) { if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; if (point = node.point) { var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; if (distance2 < minDistance2) { var distance = Math.sqrt(minDistance2 = distance2); x0 = x - distance, y0 = y - distance; x3 = x + distance, y3 = y + distance; closestPoint = point; } } var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; for (var i = below << 1 | right, j = i + 4; i < j; ++i) { if (node = children[i & 3]) switch (i & 3) { case 0: find(node, x1, y1, xm, ym); break; case 1: find(node, xm, y1, x2, ym); break; case 2: find(node, x1, ym, xm, y2); break; case 3: find(node, xm, ym, x2, y2); break; } } })(root, x0, y0, x3, y3); return closestPoint; } d3.interpolateRgb = d3_interpolateRgb; function d3_interpolateRgb(a, b) { a = d3.rgb(a); b = d3.rgb(b); var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; return function(t) { return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); }; } d3.interpolateObject = d3_interpolateObject; function d3_interpolateObject(a, b) { var i = {}, c = {}, k; for (k in a) { if (k in b) { i[k] = d3_interpolate(a[k], b[k]); } else { c[k] = a[k]; } } for (k in b) { if (!(k in a)) { c[k] = b[k]; } } return function(t) { for (k in i) c[k] = i[k](t); return c; }; } d3.interpolateNumber = d3_interpolateNumber; function d3_interpolateNumber(a, b) { a = +a, b = +b; return function(t) { return a * (1 - t) + b * t; }; } d3.interpolateString = d3_interpolateString; function d3_interpolateString(a, b) { var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; a = a + "", b = b + ""; while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { if ((bs = bm.index) > bi) { bs = b.slice(bi, bs); if (s[i]) s[i] += bs; else s[++i] = bs; } if ((am = am[0]) === (bm = bm[0])) { if (s[i]) s[i] += bm; else s[++i] = bm; } else { s[++i] = null; q.push({ i: i, x: d3_interpolateNumber(am, bm) }); } bi = d3_interpolate_numberB.lastIndex; } if (bi < b.length) { bs = b.slice(bi); if (s[i]) s[i] += bs; else s[++i] = bs; } return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { return b(t) + ""; }) : function() { return b; } : (b = q.length, function(t) { for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }); } var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); d3.interpolate = d3_interpolate; function d3_interpolate(a, b) { var i = d3.interpolators.length, f; while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; return f; } d3.interpolators = [ function(a, b) { var t = typeof b; return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); } ]; d3.interpolateArray = d3_interpolateArray; function d3_interpolateArray(a, b) { var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); for (;i < na; ++i) c[i] = a[i]; for (;i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < n0; ++i) c[i] = x[i](t); return c; }; } var d3_ease_default = function() { return d3_identity; }; var d3_ease = d3.map({ linear: d3_ease_default, poly: d3_ease_poly, quad: function() { return d3_ease_quad; }, cubic: function() { return d3_ease_cubic; }, sin: function() { return d3_ease_sin; }, exp: function() { return d3_ease_exp; }, circle: function() { return d3_ease_circle; }, elastic: d3_ease_elastic, back: d3_ease_back, bounce: function() { return d3_ease_bounce; } }); var d3_ease_mode = d3.map({ "in": d3_identity, out: d3_ease_reverse, "in-out": d3_ease_reflect, "out-in": function(f) { return d3_ease_reflect(d3_ease_reverse(f)); } }); d3.ease = function(name) { var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; t = d3_ease.get(t) || d3_ease_default; m = d3_ease_mode.get(m) || d3_identity; return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); }; function d3_ease_clamp(f) { return function(t) { return t <= 0 ? 0 : t >= 1 ? 1 : f(t); }; } function d3_ease_reverse(f) { return function(t) { return 1 - f(1 - t); }; } function d3_ease_reflect(f) { return function(t) { return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); }; } function d3_ease_quad(t) { return t * t; } function d3_ease_cubic(t) { return t * t * t; } function d3_ease_cubicInOut(t) { if (t <= 0) return 0; if (t >= 1) return 1; var t2 = t * t, t3 = t2 * t; return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); } function d3_ease_poly(e) { return function(t) { return Math.pow(t, e); }; } function d3_ease_sin(t) { return 1 - Math.cos(t * halfπ); } function d3_ease_exp(t) { return Math.pow(2, 10 * (t - 1)); } function d3_ease_circle(t) { return 1 - Math.sqrt(1 - t * t); } function d3_ease_elastic(a, p) { var s; if (arguments.length < 2) p = .45; if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); }; } function d3_ease_back(s) { if (!s) s = 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } function d3_ease_bounce(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } d3.interpolateHcl = d3_interpolateHcl; function d3_interpolateHcl(a, b) { a = d3.hcl(a); b = d3.hcl(b); var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; return function(t) { return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; }; } d3.interpolateHsl = d3_interpolateHsl; function d3_interpolateHsl(a, b) { a = d3.hsl(a); b = d3.hsl(b); var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; return function(t) { return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; }; } d3.interpolateLab = d3_interpolateLab; function d3_interpolateLab(a, b) { a = d3.lab(a); b = d3.lab(b); var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; return function(t) { return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; }; } d3.interpolateRound = d3_interpolateRound; function d3_interpolateRound(a, b) { b -= a; return function(t) { return Math.round(a + b * t); }; } d3.transform = function(string) { var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); return (d3.transform = function(string) { if (string != null) { g.setAttribute("transform", string); var t = g.transform.baseVal.consolidate(); } return new d3_transform(t ? t.matrix : d3_transformIdentity); })(string); }; function d3_transform(m) { var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; if (r0[0] * r1[1] < r1[0] * r0[1]) { r0[0] *= -1; r0[1] *= -1; kx *= -1; kz *= -1; } this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; this.translate = [ m.e, m.f ]; this.scale = [ kx, ky ]; this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; } d3_transform.prototype.toString = function() { return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; }; function d3_transformDot(a, b) { return a[0] * b[0] + a[1] * b[1]; } function d3_transformNormalize(a) { var k = Math.sqrt(d3_transformDot(a, a)); if (k) { a[0] /= k; a[1] /= k; } return k; } function d3_transformCombine(a, b, k) { a[0] += k * b[0]; a[1] += k * b[1]; return a; } var d3_transformIdentity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }; d3.interpolateTransform = d3_interpolateTransform; function d3_interpolateTransformPop(s) { return s.length ? s.pop() + "," : ""; } function d3_interpolateTranslate(ta, tb, s, q) { if (ta[0] !== tb[0] || ta[1] !== tb[1]) { var i = s.push("translate(", null, ",", null, ")"); q.push({ i: i - 4, x: d3_interpolateNumber(ta[0], tb[0]) }, { i: i - 2, x: d3_interpolateNumber(ta[1], tb[1]) }); } else if (tb[0] || tb[1]) { s.push("translate(" + tb + ")"); } } function d3_interpolateRotate(ra, rb, s, q) { if (ra !== rb) { if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; q.push({ i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, x: d3_interpolateNumber(ra, rb) }); } else if (rb) { s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); } } function d3_interpolateSkew(wa, wb, s, q) { if (wa !== wb) { q.push({ i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, x: d3_interpolateNumber(wa, wb) }); } else if (wb) { s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); } } function d3_interpolateScale(ka, kb, s, q) { if (ka[0] !== kb[0] || ka[1] !== kb[1]) { var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); q.push({ i: i - 4, x: d3_interpolateNumber(ka[0], kb[0]) }, { i: i - 2, x: d3_interpolateNumber(ka[1], kb[1]) }); } else if (kb[0] !== 1 || kb[1] !== 1) { s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); } } function d3_interpolateTransform(a, b) { var s = [], q = []; a = d3.transform(a), b = d3.transform(b); d3_interpolateTranslate(a.translate, b.translate, s, q); d3_interpolateRotate(a.rotate, b.rotate, s, q); d3_interpolateSkew(a.skew, b.skew, s, q); d3_interpolateScale(a.scale, b.scale, s, q); a = b = null; return function(t) { var i = -1, n = q.length, o; while (++i < n) s[(o = q[i]).i] = o.x(t); return s.join(""); }; } function d3_uninterpolateNumber(a, b) { b = (b -= a = +a) || 1 / b; return function(x) { return (x - a) / b; }; } function d3_uninterpolateClamp(a, b) { b = (b -= a = +a) || 1 / b; return function(x) { return Math.max(0, Math.min(1, (x - a) / b)); }; } d3.layout = {}; d3.layout.bundle = function() { return function(links) { var paths = [], i = -1, n = links.length; while (++i < n) paths.push(d3_layout_bundlePath(links[i])); return paths; }; }; function d3_layout_bundlePath(link) { var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; while (start !== lca) { start = start.parent; points.push(start); } var k = points.length; while (end !== lca) { points.splice(k, 0, end); end = end.parent; } return points; } function d3_layout_bundleAncestors(node) { var ancestors = [], parent = node.parent; while (parent != null) { ancestors.push(node); node = parent; parent = parent.parent; } ancestors.push(node); return ancestors; } function d3_layout_bundleLeastCommonAncestor(a, b) { if (a === b) return a; var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; while (aNode === bNode) { sharedNode = aNode; aNode = aNodes.pop(); bNode = bNodes.pop(); } return sharedNode; } d3.layout.chord = function() { var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; function relayout() { var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; chords = []; groups = []; k = 0, i = -1; while (++i < n) { x = 0, j = -1; while (++j < n) { x += matrix[i][j]; } groupSums.push(x); subgroupIndex.push(d3.range(n)); k += x; } if (sortGroups) { groupIndex.sort(function(a, b) { return sortGroups(groupSums[a], groupSums[b]); }); } if (sortSubgroups) { subgroupIndex.forEach(function(d, i) { d.sort(function(a, b) { return sortSubgroups(matrix[i][a], matrix[i][b]); }); }); } k = (τ - padding * n) / k; x = 0, i = -1; while (++i < n) { x0 = x, j = -1; while (++j < n) { var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; subgroups[di + "-" + dj] = { index: di, subindex: dj, startAngle: a0, endAngle: a1, value: v }; } groups[di] = { index: di, startAngle: x0, endAngle: x, value: groupSums[di] }; x += padding; } i = -1; while (++i < n) { j = i - 1; while (++j < n) { var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; if (source.value || target.value) { chords.push(source.value < target.value ? { source: target, target: source } : { source: source, target: target }); } } } if (sortChords) resort(); } function resort() { chords.sort(function(a, b) { return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); }); } chord.matrix = function(x) { if (!arguments.length) return matrix; n = (matrix = x) && matrix.length; chords = groups = null; return chord; }; chord.padding = function(x) { if (!arguments.length) return padding; padding = x; chords = groups = null; return chord; }; chord.sortGroups = function(x) { if (!arguments.length) return sortGroups; sortGroups = x; chords = groups = null; return chord; }; chord.sortSubgroups = function(x) { if (!arguments.length) return sortSubgroups; sortSubgroups = x; chords = null; return chord; }; chord.sortChords = function(x) { if (!arguments.length) return sortChords; sortChords = x; if (chords) resort(); return chord; }; chord.chords = function() { if (!chords) relayout(); return chords; }; chord.groups = function() { if (!groups) relayout(); return groups; }; return chord; }; d3.layout.force = function() { var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; function repulse(node) { return function(quad, x1, _, x2) { if (quad.point !== node) { var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; if (dw * dw / theta2 < dn) { if (dn < chargeDistance2) { var k = quad.charge / dn; node.px -= dx * k; node.py -= dy * k; } return true; } if (quad.point && dn && dn < chargeDistance2) { var k = quad.pointCharge / dn; node.px -= dx * k; node.py -= dy * k; } } return !quad.charge; }; } force.tick = function() { if ((alpha *= .99) < .005) { timer = null; event.end({ type: "end", alpha: alpha = 0 }); return true; } var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; for (i = 0; i < m; ++i) { o = links[i]; s = o.source; t = o.target; x = t.x - s.x; y = t.y - s.y; if (l = x * x + y * y) { l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; x *= l; y *= l; t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5); t.y -= y * k; s.x += x * (k = 1 - k); s.y += y * k; } } if (k = alpha * gravity) { x = size[0] / 2; y = size[1] / 2; i = -1; if (k) while (++i < n) { o = nodes[i]; o.x += (x - o.x) * k; o.y += (y - o.y) * k; } } if (charge) { d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); i = -1; while (++i < n) { if (!(o = nodes[i]).fixed) { q.visit(repulse(o)); } } } i = -1; while (++i < n) { o = nodes[i]; if (o.fixed) { o.x = o.px; o.y = o.py; } else { o.x -= (o.px - (o.px = o.x)) * friction; o.y -= (o.py - (o.py = o.y)) * friction; } } event.tick({ type: "tick", alpha: alpha }); }; force.nodes = function(x) { if (!arguments.length) return nodes; nodes = x; return force; }; force.links = function(x) { if (!arguments.length) return links; links = x; return force; }; force.size = function(x) { if (!arguments.length) return size; size = x; return force; }; force.linkDistance = function(x) { if (!arguments.length) return linkDistance; linkDistance = typeof x === "function" ? x : +x; return force; }; force.distance = force.linkDistance; force.linkStrength = function(x) { if (!arguments.length) return linkStrength; linkStrength = typeof x === "function" ? x : +x; return force; }; force.friction = function(x) { if (!arguments.length) return friction; friction = +x; return force; }; force.charge = function(x) { if (!arguments.length) return charge; charge = typeof x === "function" ? x : +x; return force; }; force.chargeDistance = function(x) { if (!arguments.length) return Math.sqrt(chargeDistance2); chargeDistance2 = x * x; return force; }; force.gravity = function(x) { if (!arguments.length) return gravity; gravity = +x; return force; }; force.theta = function(x) { if (!arguments.length) return Math.sqrt(theta2); theta2 = x * x; return force; }; force.alpha = function(x) { if (!arguments.length) return alpha; x = +x; if (alpha) { if (x > 0) { alpha = x; } else { timer.c = null, timer.t = NaN, timer = null; event.end({ type: "end", alpha: alpha = 0 }); } } else if (x > 0) { event.start({ type: "start", alpha: alpha = x }); timer = d3_timer(force.tick); } return force; }; force.start = function() { var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; for (i = 0; i < n; ++i) { (o = nodes[i]).index = i; o.weight = 0; } for (i = 0; i < m; ++i) { o = links[i]; if (typeof o.source == "number") o.source = nodes[o.source]; if (typeof o.target == "number") o.target = nodes[o.target]; ++o.source.weight; ++o.target.weight; } for (i = 0; i < n; ++i) { o = nodes[i]; if (isNaN(o.x)) o.x = position("x", w); if (isNaN(o.y)) o.y = position("y", h); if (isNaN(o.px)) o.px = o.x; if (isNaN(o.py)) o.py = o.y; } distances = []; if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; strengths = []; if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; charges = []; if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; function position(dimension, size) { if (!neighbors) { neighbors = new Array(n); for (j = 0; j < n; ++j) { neighbors[j] = []; } for (j = 0; j < m; ++j) { var o = links[j]; neighbors[o.source.index].push(o.target); neighbors[o.target.index].push(o.source); } } var candidates = neighbors[i], j = -1, l = candidates.length, x; while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; return Math.random() * size; } return force.resume(); }; force.resume = function() { return force.alpha(.1); }; force.stop = function() { return force.alpha(0); }; force.drag = function() { if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); if (!arguments.length) return drag; this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); }; function dragmove(d) { d.px = d3.event.x, d.py = d3.event.y; force.resume(); } return d3.rebind(force, event, "on"); }; function d3_layout_forceDragstart(d) { d.fixed |= 2; } function d3_layout_forceDragend(d) { d.fixed &= ~6; } function d3_layout_forceMouseover(d) { d.fixed |= 4; d.px = d.x, d.py = d.y; } function d3_layout_forceMouseout(d) { d.fixed &= ~4; } function d3_layout_forceAccumulate(quad, alpha, charges) { var cx = 0, cy = 0; quad.charge = 0; if (!quad.leaf) { var nodes = quad.nodes, n = nodes.length, i = -1, c; while (++i < n) { c = nodes[i]; if (c == null) continue; d3_layout_forceAccumulate(c, alpha, charges); quad.charge += c.charge; cx += c.charge * c.cx; cy += c.charge * c.cy; } } if (quad.point) { if (!quad.leaf) { quad.point.x += Math.random() - .5; quad.point.y += Math.random() - .5; } var k = alpha * charges[quad.point.index]; quad.charge += quad.pointCharge = k; cx += k * quad.point.x; cy += k * quad.point.y; } quad.cx = cx / quad.charge; quad.cy = cy / quad.charge; } var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; d3.layout.hierarchy = function() { var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; function hierarchy(root) { var stack = [ root ], nodes = [], node; root.depth = 0; while ((node = stack.pop()) != null) { nodes.push(node); if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { var n, childs, child; while (--n >= 0) { stack.push(child = childs[n]); child.parent = node; child.depth = node.depth + 1; } if (value) node.value = 0; node.children = childs; } else { if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; delete node.children; } } d3_layout_hierarchyVisitAfter(root, function(node) { var childs, parent; if (sort && (childs = node.children)) childs.sort(sort); if (value && (parent = node.parent)) parent.value += node.value; }); return nodes; } hierarchy.sort = function(x) { if (!arguments.length) return sort; sort = x; return hierarchy; }; hierarchy.children = function(x) { if (!arguments.length) return children; children = x; return hierarchy; }; hierarchy.value = function(x) { if (!arguments.length) return value; value = x; return hierarchy; }; hierarchy.revalue = function(root) { if (value) { d3_layout_hierarchyVisitBefore(root, function(node) { if (node.children) node.value = 0; }); d3_layout_hierarchyVisitAfter(root, function(node) { var parent; if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; if (parent = node.parent) parent.value += node.value; }); } return root; }; return hierarchy; }; function d3_layout_hierarchyRebind(object, hierarchy) { d3.rebind(object, hierarchy, "sort", "children", "value"); object.nodes = object; object.links = d3_layout_hierarchyLinks; return object; } function d3_layout_hierarchyVisitBefore(node, callback) { var nodes = [ node ]; while ((node = nodes.pop()) != null) { callback(node); if ((children = node.children) && (n = children.length)) { var n, children; while (--n >= 0) nodes.push(children[n]); } } } function d3_layout_hierarchyVisitAfter(node, callback) { var nodes = [ node ], nodes2 = []; while ((node = nodes.pop()) != null) { nodes2.push(node); if ((children = node.children) && (n = children.length)) { var i = -1, n, children; while (++i < n) nodes.push(children[i]); } } while ((node = nodes2.pop()) != null) { callback(node); } } function d3_layout_hierarchyChildren(d) { return d.children; } function d3_layout_hierarchyValue(d) { return d.value; } function d3_layout_hierarchySort(a, b) { return b.value - a.value; } function d3_layout_hierarchyLinks(nodes) { return d3.merge(nodes.map(function(parent) { return (parent.children || []).map(function(child) { return { source: parent, target: child }; }); })); } d3.layout.partition = function() { var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; function position(node, x, dx, dy) { var children = node.children; node.x = x; node.y = node.depth * dy; node.dx = dx; node.dy = dy; if (children && (n = children.length)) { var i = -1, n, c, d; dx = node.value ? dx / node.value : 0; while (++i < n) { position(c = children[i], x, d = c.value * dx, dy); x += d; } } } function depth(node) { var children = node.children, d = 0; if (children && (n = children.length)) { var i = -1, n; while (++i < n) d = Math.max(d, depth(children[i])); } return 1 + d; } function partition(d, i) { var nodes = hierarchy.call(this, d, i); position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); return nodes; } partition.size = function(x) { if (!arguments.length) return size; size = x; return partition; }; return d3_layout_hierarchyRebind(partition, hierarchy); }; d3.layout.pie = function() { var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; function pie(data) { var n = data.length, values = data.map(function(d, i) { return +value.call(pie, d, i); }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v; if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { return values[j] - values[i]; } : function(i, j) { return sort(data[i], data[j]); }); index.forEach(function(i) { arcs[i] = { data: data[i], value: v = values[i], startAngle: a, endAngle: a += v * k + pa, padAngle: p }; }); return arcs; } pie.value = function(_) { if (!arguments.length) return value; value = _; return pie; }; pie.sort = function(_) { if (!arguments.length) return sort; sort = _; return pie; }; pie.startAngle = function(_) { if (!arguments.length) return startAngle; startAngle = _; return pie; }; pie.endAngle = function(_) { if (!arguments.length) return endAngle; endAngle = _; return pie; }; pie.padAngle = function(_) { if (!arguments.length) return padAngle; padAngle = _; return pie; }; return pie; }; var d3_layout_pieSortByValue = {}; d3.layout.stack = function() { var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; function stack(data, index) { if (!(n = data.length)) return data; var series = data.map(function(d, i) { return values.call(stack, d, i); }); var points = series.map(function(d) { return d.map(function(v, i) { return [ x.call(stack, v, i), y.call(stack, v, i) ]; }); }); var orders = order.call(stack, points, index); series = d3.permute(series, orders); points = d3.permute(points, orders); var offsets = offset.call(stack, points, index); var m = series[0].length, n, i, j, o; for (j = 0; j < m; ++j) { out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); for (i = 1; i < n; ++i) { out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); } } return data; } stack.values = function(x) { if (!arguments.length) return values; values = x; return stack; }; stack.order = function(x) { if (!arguments.length) return order; order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; return stack; }; stack.offset = function(x) { if (!arguments.length) return offset; offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; return stack; }; stack.x = function(z) { if (!arguments.length) return x; x = z; return stack; }; stack.y = function(z) { if (!arguments.length) return y; y = z; return stack; }; stack.out = function(z) { if (!arguments.length) return out; out = z; return stack; }; return stack; }; function d3_layout_stackX(d) { return d.x; } function d3_layout_stackY(d) { return d.y; } function d3_layout_stackOut(d, y0, y) { d.y0 = y0; d.y = y; } var d3_layout_stackOrders = d3.map({ "inside-out": function(data) { var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { return max[a] - max[b]; }), top = 0, bottom = 0, tops = [], bottoms = []; for (i = 0; i < n; ++i) { j = index[i]; if (top < bottom) { top += sums[j]; tops.push(j); } else { bottom += sums[j]; bottoms.push(j); } } return bottoms.reverse().concat(tops); }, reverse: function(data) { return d3.range(data.length).reverse(); }, "default": d3_layout_stackOrderDefault }); var d3_layout_stackOffsets = d3.map({ silhouette: function(data) { var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; for (j = 0; j < m; ++j) { for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; if (o > max) max = o; sums.push(o); } for (j = 0; j < m; ++j) { y0[j] = (max - sums[j]) / 2; } return y0; }, wiggle: function(data) { var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; y0[0] = o = o0 = 0; for (j = 1; j < m; ++j) { for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; } s2 += s3 * data[i][j][1]; } y0[j] = o -= s1 ? s2 / s1 * dx : 0; if (o < o0) o0 = o; } for (j = 0; j < m; ++j) y0[j] -= o0; return y0; }, expand: function(data) { var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; for (j = 0; j < m; ++j) { for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; } for (j = 0; j < m; ++j) y0[j] = 0; return y0; }, zero: d3_layout_stackOffsetZero }); function d3_layout_stackOrderDefault(data) { return d3.range(data.length); } function d3_layout_stackOffsetZero(data) { var j = -1, m = data[0].length, y0 = []; while (++j < m) y0[j] = 0; return y0; } function d3_layout_stackMaxIndex(array) { var i = 1, j = 0, v = array[0][1], k, n = array.length; for (;i < n; ++i) { if ((k = array[i][1]) > v) { j = i; v = k; } } return j; } function d3_layout_stackReduceSum(d) { return d.reduce(d3_layout_stackSum, 0); } function d3_layout_stackSum(p, d) { return p + d[1]; } d3.layout.histogram = function() { var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; function histogram(data, i) { var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; while (++i < m) { bin = bins[i] = []; bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); bin.y = 0; } if (m > 0) { i = -1; while (++i < n) { x = values[i]; if (x >= range[0] && x <= range[1]) { bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; bin.y += k; bin.push(data[i]); } } } return bins; } histogram.value = function(x) { if (!arguments.length) return valuer; valuer = x; return histogram; }; histogram.range = function(x) { if (!arguments.length) return ranger; ranger = d3_functor(x); return histogram; }; histogram.bins = function(x) { if (!arguments.length) return binner; binner = typeof x === "number" ? function(range) { return d3_layout_histogramBinFixed(range, x); } : d3_functor(x); return histogram; }; histogram.frequency = function(x) { if (!arguments.length) return frequency; frequency = !!x; return histogram; }; return histogram; }; function d3_layout_histogramBinSturges(range, values) { return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); } function d3_layout_histogramBinFixed(range, n) { var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; while (++x <= n) f[x] = m * x + b; return f; } function d3_layout_histogramRange(values) { return [ d3.min(values), d3.max(values) ]; } d3.layout.pack = function() { var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; function pack(d, i) { var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { return radius; }; root.x = root.y = 0; d3_layout_hierarchyVisitAfter(root, function(d) { d.r = +r(d.value); }); d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); if (padding) { var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; d3_layout_hierarchyVisitAfter(root, function(d) { d.r += dr; }); d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); d3_layout_hierarchyVisitAfter(root, function(d) { d.r -= dr; }); } d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); return nodes; } pack.size = function(_) { if (!arguments.length) return size; size = _; return pack; }; pack.radius = function(_) { if (!arguments.length) return radius; radius = _ == null || typeof _ === "function" ? _ : +_; return pack; }; pack.padding = function(_) { if (!arguments.length) return padding; padding = +_; return pack; }; return d3_layout_hierarchyRebind(pack, hierarchy); }; function d3_layout_packSort(a, b) { return a.value - b.value; } function d3_layout_packInsert(a, b) { var c = a._pack_next; a._pack_next = b; b._pack_prev = a; b._pack_next = c; c._pack_prev = b; } function d3_layout_packSplice(a, b) { a._pack_next = b; b._pack_prev = a; } function d3_layout_packIntersects(a, b) { var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; return .999 * dr * dr > dx * dx + dy * dy; } function d3_layout_packSiblings(node) { if (!(nodes = node.children) || !(n = nodes.length)) return; var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; function bound(node) { xMin = Math.min(node.x - node.r, xMin); xMax = Math.max(node.x + node.r, xMax); yMin = Math.min(node.y - node.r, yMin); yMax = Math.max(node.y + node.r, yMax); } nodes.forEach(d3_layout_packLink); a = nodes[0]; a.x = -a.r; a.y = 0; bound(a); if (n > 1) { b = nodes[1]; b.x = b.r; b.y = 0; bound(b); if (n > 2) { c = nodes[2]; d3_layout_packPlace(a, b, c); bound(c); d3_layout_packInsert(a, c); a._pack_prev = c; d3_layout_packInsert(c, b); b = a._pack_next; for (i = 3; i < n; i++) { d3_layout_packPlace(a, b, c = nodes[i]); var isect = 0, s1 = 1, s2 = 1; for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { if (d3_layout_packIntersects(j, c)) { isect = 1; break; } } if (isect == 1) { for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { if (d3_layout_packIntersects(k, c)) { break; } } } if (isect) { if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); i--; } else { d3_layout_packInsert(a, c); b = c; bound(c); } } } } var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; for (i = 0; i < n; i++) { c = nodes[i]; c.x -= cx; c.y -= cy; cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); } node.r = cr; nodes.forEach(d3_layout_packUnlink); } function d3_layout_packLink(node) { node._pack_next = node._pack_prev = node; } function d3_layout_packUnlink(node) { delete node._pack_next; delete node._pack_prev; } function d3_layout_packTransform(node, x, y, k) { var children = node.children; node.x = x += k * node.x; node.y = y += k * node.y; node.r *= k; if (children) { var i = -1, n = children.length; while (++i < n) d3_layout_packTransform(children[i], x, y, k); } } function d3_layout_packPlace(a, b, c) { var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; if (db && (dx || dy)) { var da = b.r + c.r, dc = dx * dx + dy * dy; da *= da; db *= db; var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); c.x = a.x + x * dx + y * dy; c.y = a.y + x * dy - y * dx; } else { c.x = a.x + db; c.y = a.y; } } d3.layout.tree = function() { var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; function tree(d, i) { var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; d3_layout_hierarchyVisitBefore(root1, secondWalk); if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { var left = root0, right = root0, bottom = root0; d3_layout_hierarchyVisitBefore(root0, function(node) { if (node.x < left.x) left = node; if (node.x > right.x) right = node; if (node.depth > bottom.depth) bottom = node; }); var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); d3_layout_hierarchyVisitBefore(root0, function(node) { node.x = (node.x + tx) * kx; node.y = node.depth * ky; }); } return nodes; } function wrapTree(root0) { var root1 = { A: null, children: [ root0 ] }, queue = [ root1 ], node1; while ((node1 = queue.pop()) != null) { for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { queue.push((children[i] = child = { _: children[i], parent: node1, children: (child = children[i].children) && child.slice() || [], A: null, a: null, z: 0, m: 0, c: 0, s: 0, t: null, i: i }).a = child); } } return root1.children[0]; } function firstWalk(v) { var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; if (children.length) { d3_layout_treeShift(v); var midpoint = (children[0].z + children[children.length - 1].z) / 2; if (w) { v.z = w.z + separation(v._, w._); v.m = v.z - midpoint; } else { v.z = midpoint; } } else if (w) { v.z = w.z + separation(v._, w._); } v.parent.A = apportion(v, w, v.parent.A || siblings[0]); } function secondWalk(v) { v._.x = v.z + v.parent.m; v.m += v.parent.m; } function apportion(v, w, ancestor) { if (w) { var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { vom = d3_layout_treeLeft(vom); vop = d3_layout_treeRight(vop); vop.a = v; shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); if (shift > 0) { d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); sip += shift; sop += shift; } sim += vim.m; sip += vip.m; som += vom.m; sop += vop.m; } if (vim && !d3_layout_treeRight(vop)) { vop.t = vim; vop.m += sim - sop; } if (vip && !d3_layout_treeLeft(vom)) { vom.t = vip; vom.m += sip - som; ancestor = v; } } return ancestor; } function sizeNode(node) { node.x *= size[0]; node.y = node.depth * size[1]; } tree.separation = function(x) { if (!arguments.length) return separation; separation = x; return tree; }; tree.size = function(x) { if (!arguments.length) return nodeSize ? null : size; nodeSize = (size = x) == null ? sizeNode : null; return tree; }; tree.nodeSize = function(x) { if (!arguments.length) return nodeSize ? size : null; nodeSize = (size = x) == null ? null : sizeNode; return tree; }; return d3_layout_hierarchyRebind(tree, hierarchy); }; function d3_layout_treeSeparation(a, b) { return a.parent == b.parent ? 1 : 2; } function d3_layout_treeLeft(v) { var children = v.children; return children.length ? children[0] : v.t; } function d3_layout_treeRight(v) { var children = v.children, n; return (n = children.length) ? children[n - 1] : v.t; } function d3_layout_treeMove(wm, wp, shift) { var change = shift / (wp.i - wm.i); wp.c -= change; wp.s += shift; wm.c += change; wp.z += shift; wp.m += shift; } function d3_layout_treeShift(v) { var shift = 0, change = 0, children = v.children, i = children.length, w; while (--i >= 0) { w = children[i]; w.z += shift; w.m += shift; shift += w.s + (change += w.c); } } function d3_layout_treeAncestor(vim, v, ancestor) { return vim.a.parent === v.parent ? vim.a : ancestor; } d3.layout.cluster = function() { var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; function cluster(d, i) { var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; d3_layout_hierarchyVisitAfter(root, function(node) { var children = node.children; if (children && children.length) { node.x = d3_layout_clusterX(children); node.y = d3_layout_clusterY(children); } else { node.x = previousNode ? x += separation(node, previousNode) : 0; node.y = 0; previousNode = node; } }); var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { node.x = (node.x - root.x) * size[0]; node.y = (root.y - node.y) * size[1]; } : function(node) { node.x = (node.x - x0) / (x1 - x0) * size[0]; node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; }); return nodes; } cluster.separation = function(x) { if (!arguments.length) return separation; separation = x; return cluster; }; cluster.size = function(x) { if (!arguments.length) return nodeSize ? null : size; nodeSize = (size = x) == null; return cluster; }; cluster.nodeSize = function(x) { if (!arguments.length) return nodeSize ? size : null; nodeSize = (size = x) != null; return cluster; }; return d3_layout_hierarchyRebind(cluster, hierarchy); }; function d3_layout_clusterY(children) { return 1 + d3.max(children, function(child) { return child.y; }); } function d3_layout_clusterX(children) { return children.reduce(function(x, child) { return x + child.x; }, 0) / children.length; } function d3_layout_clusterLeft(node) { var children = node.children; return children && children.length ? d3_layout_clusterLeft(children[0]) : node; } function d3_layout_clusterRight(node) { var children = node.children, n; return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; } d3.layout.treemap = function() { var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); function scale(children, k) { var i = -1, n = children.length, child, area; while (++i < n) { area = (child = children[i]).value * (k < 0 ? 0 : k); child.area = isNaN(area) || area <= 0 ? 0 : area; } } function squarify(node) { var children = node.children; if (children && children.length) { var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; scale(remaining, rect.dx * rect.dy / node.value); row.area = 0; while ((n = remaining.length) > 0) { row.push(child = remaining[n - 1]); row.area += child.area; if (mode !== "squarify" || (score = worst(row, u)) <= best) { remaining.pop(); best = score; } else { row.area -= row.pop().area; position(row, u, rect, false); u = Math.min(rect.dx, rect.dy); row.length = row.area = 0; best = Infinity; } } if (row.length) { position(row, u, rect, true); row.length = row.area = 0; } children.forEach(squarify); } } function stickify(node) { var children = node.children; if (children && children.length) { var rect = pad(node), remaining = children.slice(), child, row = []; scale(remaining, rect.dx * rect.dy / node.value); row.area = 0; while (child = remaining.pop()) { row.push(child); row.area += child.area; if (child.z != null) { position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); row.length = row.area = 0; } } children.forEach(stickify); } } function worst(row, u) { var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; while (++i < n) { if (!(r = row[i].area)) continue; if (r < rmin) rmin = r; if (r > rmax) rmax = r; } s *= s; u *= u; return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; } function position(row, u, rect, flush) { var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; if (u == rect.dx) { if (flush || v > rect.dy) v = rect.dy; while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dy = v; x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); } o.z = true; o.dx += rect.x + rect.dx - x; rect.y += v; rect.dy -= v; } else { if (flush || v > rect.dx) v = rect.dx; while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dx = v; y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); } o.z = false; o.dy += rect.y + rect.dy - y; rect.x += v; rect.dx -= v; } } function treemap(d) { var nodes = stickies || hierarchy(d), root = nodes[0]; root.x = root.y = 0; if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; if (stickies) hierarchy.revalue(root); scale([ root ], root.dx * root.dy / root.value); (stickies ? stickify : squarify)(root); if (sticky) stickies = nodes; return nodes; } treemap.size = function(x) { if (!arguments.length) return size; size = x; return treemap; }; treemap.padding = function(x) { if (!arguments.length) return padding; function padFunction(node) { var p = x.call(treemap, node, node.depth); return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); } function padConstant(node) { return d3_layout_treemapPad(node, x); } var type; pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], padConstant) : padConstant; return treemap; }; treemap.round = function(x) { if (!arguments.length) return round != Number; round = x ? Math.round : Number; return treemap; }; treemap.sticky = function(x) { if (!arguments.length) return sticky; sticky = x; stickies = null; return treemap; }; treemap.ratio = function(x) { if (!arguments.length) return ratio; ratio = x; return treemap; }; treemap.mode = function(x) { if (!arguments.length) return mode; mode = x + ""; return treemap; }; return d3_layout_hierarchyRebind(treemap, hierarchy); }; function d3_layout_treemapPadNull(node) { return { x: node.x, y: node.y, dx: node.dx, dy: node.dy }; } function d3_layout_treemapPad(node, padding) { var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; if (dx < 0) { x += dx / 2; dx = 0; } if (dy < 0) { y += dy / 2; dy = 0; } return { x: x, y: y, dx: dx, dy: dy }; } d3.random = { normal: function(µ, σ) { var n = arguments.length; if (n < 2) σ = 1; if (n < 1) µ = 0; return function() { var x, y, r; do { x = Math.random() * 2 - 1; y = Math.random() * 2 - 1; r = x * x + y * y; } while (!r || r > 1); return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); }; }, logNormal: function() { var random = d3.random.normal.apply(d3, arguments); return function() { return Math.exp(random()); }; }, bates: function(m) { var random = d3.random.irwinHall(m); return function() { return random() / m; }; }, irwinHall: function(m) { return function() { for (var s = 0, j = 0; j < m; j++) s += Math.random(); return s; }; } }; d3.scale = {}; function d3_scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [ start, stop ] : [ stop, start ]; } function d3_scaleRange(scale) { return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); } function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); return function(x) { return i(u(x)); }; } function d3_scale_nice(domain, nice) { var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; if (x1 < x0) { dx = i0, i0 = i1, i1 = dx; dx = x0, x0 = x1, x1 = dx; } domain[i0] = nice.floor(x0); domain[i1] = nice.ceil(x1); return domain; } function d3_scale_niceStep(step) { return step ? { floor: function(x) { return Math.floor(x / step) * step; }, ceil: function(x) { return Math.ceil(x / step) * step; } } : d3_scale_niceIdentity; } var d3_scale_niceIdentity = { floor: d3_identity, ceil: d3_identity }; function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; if (domain[k] < domain[0]) { domain = domain.slice().reverse(); range = range.slice().reverse(); } while (++j <= k) { u.push(uninterpolate(domain[j - 1], domain[j])); i.push(interpolate(range[j - 1], range[j])); } return function(x) { var j = d3.bisect(domain, x, 1, k) - 1; return i[j](u[j](x)); }; } d3.scale.linear = function() { return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); }; function d3_scale_linear(domain, range, interpolate, clamp) { var output, input; function rescale() { var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; output = linear(domain, range, uninterpolate, interpolate); input = linear(range, domain, uninterpolate, d3_interpolate); return scale; } function scale(x) { return output(x); } scale.invert = function(y) { return input(y); }; scale.domain = function(x) { if (!arguments.length) return domain; domain = x.map(Number); return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.rangeRound = function(x) { return scale.range(x).interpolate(d3_interpolateRound); }; scale.clamp = function(x) { if (!arguments.length) return clamp; clamp = x; return rescale(); }; scale.interpolate = function(x) { if (!arguments.length) return interpolate; interpolate = x; return rescale(); }; scale.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; scale.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; scale.nice = function(m) { d3_scale_linearNice(domain, m); return rescale(); }; scale.copy = function() { return d3_scale_linear(domain, range, interpolate, clamp); }; return rescale(); } function d3_scale_linearRebind(scale, linear) { return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } function d3_scale_linearNice(domain, m) { d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); return domain; } function d3_scale_linearTickRange(domain, m) { if (m == null) m = 10; var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; extent[0] = Math.ceil(extent[0] / step) * step; extent[1] = Math.floor(extent[1] / step) * step + step * .5; extent[2] = step; return extent; } function d3_scale_linearTicks(domain, m) { return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); } function d3_scale_linearTickFormat(domain, m, format) { var range = d3_scale_linearTickRange(domain, m); if (format) { var match = d3_format_re.exec(format); match.shift(); if (match[8] === "s") { var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); match[8] = "f"; format = d3.format(match.join("")); return function(d) { return format(prefix.scale(d)) + prefix.symbol; }; } if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); format = match.join(""); } else { format = ",." + d3_scale_linearPrecision(range[2]) + "f"; } return d3.format(format); } var d3_scale_linearFormatSignificant = { s: 1, g: 1, p: 1, r: 1, e: 1 }; function d3_scale_linearPrecision(value) { return -Math.floor(Math.log(value) / Math.LN10 + .01); } function d3_scale_linearFormatPrecision(type, range) { var p = d3_scale_linearPrecision(range[2]); return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; } d3.scale.log = function() { return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); }; function d3_scale_log(linear, base, positive, domain) { function log(x) { return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); } function pow(x) { return positive ? Math.pow(base, x) : -Math.pow(base, -x); } function scale(x) { return linear(log(x)); } scale.invert = function(x) { return pow(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return domain; positive = x[0] >= 0; linear.domain((domain = x.map(Number)).map(log)); return scale; }; scale.base = function(_) { if (!arguments.length) return base; base = +_; linear.domain(domain.map(log)); return scale; }; scale.nice = function() { var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); linear.domain(niced); domain = niced.map(pow); return scale; }; scale.ticks = function() { var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; if (isFinite(j - i)) { if (positive) { for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); ticks.push(pow(i)); } else { ticks.push(pow(i)); for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); } for (i = 0; ticks[i] < u; i++) {} for (j = ticks.length; ticks[j - 1] > v; j--) {} ticks = ticks.slice(i, j); } return ticks; }; scale.tickFormat = function(n, format) { if (!arguments.length) return d3_scale_logFormat; if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); var k = Math.max(1, base * n / scale.ticks().length); return function(d) { var i = d / pow(Math.round(log(d))); if (i * base < base - .5) i *= base; return i <= k ? format(d) : ""; }; }; scale.copy = function() { return d3_scale_log(linear.copy(), base, positive, domain); }; return d3_scale_linearRebind(scale, linear); } var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { floor: function(x) { return -Math.ceil(-x); }, ceil: function(x) { return -Math.floor(-x); } }; d3.scale.pow = function() { return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); }; function d3_scale_pow(linear, exponent, domain) { var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); function scale(x) { return linear(powp(x)); } scale.invert = function(x) { return powb(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return domain; linear.domain((domain = x.map(Number)).map(powp)); return scale; }; scale.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; scale.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; scale.nice = function(m) { return scale.domain(d3_scale_linearNice(domain, m)); }; scale.exponent = function(x) { if (!arguments.length) return exponent; powp = d3_scale_powPow(exponent = x); powb = d3_scale_powPow(1 / exponent); linear.domain(domain.map(powp)); return scale; }; scale.copy = function() { return d3_scale_pow(linear.copy(), exponent, domain); }; return d3_scale_linearRebind(scale, linear); } function d3_scale_powPow(e) { return function(x) { return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); }; } d3.scale.sqrt = function() { return d3.scale.pow().exponent(.5); }; d3.scale.ordinal = function() { return d3_scale_ordinal([], { t: "range", a: [ [] ] }); }; function d3_scale_ordinal(domain, ranger) { var index, range, rangeBand; function scale(x) { return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; } function steps(start, step) { return d3.range(domain.length).map(function(i) { return start + step * i; }); } scale.domain = function(x) { if (!arguments.length) return domain; domain = []; index = new d3_Map(); var i = -1, n = x.length, xi; while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); return scale[ranger.t].apply(scale, ranger.a); }; scale.range = function(x) { if (!arguments.length) return range; range = x; rangeBand = 0; ranger = { t: "range", a: arguments }; return scale; }; scale.rangePoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain.length - 1 + padding); range = steps(start + step * padding / 2, step); rangeBand = 0; ranger = { t: "rangePoints", a: arguments }; return scale; }; scale.rangeRoundPoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain.length - 1 + padding) | 0; range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); rangeBand = 0; ranger = { t: "rangeRoundPoints", a: arguments }; return scale; }; scale.rangeBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); range = steps(start + step * outerPadding, step); if (reverse) range.reverse(); rangeBand = step * (1 - padding); ranger = { t: "rangeBands", a: arguments }; return scale; }; scale.rangeRoundBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); if (reverse) range.reverse(); rangeBand = Math.round(step * (1 - padding)); ranger = { t: "rangeRoundBands", a: arguments }; return scale; }; scale.rangeBand = function() { return rangeBand; }; scale.rangeExtent = function() { return d3_scaleExtent(ranger.a[0]); }; scale.copy = function() { return d3_scale_ordinal(domain, ranger); }; return scale.domain(domain); } d3.scale.category10 = function() { return d3.scale.ordinal().range(d3_category10); }; d3.scale.category20 = function() { return d3.scale.ordinal().range(d3_category20); }; d3.scale.category20b = function() { return d3.scale.ordinal().range(d3_category20b); }; d3.scale.category20c = function() { return d3.scale.ordinal().range(d3_category20c); }; var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); d3.scale.quantile = function() { return d3_scale_quantile([], []); }; function d3_scale_quantile(domain, range) { var thresholds; function rescale() { var k = 0, q = range.length; thresholds = []; while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); return scale; } function scale(x) { if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; } scale.domain = function(x) { if (!arguments.length) return domain; domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.quantiles = function() { return thresholds; }; scale.invertExtent = function(y) { y = range.indexOf(y); return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; }; scale.copy = function() { return d3_scale_quantile(domain, range); }; return rescale(); } d3.scale.quantize = function() { return d3_scale_quantize(0, 1, [ 0, 1 ]); }; function d3_scale_quantize(x0, x1, range) { var kx, i; function scale(x) { return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; } function rescale() { kx = range.length / (x1 - x0); i = range.length - 1; return scale; } scale.domain = function(x) { if (!arguments.length) return [ x0, x1 ]; x0 = +x[0]; x1 = +x[x.length - 1]; return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.invertExtent = function(y) { y = range.indexOf(y); y = y < 0 ? NaN : y / kx + x0; return [ y, y + 1 / kx ]; }; scale.copy = function() { return d3_scale_quantize(x0, x1, range); }; return rescale(); } d3.scale.threshold = function() { return d3_scale_threshold([ .5 ], [ 0, 1 ]); }; function d3_scale_threshold(domain, range) { function scale(x) { if (x <= x) return range[d3.bisect(domain, x)]; } scale.domain = function(_) { if (!arguments.length) return domain; domain = _; return scale; }; scale.range = function(_) { if (!arguments.length) return range; range = _; return scale; }; scale.invertExtent = function(y) { y = range.indexOf(y); return [ domain[y - 1], domain[y] ]; }; scale.copy = function() { return d3_scale_threshold(domain, range); }; return scale; } d3.scale.identity = function() { return d3_scale_identity([ 0, 1 ]); }; function d3_scale_identity(domain) { function identity(x) { return +x; } identity.invert = identity; identity.domain = identity.range = function(x) { if (!arguments.length) return domain; domain = x.map(identity); return identity; }; identity.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; identity.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; identity.copy = function() { return d3_scale_identity(domain); }; return identity; } d3.svg = {}; function d3_zero() { return 0; } d3.svg.arc = function() { var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; function arc() { var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; if (r1 < r0) rc = r1, r1 = r0, r0 = rc; if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); if (!cw) p1 *= -1; if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); } if (r1) { x0 = r1 * Math.cos(a0 + p1); y0 = r1 * Math.sin(a0 + p1); x1 = r1 * Math.cos(a1 - p1); y1 = r1 * Math.sin(a1 - p1); var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { var h1 = (a0 + a1) / 2; x0 = r1 * Math.cos(h1); y0 = r1 * Math.sin(h1); x1 = y1 = null; } } else { x0 = y0 = 0; } if (r0) { x2 = r0 * Math.cos(a1 - p0); y2 = r0 * Math.sin(a1 - p0); x3 = r0 * Math.cos(a0 + p0); y3 = r0 * Math.sin(a0 + p0); var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { var h0 = (a0 + a1) / 2; x2 = r0 * Math.cos(h0); y2 = r0 * Math.sin(h0); x3 = y3 = null; } } else { x2 = y2 = 0; } if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { cr = r0 < r1 ^ cw ? 0 : 1; var rc1 = rc, rc0 = rc; if (da < π) { var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); } if (x1 != null) { var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); if (rc === rc1) { path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); } else { path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); } } else { path.push("M", x0, ",", y0); } if (x3 != null) { var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); if (rc === rc0) { path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); } else { path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); } } else { path.push("L", x2, ",", y2); } } else { path.push("M", x0, ",", y0); if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); path.push("L", x2, ",", y2); if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); } path.push("Z"); return path.join(""); } function circleSegment(r1, cw) { return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; } arc.innerRadius = function(v) { if (!arguments.length) return innerRadius; innerRadius = d3_functor(v); return arc; }; arc.outerRadius = function(v) { if (!arguments.length) return outerRadius; outerRadius = d3_functor(v); return arc; }; arc.cornerRadius = function(v) { if (!arguments.length) return cornerRadius; cornerRadius = d3_functor(v); return arc; }; arc.padRadius = function(v) { if (!arguments.length) return padRadius; padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); return arc; }; arc.startAngle = function(v) { if (!arguments.length) return startAngle; startAngle = d3_functor(v); return arc; }; arc.endAngle = function(v) { if (!arguments.length) return endAngle; endAngle = d3_functor(v); return arc; }; arc.padAngle = function(v) { if (!arguments.length) return padAngle; padAngle = d3_functor(v); return arc; }; arc.centroid = function() { var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; return [ Math.cos(a) * r, Math.sin(a) * r ]; }; return arc; }; var d3_svg_arcAuto = "auto"; function d3_svg_arcInnerRadius(d) { return d.innerRadius; } function d3_svg_arcOuterRadius(d) { return d.outerRadius; } function d3_svg_arcStartAngle(d) { return d.startAngle; } function d3_svg_arcEndAngle(d) { return d.endAngle; } function d3_svg_arcPadAngle(d) { return d && d.padAngle; } function d3_svg_arcSweep(x0, y0, x1, y1) { return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; } function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; } function d3_svg_line(projection) { var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; function line(data) { var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); function segment() { segments.push("M", interpolate(projection(points), tension)); } while (++i < n) { if (defined.call(this, d = data[i], i)) { points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); } else if (points.length) { segment(); points = []; } } if (points.length) segment(); return segments.length ? segments.join("") : null; } line.x = function(_) { if (!arguments.length) return x; x = _; return line; }; line.y = function(_) { if (!arguments.length) return y; y = _; return line; }; line.defined = function(_) { if (!arguments.length) return defined; defined = _; return line; }; line.interpolate = function(_) { if (!arguments.length) return interpolateKey; if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; return line; }; line.tension = function(_) { if (!arguments.length) return tension; tension = _; return line; }; return line; } d3.svg.line = function() { return d3_svg_line(d3_identity); }; var d3_svg_lineInterpolators = d3.map({ linear: d3_svg_lineLinear, "linear-closed": d3_svg_lineLinearClosed, step: d3_svg_lineStep, "step-before": d3_svg_lineStepBefore, "step-after": d3_svg_lineStepAfter, basis: d3_svg_lineBasis, "basis-open": d3_svg_lineBasisOpen, "basis-closed": d3_svg_lineBasisClosed, bundle: d3_svg_lineBundle, cardinal: d3_svg_lineCardinal, "cardinal-open": d3_svg_lineCardinalOpen, "cardinal-closed": d3_svg_lineCardinalClosed, monotone: d3_svg_lineMonotone }); d3_svg_lineInterpolators.forEach(function(key, value) { value.key = key; value.closed = /-closed$/.test(key); }); function d3_svg_lineLinear(points) { return points.length > 1 ? points.join("L") : points + "Z"; } function d3_svg_lineLinearClosed(points) { return points.join("L") + "Z"; } function d3_svg_lineStep(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); if (n > 1) path.push("H", p[0]); return path.join(""); } function d3_svg_lineStepBefore(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); return path.join(""); } function d3_svg_lineStepAfter(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); return path.join(""); } function d3_svg_lineCardinalOpen(points, tension) { return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); } function d3_svg_lineCardinalClosed(points, tension) { return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); } function d3_svg_lineCardinal(points, tension) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); } function d3_svg_lineHermite(points, tangents) { if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { return d3_svg_lineLinear(points); } var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; if (quad) { path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; p0 = points[1]; pi = 2; } if (tangents.length > 1) { t = tangents[1]; p = points[pi]; pi++; path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; for (var i = 2; i < tangents.length; i++, pi++) { p = points[pi]; t = tangents[i]; path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; } } if (quad) { var lp = points[pi]; path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; } return path; } function d3_svg_lineCardinalTangents(points, tension) { var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; while (++i < n) { p0 = p1; p1 = p2; p2 = points[i]; tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); } return tangents; } function d3_svg_lineBasis(points) { if (points.length < 3) return d3_svg_lineLinear(points); var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; points.push(points[n - 1]); while (++i <= n) { pi = points[i]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } points.pop(); path.push("L", pi); return path.join(""); } function d3_svg_lineBasisOpen(points) { if (points.length < 4) return d3_svg_lineLinear(points); var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; while (++i < 3) { pi = points[i]; px.push(pi[0]); py.push(pi[1]); } path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); --i; while (++i < n) { pi = points[i]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBasisClosed(points) { var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; while (++i < 4) { pi = points[i % n]; px.push(pi[0]); py.push(pi[1]); } path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; --i; while (++i < m) { pi = points[i % n]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBundle(points, tension) { var n = points.length - 1; if (n) { var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; while (++i <= n) { p = points[i]; t = i / n; p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); } } return d3_svg_lineBasis(points); } function d3_svg_lineDot4(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; function d3_svg_lineBasisBezier(path, x, y) { path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); } function d3_svg_lineSlope(p0, p1) { return (p1[1] - p0[1]) / (p1[0] - p0[0]); } function d3_svg_lineFiniteDifferences(points) { var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); while (++i < j) { m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; } m[i] = d; return m; } function d3_svg_lineMonotoneTangents(points) { var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; while (++i < j) { d = d3_svg_lineSlope(points[i], points[i + 1]); if (abs(d) < ε) { m[i] = m[i + 1] = 0; } else { a = m[i] / d; b = m[i + 1] / d; s = a * a + b * b; if (s > 9) { s = d * 3 / Math.sqrt(s); m[i] = s * a; m[i + 1] = s * b; } } } i = -1; while (++i <= j) { s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); tangents.push([ s || 0, m[i] * s || 0 ]); } return tangents; } function d3_svg_lineMonotone(points) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); } d3.svg.line.radial = function() { var line = d3_svg_line(d3_svg_lineRadial); line.radius = line.x, delete line.x; line.angle = line.y, delete line.y; return line; }; function d3_svg_lineRadial(points) { var point, i = -1, n = points.length, r, a; while (++i < n) { point = points[i]; r = point[0]; a = point[1] - halfπ; point[0] = r * Math.cos(a); point[1] = r * Math.sin(a); } return points; } function d3_svg_area(projection) { var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; function area(data) { var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { return x; } : d3_functor(x1), fy1 = y0 === y1 ? function() { return y; } : d3_functor(y1), x, y; function segment() { segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); } while (++i < n) { if (defined.call(this, d = data[i], i)) { points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); } else if (points0.length) { segment(); points0 = []; points1 = []; } } if (points0.length) segment(); return segments.length ? segments.join("") : null; } area.x = function(_) { if (!arguments.length) return x1; x0 = x1 = _; return area; }; area.x0 = function(_) { if (!arguments.length) return x0; x0 = _; return area; }; area.x1 = function(_) { if (!arguments.length) return x1; x1 = _; return area; }; area.y = function(_) { if (!arguments.length) return y1; y0 = y1 = _; return area; }; area.y0 = function(_) { if (!arguments.length) return y0; y0 = _; return area; }; area.y1 = function(_) { if (!arguments.length) return y1; y1 = _; return area; }; area.defined = function(_) { if (!arguments.length) return defined; defined = _; return area; }; area.interpolate = function(_) { if (!arguments.length) return interpolateKey; if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; interpolateReverse = interpolate.reverse || interpolate; L = interpolate.closed ? "M" : "L"; return area; }; area.tension = function(_) { if (!arguments.length) return tension; tension = _; return area; }; return area; } d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; d3.svg.area = function() { return d3_svg_area(d3_identity); }; d3.svg.area.radial = function() { var area = d3_svg_area(d3_svg_lineRadial); area.radius = area.x, delete area.x; area.innerRadius = area.x0, delete area.x0; area.outerRadius = area.x1, delete area.x1; area.angle = area.y, delete area.y; area.startAngle = area.y0, delete area.y0; area.endAngle = area.y1, delete area.y1; return area; }; d3.svg.chord = function() { var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; function chord(d, i) { var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; } function subgroup(self, f, d, i) { var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; return { r: r, a0: a0, a1: a1, p0: [ r * Math.cos(a0), r * Math.sin(a0) ], p1: [ r * Math.cos(a1), r * Math.sin(a1) ] }; } function equals(a, b) { return a.a0 == b.a0 && a.a1 == b.a1; } function arc(r, p, a) { return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; } function curve(r0, p0, r1, p1) { return "Q 0,0 " + p1; } chord.radius = function(v) { if (!arguments.length) return radius; radius = d3_functor(v); return chord; }; chord.source = function(v) { if (!arguments.length) return source; source = d3_functor(v); return chord; }; chord.target = function(v) { if (!arguments.length) return target; target = d3_functor(v); return chord; }; chord.startAngle = function(v) { if (!arguments.length) return startAngle; startAngle = d3_functor(v); return chord; }; chord.endAngle = function(v) { if (!arguments.length) return endAngle; endAngle = d3_functor(v); return chord; }; return chord; }; function d3_svg_chordRadius(d) { return d.radius; } d3.svg.diagonal = function() { var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; function diagonal(d, i) { var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { x: p0.x, y: m }, { x: p3.x, y: m }, p3 ]; p = p.map(projection); return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; } diagonal.source = function(x) { if (!arguments.length) return source; source = d3_functor(x); return diagonal; }; diagonal.target = function(x) { if (!arguments.length) return target; target = d3_functor(x); return diagonal; }; diagonal.projection = function(x) { if (!arguments.length) return projection; projection = x; return diagonal; }; return diagonal; }; function d3_svg_diagonalProjection(d) { return [ d.x, d.y ]; } d3.svg.diagonal.radial = function() { var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; diagonal.projection = function(x) { return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; }; return diagonal; }; function d3_svg_diagonalRadialProjection(projection) { return function() { var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; return [ r * Math.cos(a), r * Math.sin(a) ]; }; } d3.svg.symbol = function() { var type = d3_svg_symbolType, size = d3_svg_symbolSize; function symbol(d, i) { return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); } symbol.type = function(x) { if (!arguments.length) return type; type = d3_functor(x); return symbol; }; symbol.size = function(x) { if (!arguments.length) return size; size = d3_functor(x); return symbol; }; return symbol; }; function d3_svg_symbolSize() { return 64; } function d3_svg_symbolType() { return "circle"; } function d3_svg_symbolCircle(size) { var r = Math.sqrt(size / π); return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; } var d3_svg_symbols = d3.map({ circle: d3_svg_symbolCircle, cross: function(size) { var r = Math.sqrt(size / 5) / 2; return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; }, diamond: function(size) { var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; }, square: function(size) { var r = Math.sqrt(size) / 2; return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; }, "triangle-down": function(size) { var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; }, "triangle-up": function(size) { var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; } }); d3.svg.symbolTypes = d3_svg_symbols.keys(); var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); d3_selectionPrototype.transition = function(name) { var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { time: Date.now(), ease: d3_ease_cubicInOut, delay: 0, duration: 250 }; for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); subgroup.push(node); } } return d3_transition(subgroups, ns, id); }; d3_selectionPrototype.interrupt = function(name) { return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); }; var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); function d3_selection_interruptNS(ns) { return function() { var lock, activeId, active; if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { active.timer.c = null; active.timer.t = NaN; if (--lock.count) delete lock[activeId]; else delete this[ns]; lock.active += .5; active.event && active.event.interrupt.call(this, this.__data__, active.index); } }; } function d3_transition(groups, ns, id) { d3_subclass(groups, d3_transitionPrototype); groups.namespace = ns; groups.id = id; return groups; } var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; d3_transitionPrototype.call = d3_selectionPrototype.call; d3_transitionPrototype.empty = d3_selectionPrototype.empty; d3_transitionPrototype.node = d3_selectionPrototype.node; d3_transitionPrototype.size = d3_selectionPrototype.size; d3.transition = function(selection, name) { return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); }; d3.transition.prototype = d3_transitionPrototype; d3_transitionPrototype.select = function(selector) { var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; selector = d3_selection_selector(selector); for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { if ("__data__" in node) subnode.__data__ = node.__data__; d3_transitionNode(subnode, i, ns, id, node[ns][id]); subgroup.push(subnode); } else { subgroup.push(null); } } } return d3_transition(subgroups, ns, id); }; d3_transitionPrototype.selectAll = function(selector) { var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; selector = d3_selection_selectorAll(selector); for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { transition = node[ns][id]; subnodes = selector.call(node, node.__data__, i, j); subgroups.push(subgroup = []); for (var k = -1, o = subnodes.length; ++k < o; ) { if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); subgroup.push(subnode); } } } } return d3_transition(subgroups, ns, id); }; d3_transitionPrototype.filter = function(filter) { var subgroups = [], subgroup, group, node; if (typeof filter !== "function") filter = d3_selection_filter(filter); for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); for (var group = this[j], i = 0, n = group.length; i < n; i++) { if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { subgroup.push(node); } } } return d3_transition(subgroups, this.namespace, this.id); }; d3_transitionPrototype.tween = function(name, tween) { var id = this.id, ns = this.namespace; if (arguments.length < 2) return this.node()[ns][id].tween.get(name); return d3_selection_each(this, tween == null ? function(node) { node[ns][id].tween.remove(name); } : function(node) { node[ns][id].tween.set(name, tween); }); }; function d3_transition_tween(groups, name, value, tween) { var id = groups.id, ns = groups.namespace; return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); } : (value = tween(value), function(node) { node[ns][id].tween.set(name, value); })); } d3_transitionPrototype.attr = function(nameNS, value) { if (arguments.length < 2) { for (value in nameNS) this.attr(value, nameNS[value]); return this; } var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); function attrNull() { this.removeAttribute(name); } function attrNullNS() { this.removeAttributeNS(name.space, name.local); } function attrTween(b) { return b == null ? attrNull : (b += "", function() { var a = this.getAttribute(name), i; return a !== b && (i = interpolate(a, b), function(t) { this.setAttribute(name, i(t)); }); }); } function attrTweenNS(b) { return b == null ? attrNullNS : (b += "", function() { var a = this.getAttributeNS(name.space, name.local), i; return a !== b && (i = interpolate(a, b), function(t) { this.setAttributeNS(name.space, name.local, i(t)); }); }); } return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); }; d3_transitionPrototype.attrTween = function(nameNS, tween) { var name = d3.ns.qualify(nameNS); function attrTween(d, i) { var f = tween.call(this, d, i, this.getAttribute(name)); return f && function(t) { this.setAttribute(name, f(t)); }; } function attrTweenNS(d, i) { var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); return f && function(t) { this.setAttributeNS(name.space, name.local, f(t)); }; } return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); }; d3_transitionPrototype.style = function(name, value, priority) { var n = arguments.length; if (n < 3) { if (typeof name !== "string") { if (n < 2) value = ""; for (priority in name) this.style(priority, name[priority], value); return this; } priority = ""; } function styleNull() { this.style.removeProperty(name); } function styleString(b) { return b == null ? styleNull : (b += "", function() { var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; return a !== b && (i = d3_interpolate(a, b), function(t) { this.style.setProperty(name, i(t), priority); }); }); } return d3_transition_tween(this, "style." + name, value, styleString); }; d3_transitionPrototype.styleTween = function(name, tween, priority) { if (arguments.length < 3) priority = ""; function styleTween(d, i) { var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); return f && function(t) { this.style.setProperty(name, f(t), priority); }; } return this.tween("style." + name, styleTween); }; d3_transitionPrototype.text = function(value) { return d3_transition_tween(this, "text", value, d3_transition_text); }; function d3_transition_text(b) { if (b == null) b = ""; return function() { this.textContent = b; }; } d3_transitionPrototype.remove = function() { var ns = this.namespace; return this.each("end.transition", function() { var p; if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); }); }; d3_transitionPrototype.ease = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].ease; if (typeof value !== "function") value = d3.ease.apply(d3, arguments); return d3_selection_each(this, function(node) { node[ns][id].ease = value; }); }; d3_transitionPrototype.delay = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].delay; return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { node[ns][id].delay = +value.call(node, node.__data__, i, j); } : (value = +value, function(node) { node[ns][id].delay = value; })); }; d3_transitionPrototype.duration = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].duration; return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); } : (value = Math.max(1, value), function(node) { node[ns][id].duration = value; })); }; d3_transitionPrototype.each = function(type, listener) { var id = this.id, ns = this.namespace; if (arguments.length < 2) { var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; try { d3_transitionInheritId = id; d3_selection_each(this, function(node, i, j) { d3_transitionInherit = node[ns][id]; type.call(node, node.__data__, i, j); }); } finally { d3_transitionInherit = inherit; d3_transitionInheritId = inheritId; } } else { d3_selection_each(this, function(node) { var transition = node[ns][id]; (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); }); } return this; }; d3_transitionPrototype.transition = function() { var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); for (var group = this[j], i = 0, n = group.length; i < n; i++) { if (node = group[i]) { transition = node[ns][id0]; d3_transitionNode(node, i, ns, id1, { time: transition.time, ease: transition.ease, delay: transition.delay + transition.duration, duration: transition.duration }); } subgroup.push(node); } } return d3_transition(subgroups, ns, id1); }; function d3_transitionNamespace(name) { return name == null ? "__transition__" : "__transition_" + name + "__"; } function d3_transitionNode(node, i, ns, id, inherit) { var lock = node[ns] || (node[ns] = { active: 0, count: 0 }), transition = lock[id], time, timer, duration, ease, tweens; function schedule(elapsed) { var delay = transition.delay; timer.t = delay + time; if (delay <= elapsed) return start(elapsed - delay); timer.c = start; } function start(elapsed) { var activeId = lock.active, active = lock[activeId]; if (active) { active.timer.c = null; active.timer.t = NaN; --lock.count; delete lock[activeId]; active.event && active.event.interrupt.call(node, node.__data__, active.index); } for (var cancelId in lock) { if (+cancelId < id) { var cancel = lock[cancelId]; cancel.timer.c = null; cancel.timer.t = NaN; --lock.count; delete lock[cancelId]; } } timer.c = tick; d3_timer(function() { if (timer.c && tick(elapsed || 1)) { timer.c = null; timer.t = NaN; } return 1; }, 0, time); lock.active = id; transition.event && transition.event.start.call(node, node.__data__, i); tweens = []; transition.tween.forEach(function(key, value) { if (value = value.call(node, node.__data__, i)) { tweens.push(value); } }); ease = transition.ease; duration = transition.duration; } function tick(elapsed) { var t = elapsed / duration, e = ease(t), n = tweens.length; while (n > 0) { tweens[--n].call(node, e); } if (t >= 1) { transition.event && transition.event.end.call(node, node.__data__, i); if (--lock.count) delete lock[id]; else delete node[ns]; return 1; } } if (!transition) { time = inherit.time; timer = d3_timer(schedule, 0, time); transition = lock[id] = { tween: new d3_Map(), time: time, timer: timer, delay: inherit.delay, duration: inherit.duration, ease: inherit.ease, index: i }; inherit = null; ++lock.count; } } d3.svg.axis = function() { var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; function axis(g) { g.each(function() { var g = d3.select(this); var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), d3.transition(path)); tickEnter.append("line"); tickEnter.append("text"); var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; if (orient === "bottom" || orient === "top") { tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); } else { tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); } lineEnter.attr(y2, sign * innerTickSize); textEnter.attr(y1, sign * tickSpacing); lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); if (scale1.rangeBand) { var x = scale1, dx = x.rangeBand() / 2; scale0 = scale1 = function(d) { return x(d) + dx; }; } else if (scale0.rangeBand) { scale0 = scale1; } else { tickExit.call(tickTransform, scale1, scale0); } tickEnter.call(tickTransform, scale0, scale1); tickUpdate.call(tickTransform, scale1, scale1); }); } axis.scale = function(x) { if (!arguments.length) return scale; scale = x; return axis; }; axis.orient = function(x) { if (!arguments.length) return orient; orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; return axis; }; axis.ticks = function() { if (!arguments.length) return tickArguments_; tickArguments_ = d3_array(arguments); return axis; }; axis.tickValues = function(x) { if (!arguments.length) return tickValues; tickValues = x; return axis; }; axis.tickFormat = function(x) { if (!arguments.length) return tickFormat_; tickFormat_ = x; return axis; }; axis.tickSize = function(x) { var n = arguments.length; if (!n) return innerTickSize; innerTickSize = +x; outerTickSize = +arguments[n - 1]; return axis; }; axis.innerTickSize = function(x) { if (!arguments.length) return innerTickSize; innerTickSize = +x; return axis; }; axis.outerTickSize = function(x) { if (!arguments.length) return outerTickSize; outerTickSize = +x; return axis; }; axis.tickPadding = function(x) { if (!arguments.length) return tickPadding; tickPadding = +x; return axis; }; axis.tickSubdivide = function() { return arguments.length && axis; }; return axis; }; var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { top: 1, right: 1, bottom: 1, left: 1 }; function d3_svg_axisX(selection, x0, x1) { selection.attr("transform", function(d) { var v0 = x0(d); return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; }); } function d3_svg_axisY(selection, y0, y1) { selection.attr("transform", function(d) { var v0 = y0(d); return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; }); } d3.svg.brush = function() { var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; function brush(g) { g.each(function() { var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); var background = g.selectAll(".background").data([ 0 ]); background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); var resize = g.selectAll(".resize").data(resizes, d3_identity); resize.exit().remove(); resize.enter().append("g").attr("class", function(d) { return "resize " + d; }).style("cursor", function(d) { return d3_svg_brushCursor[d]; }).append("rect").attr("x", function(d) { return /[ew]$/.test(d) ? -3 : null; }).attr("y", function(d) { return /^[ns]/.test(d) ? -3 : null; }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); resize.style("display", brush.empty() ? "none" : null); var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; if (x) { range = d3_scaleRange(x); backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); redrawX(gUpdate); } if (y) { range = d3_scaleRange(y); backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); redrawY(gUpdate); } redraw(gUpdate); }); } brush.event = function(g) { g.each(function() { var event_ = event.of(this, arguments), extent1 = { x: xExtent, y: yExtent, i: xExtentDomain, j: yExtentDomain }, extent0 = this.__chart__ || extent1; this.__chart__ = extent1; if (d3_transitionInheritId) { d3.select(this).transition().each("start.brush", function() { xExtentDomain = extent0.i; yExtentDomain = extent0.j; xExtent = extent0.x; yExtent = extent0.y; event_({ type: "brushstart" }); }).tween("brush:brush", function() { var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); xExtentDomain = yExtentDomain = null; return function(t) { xExtent = extent1.x = xi(t); yExtent = extent1.y = yi(t); event_({ type: "brush", mode: "resize" }); }; }).each("end.brush", function() { xExtentDomain = extent1.i; yExtentDomain = extent1.j; event_({ type: "brush", mode: "resize" }); event_({ type: "brushend" }); }); } else { event_({ type: "brushstart" }); event_({ type: "brush", mode: "resize" }); event_({ type: "brushend" }); } }); }; function redraw(g) { g.selectAll(".resize").attr("transform", function(d) { return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; }); } function redrawX(g) { g.select(".extent").attr("x", xExtent[0]); g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); } function redrawY(g) { g.select(".extent").attr("y", yExtent[0]); g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); } function brushstart() { var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset; var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); if (d3.event.changedTouches) { w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); } else { w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); } g.interrupt().selectAll("*").interrupt(); if (dragging) { origin[0] = xExtent[0] - origin[0]; origin[1] = yExtent[0] - origin[1]; } else if (resizing) { var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; origin[0] = xExtent[ex]; origin[1] = yExtent[ey]; } else if (d3.event.altKey) center = origin.slice(); g.style("pointer-events", "none").selectAll(".resize").style("display", null); d3.select("body").style("cursor", eventTarget.style("cursor")); event_({ type: "brushstart" }); brushmove(); function keydown() { if (d3.event.keyCode == 32) { if (!dragging) { center = null; origin[0] -= xExtent[1]; origin[1] -= yExtent[1]; dragging = 2; } d3_eventPreventDefault(); } } function keyup() { if (d3.event.keyCode == 32 && dragging == 2) { origin[0] += xExtent[1]; origin[1] += yExtent[1]; dragging = 0; d3_eventPreventDefault(); } } function brushmove() { var point = d3.mouse(target), moved = false; if (offset) { point[0] += offset[0]; point[1] += offset[1]; } if (!dragging) { if (d3.event.altKey) { if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; origin[0] = xExtent[+(point[0] < center[0])]; origin[1] = yExtent[+(point[1] < center[1])]; } else center = null; } if (resizingX && move1(point, x, 0)) { redrawX(g); moved = true; } if (resizingY && move1(point, y, 1)) { redrawY(g); moved = true; } if (moved) { redraw(g); event_({ type: "brush", mode: dragging ? "move" : "resize" }); } } function move1(point, scale, i) { var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; if (dragging) { r0 -= position; r1 -= size + position; } min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; if (dragging) { max = (min += position) + size; } else { if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); if (position < min) { max = min; min = position; } else { max = position; } } if (extent[0] != min || extent[1] != max) { if (i) yExtentDomain = null; else xExtentDomain = null; extent[0] = min; extent[1] = max; return true; } } function brushend() { brushmove(); g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); d3.select("body").style("cursor", null); w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); dragRestore(); event_({ type: "brushend" }); } } brush.x = function(z) { if (!arguments.length) return x; x = z; resizes = d3_svg_brushResizes[!x << 1 | !y]; return brush; }; brush.y = function(z) { if (!arguments.length) return y; y = z; resizes = d3_svg_brushResizes[!x << 1 | !y]; return brush; }; brush.clamp = function(z) { if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; return brush; }; brush.extent = function(z) { var x0, x1, y0, y1, t; if (!arguments.length) { if (x) { if (xExtentDomain) { x0 = xExtentDomain[0], x1 = xExtentDomain[1]; } else { x0 = xExtent[0], x1 = xExtent[1]; if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; } } if (y) { if (yExtentDomain) { y0 = yExtentDomain[0], y1 = yExtentDomain[1]; } else { y0 = yExtent[0], y1 = yExtent[1]; if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; } } return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; } if (x) { x0 = z[0], x1 = z[1]; if (y) x0 = x0[0], x1 = x1[0]; xExtentDomain = [ x0, x1 ]; if (x.invert) x0 = x(x0), x1 = x(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; } if (y) { y0 = z[0], y1 = z[1]; if (x) y0 = y0[1], y1 = y1[1]; yExtentDomain = [ y0, y1 ]; if (y.invert) y0 = y(y0), y1 = y(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; } return brush; }; brush.clear = function() { if (!brush.empty()) { xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; xExtentDomain = yExtentDomain = null; } return brush; }; brush.empty = function() { return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; }; return d3.rebind(brush, event, "on"); }; var d3_svg_brushCursor = { n: "ns-resize", e: "ew-resize", s: "ns-resize", w: "ew-resize", nw: "nwse-resize", ne: "nesw-resize", se: "nwse-resize", sw: "nesw-resize" }; var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; var d3_time_formatUtc = d3_time_format.utc; var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; function d3_time_formatIsoNative(date) { return date.toISOString(); } d3_time_formatIsoNative.parse = function(string) { var date = new Date(string); return isNaN(date) ? null : date; }; d3_time_formatIsoNative.toString = d3_time_formatIso.toString; d3_time.second = d3_time_interval(function(date) { return new d3_date(Math.floor(date / 1e3) * 1e3); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 1e3); }, function(date) { return date.getSeconds(); }); d3_time.seconds = d3_time.second.range; d3_time.seconds.utc = d3_time.second.utc.range; d3_time.minute = d3_time_interval(function(date) { return new d3_date(Math.floor(date / 6e4) * 6e4); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 6e4); }, function(date) { return date.getMinutes(); }); d3_time.minutes = d3_time.minute.range; d3_time.minutes.utc = d3_time.minute.utc.range; d3_time.hour = d3_time_interval(function(date) { var timezone = date.getTimezoneOffset() / 60; return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 36e5); }, function(date) { return date.getHours(); }); d3_time.hours = d3_time.hour.range; d3_time.hours.utc = d3_time.hour.utc.range; d3_time.month = d3_time_interval(function(date) { date = d3_time.day(date); date.setDate(1); return date; }, function(date, offset) { date.setMonth(date.getMonth() + offset); }, function(date) { return date.getMonth(); }); d3_time.months = d3_time.month.range; d3_time.months.utc = d3_time.month.utc.range; function d3_time_scale(linear, methods, format) { function scale(x) { return linear(x); } scale.invert = function(x) { return d3_time_scaleDate(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return linear.domain().map(d3_time_scaleDate); linear.domain(x); return scale; }; function tickMethod(extent, count) { var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { return d / 31536e6; }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; } scale.nice = function(interval, skip) { var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); if (method) interval = method[0], skip = method[1]; function skipped(date) { return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; } return scale.domain(d3_scale_nice(domain, skip > 1 ? { floor: function(date) { while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); return date; }, ceil: function(date) { while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); return date; } } : interval)); }; scale.ticks = function(interval, skip) { var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { range: interval }, skip ]; if (method) interval = method[0], skip = method[1]; return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); }; scale.tickFormat = function() { return format; }; scale.copy = function() { return d3_time_scale(linear.copy(), methods, format); }; return d3_scale_linearRebind(scale, linear); } function d3_time_scaleDate(t) { return new Date(t); } var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { return d.getMilliseconds(); } ], [ ":%S", function(d) { return d.getSeconds(); } ], [ "%I:%M", function(d) { return d.getMinutes(); } ], [ "%I %p", function(d) { return d.getHours(); } ], [ "%a %d", function(d) { return d.getDay() && d.getDate() != 1; } ], [ "%b %d", function(d) { return d.getDate() != 1; } ], [ "%B", function(d) { return d.getMonth(); } ], [ "%Y", d3_true ] ]); var d3_time_scaleMilliseconds = { range: function(start, stop, step) { return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); }, floor: d3_identity, ceil: d3_identity }; d3_time_scaleLocalMethods.year = d3_time.year; d3_time.scale = function() { return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); }; var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { return [ m[0].utc, m[1] ]; }); var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { return d.getUTCMilliseconds(); } ], [ ":%S", function(d) { return d.getUTCSeconds(); } ], [ "%I:%M", function(d) { return d.getUTCMinutes(); } ], [ "%I %p", function(d) { return d.getUTCHours(); } ], [ "%a %d", function(d) { return d.getUTCDay() && d.getUTCDate() != 1; } ], [ "%b %d", function(d) { return d.getUTCDate() != 1; } ], [ "%B", function(d) { return d.getUTCMonth(); } ], [ "%Y", d3_true ] ]); d3_time_scaleUtcMethods.year = d3_time.year.utc; d3_time.scale.utc = function() { return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); }; d3.text = d3_xhrType(function(request) { return request.responseText; }); d3.json = function(url, callback) { return d3_xhr(url, "application/json", d3_json, callback); }; function d3_json(request) { return JSON.parse(request.responseText); } d3.html = function(url, callback) { return d3_xhr(url, "text/html", d3_html, callback); }; function d3_html(request) { var range = d3_document.createRange(); range.selectNode(d3_document.body); return range.createContextualFragment(request.responseText); } d3.xml = d3_xhrType(function(request) { return request.responseXML; }); if (true) this.d3 = d3, !(__WEBPACK_AMD_DEFINE_FACTORY__ = (d3), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); else {} }(); /***/ }), /***/ "6eeb": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("da84"); var createNonEnumerableProperty = __webpack_require__("9112"); var has = __webpack_require__("5135"); var setGlobal = __webpack_require__("ce4e"); var inspectSource = __webpack_require__("8925"); var InternalStateModule = __webpack_require__("69f3"); var getInternalState = InternalStateModule.get; var enforceInternalState = InternalStateModule.enforce; var TEMPLATE = String(String).split('String'); (module.exports = function (O, key, value, options) { var unsafe = options ? !!options.unsafe : false; var simple = options ? !!options.enumerable : false; var noTargetGet = options ? !!options.noTargetGet : false; if (typeof value == 'function') { if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key); enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); } if (O === global) { if (simple) O[key] = value; else setGlobal(key, value); return; } else if (!unsafe) { delete O[key]; } else if (!noTargetGet && O[key]) { simple = true; } if (simple) O[key] = value; else createNonEnumerableProperty(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState(this).source || inspectSource(this); }); /***/ }), /***/ "6f04": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // CONCATENATED MODULE: ./node_modules/d3-collection/src/map.js var prefix = "$"; function Map() {} Map.prototype = map.prototype = { constructor: Map, has: function(key) { return (prefix + key) in this; }, get: function(key) { return this[prefix + key]; }, set: function(key, value) { this[prefix + key] = value; return this; }, remove: function(key) { var property = prefix + key; return property in this && delete this[property]; }, clear: function() { for (var property in this) if (property[0] === prefix) delete this[property]; }, keys: function() { var keys = []; for (var property in this) if (property[0] === prefix) keys.push(property.slice(1)); return keys; }, values: function() { var values = []; for (var property in this) if (property[0] === prefix) values.push(this[property]); return values; }, entries: function() { var entries = []; for (var property in this) if (property[0] === prefix) entries.push({key: property.slice(1), value: this[property]}); return entries; }, size: function() { var size = 0; for (var property in this) if (property[0] === prefix) ++size; return size; }, empty: function() { for (var property in this) if (property[0] === prefix) return false; return true; }, each: function(f) { for (var property in this) if (property[0] === prefix) f(this[property], property.slice(1), this); } }; function map(object, f) { var map = new Map; // Copy constructor. if (object instanceof Map) object.each(function(value, key) { map.set(key, value); }); // Index array by numeric index or specified key function. else if (Array.isArray(object)) { var i = -1, n = object.length, o; if (f == null) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f(o = object[i], i, object), o); } // Convert object to map. else if (object) for (var key in object) map.set(key, object[key]); return map; } /* harmony default export */ var src_map = (map); // CONCATENATED MODULE: ./node_modules/d3-collection/src/nest.js /* harmony default export */ var src_nest = (function() { var keys = [], sortKeys = [], sortValues, rollup, nest; function apply(array, depth, createResult, setResult) { if (depth >= keys.length) { if (sortValues != null) array.sort(sortValues); return rollup != null ? rollup(array) : array; } var i = -1, n = array.length, key = keys[depth++], keyValue, value, valuesByKey = src_map(), values, result = createResult(); while (++i < n) { if (values = valuesByKey.get(keyValue = key(value = array[i]) + "")) { values.push(value); } else { valuesByKey.set(keyValue, [value]); } } valuesByKey.each(function(values, key) { setResult(result, key, apply(values, depth, createResult, setResult)); }); return result; } function entries(map, depth) { if (++depth > keys.length) return map; var array, sortKey = sortKeys[depth - 1]; if (rollup != null && depth >= keys.length) array = map.entries(); else array = [], map.each(function(v, k) { array.push({key: k, values: entries(v, depth)}); }); return sortKey != null ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array; } return nest = { object: function(array) { return apply(array, 0, createObject, setObject); }, map: function(array) { return apply(array, 0, createMap, setMap); }, entries: function(array) { return entries(apply(array, 0, createMap, setMap), 0); }, key: function(d) { keys.push(d); return nest; }, sortKeys: function(order) { sortKeys[keys.length - 1] = order; return nest; }, sortValues: function(order) { sortValues = order; return nest; }, rollup: function(f) { rollup = f; return nest; } }; }); function createObject() { return {}; } function setObject(object, key, value) { object[key] = value; } function createMap() { return src_map(); } function setMap(map, key, value) { map.set(key, value); } // CONCATENATED MODULE: ./node_modules/d3-collection/src/set.js function Set() {} var proto = src_map.prototype; Set.prototype = set.prototype = { constructor: Set, has: proto.has, add: function(value) { value += ""; this[prefix + value] = value; return this; }, remove: proto.remove, clear: proto.clear, values: proto.keys, size: proto.size, empty: proto.empty, each: proto.each }; function set(object, f) { var set = new Set; // Copy constructor. if (object instanceof Set) object.each(function(value) { set.add(value); }); // Otherwise, assume it’s an array. else if (object) { var i = -1, n = object.length; if (f == null) while (++i < n) set.add(object[i]); else while (++i < n) set.add(f(object[i], i, object)); } return set; } /* harmony default export */ var src_set = (set); // CONCATENATED MODULE: ./node_modules/d3-collection/src/keys.js /* harmony default export */ var src_keys = (function(map) { var keys = []; for (var key in map) keys.push(key); return keys; }); // CONCATENATED MODULE: ./node_modules/d3-collection/src/values.js /* harmony default export */ var src_values = (function(map) { var values = []; for (var key in map) values.push(map[key]); return values; }); // CONCATENATED MODULE: ./node_modules/d3-collection/src/entries.js /* harmony default export */ var src_entries = (function(map) { var entries = []; for (var key in map) entries.push({key: key, value: map[key]}); return entries; }); // CONCATENATED MODULE: ./node_modules/d3-collection/src/index.js /* concated harmony reexport nest */__webpack_require__.d(__webpack_exports__, "b", function() { return src_nest; }); /* unused concated harmony import set */ /* concated harmony reexport map */__webpack_require__.d(__webpack_exports__, "a", function() { return src_map; }); /* unused concated harmony import keys */ /* unused concated harmony import values */ /* unused concated harmony import entries */ /***/ }), /***/ "6f09": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "6f51": /***/ (function(module, exports) { module.exports = translate; /** * Translate a mat4 by the given vector * * @param {mat4} out the receiving matrix * @param {mat4} a the matrix to translate * @param {vec3} v vector to translate by * @returns {mat4} out */ function translate(out, a, v) { var x = v[0], y = v[1], z = v[2], a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23; if (a === out) { out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; } else { a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; out[12] = a00 * x + a10 * y + a20 * z + a[12]; out[13] = a01 * x + a11 * y + a21 * z + a[13]; out[14] = a02 * x + a12 * y + a22 * z + a[14]; out[15] = a03 * x + a13 * y + a23 * z + a[15]; } return out; }; /***/ }), /***/ "6f96": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "6fa6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var createMesh = __webpack_require__("551a"); var parseColorScale = __webpack_require__("765f").parseColorScale; var str2RgbaArray = __webpack_require__("f977"); var extractOpts = __webpack_require__("c258").extractOpts; var zip3 = __webpack_require__("569b"); var findNearestOnAxis = __webpack_require__("caf7").findNearestOnAxis; var generateIsoMeshes = __webpack_require__("caf7").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(Array.isArray(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; /***/ }), /***/ "6fc3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** 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 ); } /***/ }), /***/ "7000": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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]; } } } /***/ }), /***/ "7016": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("89e1"); /***/ }), /***/ "7045": /***/ (function(module, exports, __webpack_require__) { "use strict"; var objToString = Object.prototype.toString , isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/); module.exports = function (value) { return typeof value === "function" && isFunctionStringTag(objToString.call(value)); }; /***/ }), /***/ "7089": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); module.exports = function hasColorbar(container) { return Lib.isPlainObject(container.colorbar); }; /***/ }), /***/ "70b4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var Lib = __webpack_require__("fc26"); var Axes = __webpack_require__("0642"); var BADNUM = __webpack_require__("e806").BADNUM; var subTypes = __webpack_require__("de81"); var calcColorscale = __webpack_require__("09bd"); var arraysToCalcdata = __webpack_require__("106b"); var calcSelection = __webpack_require__("4136"); 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 x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); 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); } 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]; } 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 }; /***/ }), /***/ "70f9": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var drawModule = __webpack_require__("2595"); var clickModule = __webpack_require__("34f9"); module.exports = { moduleType: 'component', name: 'annotations', layoutAttributes: __webpack_require__("bb4a"), supplyLayoutDefaults: __webpack_require__("bb5b"), includeBasePlot: __webpack_require__("37d1")('annotations'), calcAutorange: __webpack_require__("cd84"), draw: drawModule.draw, drawOne: drawModule.drawOne, drawRaw: drawModule.drawRaw, hasClickToShow: clickModule.hasClickToShow, onClick: clickModule.onClick, convertCoords: __webpack_require__("351b") }; /***/ }), /***/ "7118": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); var layoutAttributes = __webpack_require__("d798"); var handleTickValueDefaults = __webpack_require__("d92f"); var handleTickMarkDefaults = __webpack_require__("27e3"); var handleTickLabelDefaults = __webpack_require__("5008"); var handleCategoryOrderDefaults = __webpack_require__("d18b"); var handleLineGridDefaults = __webpack_require__("743b"); var setConvert = __webpack_require__("1a40"); /** * 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 axType = containerOut.type; if(axType === 'date') { var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults'); handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); } setConvert(containerOut, layoutOut); var autorangeDflt = !containerOut.isValidRange(containerIn.range); if(autorangeDflt && options.reverseDflt) autorangeDflt = 'reversed'; var autoRange = coerce('autorange', autorangeDflt); if(autoRange && (axType === 'linear' || axType === '-')) coerce('rangemode'); coerce('range'); containerOut.cleanRange(); 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]; handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options, {pass: 1}); if(!visible) return containerOut; coerce('title.text', dfltTitle); Lib.coerceFont(coerce, 'title.font', { family: font.family, size: Math.round(font.size * 1.2), color: dfltFontColor }); handleTickValueDefaults(containerIn, containerOut, coerce, axType); handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options, {pass: 2}); handleTickMarkDefaults(containerIn, containerOut, coerce, options); handleLineGridDefaults(containerIn, containerOut, coerce, { dfltColor: dfltColor, bgColor: options.bgColor, showGrid: options.showGrid, attributes: layoutAttributes }); if(containerOut.showline || containerOut.ticks) coerce('mirror'); if(options.automargin) coerce('automargin'); var isMultiCategory = containerOut.type === 'multicategory'; if(!options.noTickson && (containerOut.type === 'category' || isMultiCategory) && (containerOut.ticks || containerOut.showgrid) ) { var ticksonDflt; if(isMultiCategory) ticksonDflt = 'boundaries'; coerce('tickson', ticksonDflt); } if(isMultiCategory) { var showDividers = coerce('showdividers'); if(showDividers) { coerce('dividercolor'); coerce('dividerwidth'); } } return containerOut; }; /***/ }), /***/ "714f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); // 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'); } } }; /***/ }), /***/ "716c": /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, '__esModule', { value: true }); var helpers = __webpack_require__("feb7"); /** * Callback for coordEach * * @callback coordEachCallback * @param {Array} currentCoord The current coordinate being processed. * @param {number} coordIndex The current index of the coordinate being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed. * @param {number} geometryIndex The current index of the Geometry being processed. */ /** * Iterate over coordinates in any GeoJSON object, similar to Array.forEach() * * @name coordEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex) * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration. * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) { * //=currentCoord * //=coordIndex * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * }); */ function coordEach(geojson, callback, excludeWrapCoord) { // Handles null Geometry -- Skips this GeoJSON if (geojson === null) return; var j, k, l, geometry, stopG, coords, geometryMaybeCollection, wrapShrink = 0, coordIndex = 0, isGeometryCollection, type = geojson.type, isFeatureCollection = type === 'FeatureCollection', isFeature = type === 'Feature', stop = isFeatureCollection ? geojson.features.length : 1; // This logic may look a little weird. The reason why it is that way // is because it's trying to be fast. GeoJSON supports multiple kinds // of objects at its root: FeatureCollection, Features, Geometries. // This function has the responsibility of handling all of them, and that // means that some of the `for` loops you see below actually just don't apply // to certain inputs. For instance, if you give this just a // Point geometry, then both loops are short-circuited and all we do // is gradually rename the input until it's called 'geometry'. // // This also aims to allocate as few resources as possible: just a // few numbers and booleans, rather than any temporary arrays as would // be required with the normalization approach. for (var featureIndex = 0; featureIndex < stop; featureIndex++) { geometryMaybeCollection = (isFeatureCollection ? geojson.features[featureIndex].geometry : (isFeature ? geojson.geometry : geojson)); isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (var geomIndex = 0; geomIndex < stopG; geomIndex++) { var multiFeatureIndex = 0; var geometryIndex = 0; geometry = isGeometryCollection ? geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection; // Handles null Geometry -- Skips this geometry if (geometry === null) continue; coords = geometry.coordinates; var geomType = geometry.type; wrapShrink = (excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon')) ? 1 : 0; switch (geomType) { case null: break; case 'Point': if (callback(coords, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false; coordIndex++; multiFeatureIndex++; break; case 'LineString': case 'MultiPoint': for (j = 0; j < coords.length; j++) { if (callback(coords[j], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false; coordIndex++; if (geomType === 'MultiPoint') multiFeatureIndex++; } if (geomType === 'LineString') multiFeatureIndex++; break; case 'Polygon': case 'MultiLineString': for (j = 0; j < coords.length; j++) { for (k = 0; k < coords[j].length - wrapShrink; k++) { if (callback(coords[j][k], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false; coordIndex++; } if (geomType === 'MultiLineString') multiFeatureIndex++; if (geomType === 'Polygon') geometryIndex++; } if (geomType === 'Polygon') multiFeatureIndex++; break; case 'MultiPolygon': for (j = 0; j < coords.length; j++) { geometryIndex = 0; for (k = 0; k < coords[j].length; k++) { for (l = 0; l < coords[j][k].length - wrapShrink; l++) { if (callback(coords[j][k][l], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false; coordIndex++; } geometryIndex++; } multiFeatureIndex++; } break; case 'GeometryCollection': for (j = 0; j < geometry.geometries.length; j++) if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false) return false; break; default: throw new Error('Unknown Geometry Type'); } } } } /** * Callback for coordReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback coordReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Array} currentCoord The current coordinate being processed. * @param {number} coordIndex The current index of the coordinate being processed. * Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} featureIndex The current index of the Feature being processed. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed. * @param {number} geometryIndex The current index of the Geometry being processed. */ /** * Reduce coordinates in any GeoJSON object, similar to Array.reduce() * * @name coordReduce * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) { * //=previousValue * //=currentCoord * //=coordIndex * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * return currentCoord; * }); */ function coordReduce(geojson, callback, initialValue, excludeWrapCoord) { var previousValue = initialValue; coordEach(geojson, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) { if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord; else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex); }, excludeWrapCoord); return previousValue; } /** * Callback for propEach * * @callback propEachCallback * @param {Object} currentProperties The current Properties being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Iterate over properties in any GeoJSON object, similar to Array.forEach() * * @name propEach * @param {FeatureCollection|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (currentProperties, featureIndex) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.propEach(features, function (currentProperties, featureIndex) { * //=currentProperties * //=featureIndex * }); */ function propEach(geojson, callback) { var i; switch (geojson.type) { case 'FeatureCollection': for (i = 0; i < geojson.features.length; i++) { if (callback(geojson.features[i].properties, i) === false) break; } break; case 'Feature': callback(geojson.properties, 0); break; } } /** * Callback for propReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback propReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {*} currentProperties The current Properties being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Reduce properties in any GeoJSON object into a single value, * similar to how Array.reduce works. However, in this case we lazily run * the reduction, so an array of all properties is unnecessary. * * @name propReduce * @param {FeatureCollection|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) { * //=previousValue * //=currentProperties * //=featureIndex * return currentProperties * }); */ function propReduce(geojson, callback, initialValue) { var previousValue = initialValue; propEach(geojson, function (currentProperties, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties; else previousValue = callback(previousValue, currentProperties, featureIndex); }); return previousValue; } /** * Callback for featureEach * * @callback featureEachCallback * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.featureEach(features, function (currentFeature, featureIndex) { * //=currentFeature * //=featureIndex * }); */ function featureEach(geojson, callback) { if (geojson.type === 'Feature') { callback(geojson, 0); } else if (geojson.type === 'FeatureCollection') { for (var i = 0; i < geojson.features.length; i++) { if (callback(geojson.features[i], i) === false) break; } } } /** * Callback for featureReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback featureReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name featureReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * return currentFeature * }); */ function featureReduce(geojson, callback, initialValue) { var previousValue = initialValue; featureEach(geojson, function (currentFeature, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex); }); return previousValue; } /** * Get all coordinates from any GeoJSON object. * * @name coordAll * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @returns {Array>} coordinate position array * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * var coords = turf.coordAll(features); * //= [[26, 37], [36, 53]] */ function coordAll(geojson) { var coords = []; coordEach(geojson, function (coord) { coords.push(coord); }); return coords; } /** * Callback for geomEach * * @callback geomEachCallback * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Iterate over each geometry in any GeoJSON object, similar to Array.forEach() * * @name geomEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * }); */ function geomEach(geojson, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, featureProperties, featureBBox, featureId, featureIndex = 0, isFeatureCollection = geojson.type === 'FeatureCollection', isFeature = geojson.type === 'Feature', stop = isFeatureCollection ? geojson.features.length : 1; // This logic may look a little weird. The reason why it is that way // is because it's trying to be fast. GeoJSON supports multiple kinds // of objects at its root: FeatureCollection, Features, Geometries. // This function has the responsibility of handling all of them, and that // means that some of the `for` loops you see below actually just don't apply // to certain inputs. For instance, if you give this just a // Point geometry, then both loops are short-circuited and all we do // is gradually rename the input until it's called 'geometry'. // // This also aims to allocate as few resources as possible: just a // few numbers and booleans, rather than any temporary arrays as would // be required with the normalization approach. for (i = 0; i < stop; i++) { geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry : (isFeature ? geojson.geometry : geojson)); featureProperties = (isFeatureCollection ? geojson.features[i].properties : (isFeature ? geojson.properties : {})); featureBBox = (isFeatureCollection ? geojson.features[i].bbox : (isFeature ? geojson.bbox : undefined)); featureId = (isFeatureCollection ? geojson.features[i].id : (isFeature ? geojson.id : undefined)); isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; // Handle null Geometry if (geometry === null) { if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false; continue; } switch (geometry.type) { case 'Point': case 'LineString': case 'MultiPoint': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': { if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false; break; } case 'GeometryCollection': { for (j = 0; j < geometry.geometries.length; j++) { if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false; } break; } default: throw new Error('Unknown Geometry Type'); } } // Only increase `featureIndex` per each feature featureIndex++; } } /** * Callback for geomReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback geomReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Reduce geometry in any GeoJSON object, similar to Array.reduce(). * * @name geomReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=previousValue * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * return currentGeometry * }); */ function geomReduce(geojson, callback, initialValue) { var previousValue = initialValue; geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry; else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId); }); return previousValue; } /** * Callback for flattenEach * * @callback flattenEachCallback * @param {Feature} currentFeature The current flattened feature being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed. */ /** * Iterate over flattened features in any GeoJSON object, similar to * Array.forEach. * * @name flattenEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) { * //=currentFeature * //=featureIndex * //=multiFeatureIndex * }); */ function flattenEach(geojson, callback) { geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) { // Callback for single geometry var type = (geometry === null) ? null : geometry.type; switch (type) { case null: case 'Point': case 'LineString': case 'Polygon': if (callback(helpers.feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false; return; } var geomType; // Callback for multi-geometry switch (type) { case 'MultiPoint': geomType = 'Point'; break; case 'MultiLineString': geomType = 'LineString'; break; case 'MultiPolygon': geomType = 'Polygon'; break; } for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) { var coordinate = geometry.coordinates[multiFeatureIndex]; var geom = { type: geomType, coordinates: coordinate }; if (callback(helpers.feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false; } }); } /** * Callback for flattenReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback flattenReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed. */ /** * Reduce flattened features in any GeoJSON object, similar to Array.reduce(). * * @name flattenReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * //=multiFeatureIndex * return currentFeature * }); */ function flattenReduce(geojson, callback, initialValue) { var previousValue = initialValue; flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) { if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex); }); return previousValue; } /** * Callback for segmentEach * * @callback segmentEachCallback * @param {Feature} currentSegment The current Segment being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed. * @param {number} geometryIndex The current index of the Geometry being processed. * @param {number} segmentIndex The current index of the Segment being processed. * @returns {void} */ /** * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //=currentSegment * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * //=segmentIndex * }); * * // Calculate the total number of segments * var total = 0; * turf.segmentEach(polygon, function () { * total++; * }); */ function segmentEach(geojson, callback) { flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) { var segmentIndex = 0; // Exclude null Geometries if (!feature.geometry) return; // (Multi)Point geometries do not contain segments therefore they are ignored during this operation. var type = feature.geometry.type; if (type === 'Point' || type === 'MultiPoint') return; // Generate 2-vertex line segments var previousCoords; var previousFeatureIndex = 0; var previousMultiIndex = 0; var prevGeomIndex = 0; if (coordEach(feature, function (currentCoord, coordIndex, featureIndexCoord, multiPartIndexCoord, geometryIndex) { // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false` if (previousCoords === undefined || featureIndex > previousFeatureIndex || multiPartIndexCoord > previousMultiIndex || geometryIndex > prevGeomIndex) { previousCoords = currentCoord; previousFeatureIndex = featureIndex; previousMultiIndex = multiPartIndexCoord; prevGeomIndex = geometryIndex; segmentIndex = 0; return; } var currentSegment = helpers.lineString([previousCoords, currentCoord], feature.properties); if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false; segmentIndex++; previousCoords = currentCoord; }) === false) return false; }); } /** * Callback for segmentReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback segmentReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentSegment The current Segment being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed. * @param {number} geometryIndex The current index of the Geometry being processed. * @param {number} segmentIndex The current index of the Segment being processed. */ /** * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //= previousSegment * //= currentSegment * //= featureIndex * //= multiFeatureIndex * //= geometryIndex * //= segmentInex * return currentSegment * }); * * // Calculate the total number of segments * var initialValue = 0 * var total = turf.segmentReduce(polygon, function (previousValue) { * previousValue++; * return previousValue; * }, initialValue); */ function segmentReduce(geojson, callback, initialValue) { var previousValue = initialValue; var started = false; segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { if (started === false && initialValue === undefined) previousValue = currentSegment; else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex); started = true; }); return previousValue; } /** * Callback for lineEach * * @callback lineEachCallback * @param {Feature} currentLine The current LineString|LinearRing being processed * @param {number} featureIndex The current index of the Feature being processed * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed * @param {number} geometryIndex The current index of the Geometry being processed */ /** * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries, * similar to Array.forEach. * * @name lineEach * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @example * var multiLine = turf.multiLineString([ * [[26, 37], [35, 45]], * [[36, 53], [38, 50], [41, 55]] * ]); * * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * }); */ function lineEach(geojson, callback) { // validation if (!geojson) throw new Error('geojson is required'); flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) { if (feature.geometry === null) return; var type = feature.geometry.type; var coords = feature.geometry.coordinates; switch (type) { case 'LineString': if (callback(feature, featureIndex, multiFeatureIndex, 0, 0) === false) return false; break; case 'Polygon': for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) { if (callback(helpers.lineString(coords[geometryIndex], feature.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false; } break; } }); } /** * Callback for lineReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback lineReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentLine The current LineString|LinearRing being processed. * @param {number} featureIndex The current index of the Feature being processed * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed * @param {number} geometryIndex The current index of the Geometry being processed */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name lineReduce * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var multiPoly = turf.multiPolygon([ * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]), * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]]) * ]); * * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=previousValue * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * return currentLine * }); */ function lineReduce(geojson, callback, initialValue) { var previousValue = initialValue; lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine; else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex); }); return previousValue; } /** * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * Point & MultiPoint will always return null. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.segmentIndex=0] Segment Index * @param {Object} [options.properties={}] Translate Properties to output LineString * @param {BBox} [options.bbox={}] Translate BBox to output LineString * @param {number|string} [options.id={}] Translate Id to output LineString * @returns {Feature} 2-vertex GeoJSON Feature LineString * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findSegment(multiLine); * // => Feature> * * // First Segment of 2nd Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of Last Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1}); * // => Feature> */ function findSegment(geojson, options) { // Optional Parameters options = options || {}; if (!helpers.isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var segmentIndex = options.segmentIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find SegmentIndex if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': case 'MultiPoint': return null; case 'LineString': if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1; return helpers.lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1; return helpers.lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1; return helpers.lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1; return helpers.lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options); } throw new Error('geojson is invalid'); } /** * Finds a particular Point from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.coordIndex=0] Coord Index * @param {Object} [options.properties={}] Translate Properties to output Point * @param {BBox} [options.bbox={}] Translate BBox to output Point * @param {number|string} [options.id={}] Translate Id to output Point * @returns {Feature} 2-vertex GeoJSON Feature Point * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findPoint(multiLine); * // => Feature> * * // First Segment of the 2nd Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of last Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1}); * // => Feature> */ function findPoint(geojson, options) { // Optional Parameters options = options || {}; if (!helpers.isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var coordIndex = options.coordIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find Coord Index if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': return helpers.point(coords, properties, options); case 'MultiPoint': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; return helpers.point(coords[multiFeatureIndex], properties, options); case 'LineString': if (coordIndex < 0) coordIndex = coords.length + coordIndex; return helpers.point(coords[coordIndex], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex; return helpers.point(coords[geometryIndex][coordIndex], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex; return helpers.point(coords[multiFeatureIndex][coordIndex], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex; return helpers.point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options); } throw new Error('geojson is invalid'); } exports.coordEach = coordEach; exports.coordReduce = coordReduce; exports.propEach = propEach; exports.propReduce = propReduce; exports.featureEach = featureEach; exports.featureReduce = featureReduce; exports.coordAll = coordAll; exports.geomEach = geomEach; exports.geomReduce = geomReduce; exports.flattenEach = flattenEach; exports.flattenReduce = flattenReduce; exports.segmentEach = segmentEach; exports.segmentReduce = segmentReduce; exports.lineEach = lineEach; exports.lineReduce = lineReduce; exports.findSegment = findSegment; exports.findPoint = findPoint; /***/ }), /***/ "71b1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "7210": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var handleArrayContainerDefaults = __webpack_require__("e5ac"); var attributes = __webpack_require__("9c5f"); var constants = __webpack_require__("e639"); 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'); } } /***/ }), /***/ "7223": /***/ (function(module, exports, __webpack_require__) { "use strict"; var db = __webpack_require__("abc0") var ctz = __webpack_require__("a48a").countTrailingZeros module.exports = ctzNumber //Counts the number of trailing zeros function ctzNumber(x) { var l = ctz(db.lo(x)) if(l < 32) { return l } var h = ctz(db.hi(x)) if(h > 20) { return 52 } return h + 32 } /***/ }), /***/ "722f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var axisIds = __webpack_require__("3c1c"); var traceIs = __webpack_require__("371e").traceIs; var handleGroupingDefaults = __webpack_require__("1c1c").handleGroupingDefaults; var nestedProperty = Lib.nestedProperty; var getAxisGroup = axisIds.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; // 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; for(i = 0; i < traces.length; i++) { traceOut = traces[i]; binGroupFound = coerce('bingroup'); break; } 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); } } } }; /***/ }), /***/ "72a4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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 }; /***/ }), /***/ "72e9": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var styleOne = __webpack_require__("a708"); var resizeText = __webpack_require__("93a6").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); }); }); }; /***/ }), /***/ "7327": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isBN = __webpack_require__("4e7e") module.exports = isRat function isRat(x) { return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1]) } /***/ }), /***/ "7373": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isValue = __webpack_require__("62c4"); var keys = Object.keys; module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); }; /***/ }), /***/ "7388": /***/ (function(module, exports, __webpack_require__) { module.exports = { create: __webpack_require__("2638"), clone: __webpack_require__("3c41"), fromValues: __webpack_require__("f9f9"), copy: __webpack_require__("265e"), set: __webpack_require__("204d"), add: __webpack_require__("c3a9"), subtract: __webpack_require__("56cf"), multiply: __webpack_require__("dd86"), divide: __webpack_require__("73cf"), min: __webpack_require__("5374"), max: __webpack_require__("dd05"), scale: __webpack_require__("d9c2"), scaleAndAdd: __webpack_require__("0970"), distance: __webpack_require__("fa11"), squaredDistance: __webpack_require__("bf66"), length: __webpack_require__("4e89"), squaredLength: __webpack_require__("644a"), negate: __webpack_require__("b1ca"), inverse: __webpack_require__("95c9"), normalize: __webpack_require__("5243"), dot: __webpack_require__("7bb3"), lerp: __webpack_require__("7ae4"), random: __webpack_require__("aff3"), transformMat4: __webpack_require__("6259"), transformQuat: __webpack_require__("d26e") } /***/ }), /***/ "738f": /***/ (function(module, exports) { module.exports = scaleAndAdd; /** * Adds two vec3's after scaling the second operand by a scalar value * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @param {Number} scale the amount to scale b by before adding * @returns {vec3} out */ function scaleAndAdd(out, a, b, scale) { out[0] = a[0] + (b[0] * scale) out[1] = a[1] + (b[1] * scale) out[2] = a[2] + (b[2] * scale) return out } /***/ }), /***/ "739b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Template = __webpack_require__("a651"); var colorScaleAttrs = __webpack_require__("0dd7"); var colorScaleDefaults = __webpack_require__("4183"); 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]; } } }; /***/ }), /***/ "73c9": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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 }; /***/ }), /***/ "73cf": /***/ (function(module, exports) { module.exports = divide /** * Divides two vec4's * * @param {vec4} out the receiving vector * @param {vec4} a the first operand * @param {vec4} b the second operand * @returns {vec4} out */ function divide (out, a, b) { out[0] = a[0] / b[0] out[1] = a[1] / b[1] out[2] = a[2] / b[2] out[3] = a[3] / b[3] return out } /***/ }), /***/ "7418": /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), /***/ "743b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var colorMix = __webpack_require__("66cb").mix; var lightFraction = __webpack_require__("dfb3").lightFraction; var Lib = __webpack_require__("fc26"); /** * @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 || lightFraction).toRgbString(); var gridColor = coerce2('gridcolor', gridColorDflt); var gridWidth = coerce2('gridwidth'); var showGridLines = coerce('showgrid', opts.showGrid || !!gridColor || !!gridWidth); if(!showGridLines) { delete containerOut.gridcolor; delete containerOut.gridwidth; } 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; } } }; /***/ }), /***/ "746f": /***/ (function(module, exports, __webpack_require__) { var path = __webpack_require__("428f"); var has = __webpack_require__("5135"); var wrappedWellKnownSymbolModule = __webpack_require__("e538"); var defineProperty = __webpack_require__("9bf2").f; module.exports = function (NAME) { var Symbol = path.Symbol || (path.Symbol = {}); if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, { value: wrappedWellKnownSymbolModule.f(NAME) }); }; /***/ }), /***/ "74b4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var texttemplateAttrs = __webpack_require__("94d5").texttemplateAttrs; var scatterGeoAttrs = __webpack_require__("56f3"); var scatterAttrs = __webpack_require__("107c"); var mapboxAttrs = __webpack_require__("f7e9"); var baseAttrs = __webpack_require__("a876"); var colorScaleAttrs = __webpack_require__("f4e9"); var extendFlat = __webpack_require__("9092").extendFlat; var overrideAll = __webpack_require__("cb34").overrideAll; var lineAttrs = scatterGeoAttrs.line; var markerAttrs = scatterGeoAttrs.marker; module.exports = overrideAll({ lon: scatterGeoAttrs.lon, lat: scatterGeoAttrs.lat, // 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, }, opacity: markerAttrs.opacity, size: markerAttrs.size, sizeref: markerAttrs.sizeref, sizemin: markerAttrs.sizemin, sizemode: markerAttrs.sizemode }, colorScaleAttrs('marker') // line ), fill: scatterGeoAttrs.fill, fillcolor: scatterAttrs.fillcolor, 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'); /***/ }), /***/ "74d6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var isArrayOrTypedArray = __webpack_require__("6af8").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 j = 0; var propParts = propStr.split('.'); var indexed; var indices; var i; // check for parts of the nesting hierarchy that are numbers (ie array elements) 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 }; } /***/ }), /***/ "7559": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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)' }, '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)' }, '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' } }; /***/ }), /***/ "7594": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Color = __webpack_require__("d115"); var Lib = __webpack_require__("fc26"); var resizeText = __webpack_require__("93a6").resizeText; 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); }); }); } function styleOne(s, pt, trace) { 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.style('stroke-width', lineWidth) .call(Color.fill, cdi.color) .call(Color.stroke, lineColor) .style('opacity', isLeaf ? trace.leaf.opacity : null); } module.exports = { style: style, styleOne: styleOne }; /***/ }), /***/ "75ac": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("8761"); /***/ }), /***/ "765f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var tinycolor = __webpack_require__("66cb"); var rgba = __webpack_require__("0103"); var Colorscale = __webpack_require__("c258"); var colorDflt = __webpack_require__("dfb3").defaultLine; var isArrayOrTypedArray = __webpack_require__("6af8").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; 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, alpha) { if(alpha === undefined) alpha = 1; var cOpts = Colorscale.extractOpts(cont); var colorscale = cOpts.reversescale ? Colorscale.flipScale(cOpts.colorscale) : 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, alpha] }; }); } module.exports = { formatColor: formatColor, parseColorScale: parseColorScale }; /***/ }), /***/ "7678": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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', } }; /***/ }), /***/ "76b2": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* global MathJax:false */ module.exports = function() { if(typeof MathJax !== 'undefined') { var globalConfig = (window.PlotlyConfig || {}).MathJaxConfig !== 'local'; if(globalConfig) { MathJax.Hub.Config({ messageStyle: 'none', skipStartupTypeset: true, displayAlign: 'left', tex2jax: { inlineMath: [['$', '$'], ['\\(', '\\)']] } }); MathJax.Hub.Configured(); } } }; /***/ }), /***/ "76fe": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var str2RgbaArray = __webpack_require__("f977"); var Lib = __webpack_require__("fc26"); 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.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.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; } // 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('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; /***/ }), /***/ "7797": /***/ (function(module, exports, __webpack_require__) { "use strict"; "use restrict"; module.exports = UnionFind; function UnionFind(count) { this.roots = new Array(count); this.ranks = new Array(count); for(var i=0; i ]/) ? '_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]; } /***/ }), /***/ "7831": /***/ (function(module, exports) { module.exports = function(dtype) { switch (dtype) { case 'int8': return Int8Array case 'int16': return Int16Array case 'int32': return Int32Array case 'uint8': return Uint8Array case 'uint16': return Uint16Array case 'uint32': return Uint32Array case 'float32': return Float32Array case 'float64': return Float64Array case 'array': return Array case 'uint8_clamped': return Uint8ClampedArray } } /***/ }), /***/ "7839": /***/ (function(module, exports) { // IE8- don't enum bug keys module.exports = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /***/ }), /***/ "7899": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = affineHull var orient = __webpack_require__("92ba") function linearlyIndependent(points, d) { var nhull = new Array(d+1) for(var i=0; i 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', 'translate(' + 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.makeTransFn(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;}); 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.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) { 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 fmt = 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 + fmt(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 = d3.interpolateNumber(cd[0].lastY, cd[0].y); trace._lastValue = cd[0].y; var transitionFmt = transitionFormat(trace.number.valueformat, fmt, cd[0].lastY, cd[0].y); return function(t) { that.text(bignumberPrefix + transitionFmt(interpolator(t)) + bignumberSuffix); }; }); } else { writeNumber(); } bignumberbBox = measureText(bignumberPrefix + fmt(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 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) + numberFmt(value); }; 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 = d3.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) + ' scale(' + 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 interpolate = d3.interpolate(endAngle, newAngle); return function(t) { return arc.endAngle(interpolate(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, 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 strTranslate(x, y) { return 'translate(' + x + ',' + y + ')'; } 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; } /***/ }), /***/ "792f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var extendFlat = __webpack_require__("9092").extendFlat; var scatterPolarAttrs = __webpack_require__("8a6e"); var barAttrs = __webpack_require__("fb5a"); 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: barAttrs.marker, hoverinfo: scatterPolarAttrs.hoverinfo, hovertemplate: hovertemplateAttrs(), selected: barAttrs.selected, unselected: barAttrs.unselected // error_x (error_r, error_theta) // error_y }; /***/ }), /***/ "794e": /***/ (function(module, exports, __webpack_require__) { "use strict"; var createBuffer = __webpack_require__("efce") var createVAO = __webpack_require__("b205") var createShader = __webpack_require__("e4eb") module.exports = createSpikes var identity = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] function AxisSpikes(gl, buffer, vao, shader) { this.gl = gl this.buffer = buffer this.vao = vao this.shader = shader this.pixelRatio = 1 this.bounds = [[-1000,-1000,-1000], [1000,1000,1000]] this.position = [0,0,0] this.lineWidth = [2,2,2] this.colors = [[0,0,0,1], [0,0,0,1], [0,0,0,1]] this.enabled = [true,true,true] this.drawSides = [true,true,true] this.axes = null } var proto = AxisSpikes.prototype var OUTER_FACE = [0,0,0] var INNER_FACE = [0,0,0] var SHAPE = [0,0] proto.isTransparent = function() { return false } proto.drawTransparent = function(camera) {} proto.draw = function(camera) { var gl = this.gl var vao = this.vao var shader = this.shader vao.bind() shader.bind() var model = camera.model || identity var view = camera.view || identity var projection = camera.projection || identity var axis if(this.axes) { axis = this.axes.lastCubeProps.axis } var outerFace = OUTER_FACE var innerFace = INNER_FACE for(var i=0; i<3; ++i) { if(axis && axis[i] < 0) { outerFace[i] = this.bounds[0][i] innerFace[i] = this.bounds[1][i] } else { outerFace[i] = this.bounds[1][i] innerFace[i] = this.bounds[0][i] } } SHAPE[0] = gl.drawingBufferWidth SHAPE[1] = gl.drawingBufferHeight shader.uniforms.model = model shader.uniforms.view = view shader.uniforms.projection = projection shader.uniforms.coordinates = [this.position, outerFace, innerFace] shader.uniforms.colors = this.colors shader.uniforms.screenShape = SHAPE for(var i=0; i<3; ++i) { shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio if(this.enabled[i]) { vao.draw(gl.TRIANGLES, 6, 6*i) if(this.drawSides[i]) { vao.draw(gl.TRIANGLES, 12, 18+12*i) } } } vao.unbind() } proto.update = function(options) { if(!options) { return } if("bounds" in options) { this.bounds = options.bounds } if("position" in options) { this.position = options.position } if("lineWidth" in options) { this.lineWidth = options.lineWidth } if("colors" in options) { this.colors = options.colors } if("enabled" in options) { this.enabled = options.enabled } if("drawSides" in options) { this.drawSides = options.drawSides } } proto.dispose = function() { this.vao.dispose() this.buffer.dispose() this.shader.dispose() } function createSpikes(gl, options) { //Create buffers var data = [ ] function line(x,y,z,i,l,h) { var row = [x,y,z, 0,0,0, 1] row[i+3] = 1 row[i] = l data.push.apply(data, row) row[6] = -1 data.push.apply(data, row) row[i] = h data.push.apply(data, row) data.push.apply(data, row) row[6] = 1 data.push.apply(data, row) row[i] = l data.push.apply(data, row) } line(0,0,0, 0, 0, 1) line(0,0,0, 1, 0, 1) line(0,0,0, 2, 0, 1) line(1,0,0, 1, -1,1) line(1,0,0, 2, -1,1) line(0,1,0, 0, -1,1) line(0,1,0, 2, -1,1) line(0,0,1, 0, -1,1) line(0,0,1, 1, -1,1) var buffer = createBuffer(gl, data) var vao = createVAO(gl, [{ type: gl.FLOAT, buffer: buffer, size: 3, offset: 0, stride: 28 }, { type: gl.FLOAT, buffer: buffer, size: 3, offset: 12, stride: 28 }, { type: gl.FLOAT, buffer: buffer, size: 1, offset: 24, stride: 28 }]) //Create shader var shader = createShader(gl) shader.attributes.position.location = 0 shader.attributes.color.location = 1 shader.attributes.weight.location = 2 //Create spike object var spikes = new AxisSpikes(gl, buffer, vao, shader) //Set parameters spikes.update(options) //Return resulting object return spikes } /***/ }), /***/ "7974": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var counterRegex = __webpack_require__("055a").counter; var domainAttrs = __webpack_require__("81f0").attributes; var cartesianIdRegex = __webpack_require__("d301").idRegex; var Template = __webpack_require__("a651"); 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 }; /***/ }), /***/ "7988": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var parcoords = __webpack_require__("baec"); var prepareRegl = __webpack_require__("cf42"); var isVisible = __webpack_require__("2ee6").isVisible; 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) ); }; } module.exports = function plot(gd, cdModule) { var fullLayout = gd._fullLayout; var success = prepareRegl(gd); 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 } ); }; /***/ }), /***/ "79d9": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function signum(x) { if(x < 0) { return -1 } if(x > 0) { return 1 } return 0.0 } /***/ }), /***/ "79f1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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; }; /***/ }), /***/ "7a18": /***/ (function(module) { module.exports = JSON.parse("[\"normal\",\"bold\",\"bolder\",\"lighter\",\"100\",\"200\",\"300\",\"400\",\"500\",\"600\",\"700\",\"800\",\"900\"]"); /***/ }), /***/ "7a4a": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isArrayOrTypedArray = __webpack_require__("fc26").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]; } /***/ }), /***/ "7a52": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var setConvertCartesian = __webpack_require__("1a40"); 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) { if(Lib.isTypedArray(arrayIn) && axType === 'linear') { if(len === arrayIn.length) { return arrayIn; } else if(arrayIn.subarray) { return arrayIn.subarray(0, len); } } 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)); }; }; } /***/ }), /***/ "7a5f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { moduleType: 'trace', name: 'indicator', basePlotModule: __webpack_require__("643c"), categories: ['svg', 'noOpacity', 'noHover'], animatable: true, attributes: __webpack_require__("1c82"), supplyDefaults: __webpack_require__("18bb").supplyDefaults, calc: __webpack_require__("5ad1").calc, plot: __webpack_require__("78ee"), meta: { } }; /***/ }), /***/ "7a71": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = measure measure.canvas = document.createElement('canvas') measure.cache = {} function measure (font, o) { if (!o) o = {} if (typeof font === 'string' || Array.isArray(font)) { o.family = font } var family = Array.isArray(o.family) ? o.family.join(', ') : o.family if (!family) throw Error('`family` must be defined') var fs = o.size || o.fontSize || o.em || 48 var weight = o.weight || o.fontWeight || '' var style = o.style || o.fontStyle || '' var font = [style, weight, fs].join(' ') + 'px ' + family var origin = o.origin || 'top' if (measure.cache[family]) { // return more precise values if cache has them if (fs <= measure.cache[family].em) { return applyOrigin(measure.cache[family], origin) } } var canvas = o.canvas || measure.canvas var ctx = canvas.getContext('2d') var chars = { upper: o.upper !== undefined ? o.upper : 'H', lower: o.lower !== undefined ? o.lower : 'x', descent: o.descent !== undefined ? o.descent : 'p', ascent: o.ascent !== undefined ? o.ascent : 'h', tittle: o.tittle !== undefined ? o.tittle : 'i', overshoot: o.overshoot !== undefined ? o.overshoot : 'O' } var l = Math.ceil(fs * 1.5) canvas.height = l canvas.width = l * .5 ctx.font = font var char = 'H' var result = { top: 0 } // measure line-height ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'top' ctx.fillStyle = 'black' ctx.fillText(char, 0, 0) var topPx = firstTop(ctx.getImageData(0, 0, l, l)) ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'bottom' ctx.fillText(char, 0, l) var bottomPx = firstTop(ctx.getImageData(0, 0, l, l)) result.lineHeight = result.bottom = l - bottomPx + topPx // measure baseline ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'alphabetic' ctx.fillText(char, 0, l) var baselinePx = firstTop(ctx.getImageData(0, 0, l, l)) var baseline = l - baselinePx - 1 + topPx result.baseline = result.alphabetic = baseline // measure median ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'middle' ctx.fillText(char, 0, l * .5) var medianPx = firstTop(ctx.getImageData(0, 0, l, l)) result.median = result.middle = l - medianPx - 1 + topPx - l * .5 // measure hanging ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'hanging' ctx.fillText(char, 0, l * .5) var hangingPx = firstTop(ctx.getImageData(0, 0, l, l)) result.hanging = l - hangingPx - 1 + topPx - l * .5 // measure ideographic ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'ideographic' ctx.fillText(char, 0, l) var ideographicPx = firstTop(ctx.getImageData(0, 0, l, l)) result.ideographic = l - ideographicPx - 1 + topPx // measure cap if (chars.upper) { ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'top' ctx.fillText(chars.upper, 0, 0) result.upper = firstTop(ctx.getImageData(0, 0, l, l)) result.capHeight = (result.baseline - result.upper) } // measure x if (chars.lower) { ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'top' ctx.fillText(chars.lower, 0, 0) result.lower = firstTop(ctx.getImageData(0, 0, l, l)) result.xHeight = (result.baseline - result.lower) } // measure tittle if (chars.tittle) { ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'top' ctx.fillText(chars.tittle, 0, 0) result.tittle = firstTop(ctx.getImageData(0, 0, l, l)) } // measure ascent if (chars.ascent) { ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'top' ctx.fillText(chars.ascent, 0, 0) result.ascent = firstTop(ctx.getImageData(0, 0, l, l)) } // measure descent if (chars.descent) { ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'top' ctx.fillText(chars.descent, 0, 0) result.descent = firstBottom(ctx.getImageData(0, 0, l, l)) } // measure overshoot if (chars.overshoot) { ctx.clearRect(0, 0, l, l) ctx.textBaseline = 'top' ctx.fillText(chars.overshoot, 0, 0) var overshootPx = firstBottom(ctx.getImageData(0, 0, l, l)) result.overshoot = overshootPx - baseline } // normalize result for (var name in result) { result[name] /= fs } result.em = fs measure.cache[family] = result return applyOrigin(result, origin) } function applyOrigin(obj, origin) { var res = {} if (typeof origin === 'string') origin = obj[origin] for (var name in obj) { if (name === 'em') continue res[name] = obj[name] - origin } return res } function firstTop(iData) { var l = iData.height var data = iData.data for (var i = 3; i < data.length; i+=4) { if (data[i] !== 0) { return Math.floor((i - 3) *.25 / l) } } } function firstBottom(iData) { var l = iData.height var data = iData.data for (var i = data.length - 1; i > 0; i -= 4) { if (data[i] !== 0) { return Math.floor((i - 3) *.25 / l) } } } /***/ }), /***/ "7a7d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("8bd8"), supplyDefaults: __webpack_require__("f552"), colorbar: __webpack_require__("fcb3"), calc: __webpack_require__("d0ad"), calcGeoJSON: __webpack_require__("538c").calcGeoJSON, plot: __webpack_require__("538c").plot, style: __webpack_require__("e7ab").style, styleOnSelect: __webpack_require__("e7ab").styleOnSelect, hoverPoints: __webpack_require__("038d"), eventData: __webpack_require__("a9eb"), selectPoints: __webpack_require__("ef6e"), moduleType: 'trace', name: 'choropleth', basePlotModule: __webpack_require__("9e9a"), categories: ['geo', 'noOpacity', 'showLegend'], meta: { } }; /***/ }), /***/ "7abc": /***/ (function(module, exports, __webpack_require__) { /* * World Calendars * https://github.com/alexcjohnson/world-calendars * * Batch-converted from kbwood/calendars * Many thanks to Keith Wood and all of the contributors to the original project! * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* http://keith-wood.name/calendars.html UmmAlQura calendar for jQuery v2.0.2. Written by Amro Osama March 2013. Modified by Binnooh.com & www.elm.sa - 2014 - Added dates back to 1276 Hijri year. Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ var main = __webpack_require__("0230"); var assign = __webpack_require__("320c"); /** Implementation of the UmmAlQura or 'saudi' calendar. See also http://en.wikipedia.org/wiki/Islamic_calendar#Saudi_Arabia.27s_Umm_al-Qura_calendar. http://www.ummulqura.org.sa/About.aspx http://www.staff.science.uu.nl/~gent0113/islam/ummalqura.htm @class UmmAlQuraCalendar @param [language=''] {string} The language code (default English) for localisation. */ function UmmAlQuraCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } UmmAlQuraCalendar.prototype = new main.baseCalendar; assign(UmmAlQuraCalendar.prototype, { /** The calendar name. @memberof UmmAlQuraCalendar */ name: 'UmmAlQura', //jdEpoch: 1948440, // Julian date of start of UmmAlQura epoch: 14 March 1937 CE //daysPerMonth: // Days per month in a common year, replaced by a method. /** true if has a year zero, false if not. @memberof UmmAlQuraCalendar */ hasYearZero: false, /** The minimum month number. @memberof UmmAlQuraCalendar */ minMonth: 1, /** The first month in the year. @memberof UmmAlQuraCalendar */ firstMonth: 1, /** The minimum day number. @memberof UmmAlQuraCalendar */ minDay: 1, /** Localisations for the plugin. Entries are objects indexed by the language code ('' being the default US/English). Each object has the following attributes. @memberof UmmAlQuraCalendar @property name {string} The calendar name. @property epochs {string[]} The epoch names. @property monthNames {string[]} The long names of the months of the year. @property monthNamesShort {string[]} The short names of the months of the year. @property dayNames {string[]} The long names of the days of the week. @property dayNamesShort {string[]} The short names of the days of the week. @property dayNamesMin {string[]} The minimal names of the days of the week. @property dateFormat {string} The date format for this calendar. See the options on formatDate for details. @property firstDay {number} The number of the first day of the week, starting at 0. @property isRTL {number} true if this localisation reads right-to-left. */ regionalOptions: { // Localisations '': { name: 'Umm al-Qura', epochs: ['BH', 'AH'], monthNames: ['Al-Muharram', 'Safar', 'Rabi\' al-awwal', 'Rabi\' Al-Thani', 'Jumada Al-Awwal', 'Jumada Al-Thani', 'Rajab', 'Sha\'aban', 'Ramadan', 'Shawwal', 'Dhu al-Qi\'dah', 'Dhu al-Hijjah'], monthNamesShort: ['Muh', 'Saf', 'Rab1', 'Rab2', 'Jum1', 'Jum2', 'Raj', 'Sha\'', 'Ram', 'Shaw', 'DhuQ', 'DhuH'], dayNames: ['Yawm al-Ahad', 'Yawm al-Ithnain', 'Yawm al-Thalāthā’', 'Yawm al-Arba‘ā’', 'Yawm al-Khamīs', 'Yawm al-Jum‘a', 'Yawm al-Sabt'], dayNamesMin: ['Ah', 'Ith', 'Th', 'Ar', 'Kh', 'Ju', 'Sa'], digits: null, dateFormat: 'yyyy/mm/dd', firstDay: 6, isRTL: true } }, /** Determine whether this date is in a leap year. @memberof UmmAlQuraCalendar @param year {CDate|number} The date to examine or the year to examine. @return {boolean} true if this is a leap year, false if not. @throws Error if an invalid year or a different calendar used. */ leapYear: function (year) { var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear); return (this.daysInYear(date.year()) === 355); }, /** Determine the week of the year for a date. @memberof UmmAlQuraCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {number} The week of the year. @throws Error if an invalid date or a different calendar used. */ weekOfYear: function (year, month, day) { // Find Sunday of this week starting on Sunday var checkDate = this.newDate(year, month, day); checkDate.add(-checkDate.dayOfWeek(), 'd'); return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1; }, /** Retrieve the number of days in a year. @memberof UmmAlQuraCalendar @param year {CDate|number} The date to examine or the year to examine. @return {number} The number of days. @throws Error if an invalid year or a different calendar used. */ daysInYear: function (year) { var daysCount = 0; for (var i = 1; i <= 12; i++) { daysCount += this.daysInMonth(year, i); } return daysCount; }, /** Retrieve the number of days in a month. @memberof UmmAlQuraCalendar @param year {CDate|number} The date to examine or the year of the month. @param [month] {number} The month. @return {number} The number of days in this month. @throws Error if an invalid month/year or a different calendar used. */ daysInMonth: function (year, month) { var date = this._validate(year, month, this.minDay, main.local.invalidMonth); var mcjdn = date.toJD() - 2400000 + 0.5; // Modified Chronological Julian Day Number (MCJDN) // the MCJDN's of the start of the lunations in the Umm al-Qura calendar are stored in the 'ummalqura_dat' array var index = 0; for (var i = 0; i < ummalqura_dat.length; i++) { if (ummalqura_dat[i] > mcjdn) { return (ummalqura_dat[index] - ummalqura_dat[index - 1]); } index++; } return 30; // Unknown outside }, /** Determine whether this date is a week day. @memberof UmmAlQuraCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {boolean} true if a week day, false if not. @throws Error if an invalid date or a different calendar used. */ weekDay: function (year, month, day) { return this.dayOfWeek(year, month, day) !== 5; }, /** Retrieve the Julian date equivalent for this date, i.e. days since January 1, 4713 BCE Greenwich noon. @memberof UmmAlQuraCalendar @param year {CDate|number} The date to convert or the year to convert. @param [month] {number} The month to convert. @param [day] {number} The day to convert. @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function (year, month, day) { var date = this._validate(year, month, day, main.local.invalidDate); var index = (12 * (date.year() - 1)) + date.month() - 15292; var mcjdn = date.day() + ummalqura_dat[index - 1] - 1; return mcjdn + 2400000 - 0.5; // Modified Chronological Julian Day Number (MCJDN) }, /** Create a new date from a Julian date. @memberof UmmAlQuraCalendar @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function (jd) { var mcjdn = jd - 2400000 + 0.5; // Modified Chronological Julian Day Number (MCJDN) // the MCJDN's of the start of the lunations in the Umm al-Qura calendar // are stored in the 'ummalqura_dat' array var index = 0; for (var i = 0; i < ummalqura_dat.length; i++) { if (ummalqura_dat[i] > mcjdn) break; index++; } var lunation = index + 15292; //UmmAlQura Lunation Number var ii = Math.floor((lunation - 1) / 12); var year = ii + 1; var month = lunation - 12 * ii; var day = mcjdn - ummalqura_dat[index - 1] + 1; return this.newDate(year, month, day); }, /** Determine whether a date is valid for this calendar. @memberof UmmAlQuraCalendar @param year {number} The year to examine. @param month {number} The month to examine. @param day {number} The day to examine. @return {boolean} true if a valid date, false if not. */ isValid: function(year, month, day) { var valid = main.baseCalendar.prototype.isValid.apply(this, arguments); if (valid) { year = (year.year != null ? year.year : year); valid = (year >= 1276 && year <= 1500); } return valid; }, /** Check that a candidate date is from the same calendar and is valid. @memberof UmmAlQuraCalendar @private @param year {CDate|number} The date to validate or the year to validate. @param month {number} The month to validate. @param day {number} The day to validate. @param error {string} Error message if invalid. @throws Error if different calendars used or invalid date. */ _validate: function(year, month, day, error) { var date = main.baseCalendar.prototype._validate.apply(this, arguments); if (date.year < 1276 || date.year > 1500) { throw error.replace(/\{0\}/, this.local.name); } return date; } }); // UmmAlQura calendar implementation main.calendars.ummalqura = UmmAlQuraCalendar; var ummalqura_dat = [ 20, 50, 79, 109, 138, 168, 197, 227, 256, 286, 315, 345, 374, 404, 433, 463, 492, 522, 551, 581, 611, 641, 670, 700, 729, 759, 788, 818, 847, 877, 906, 936, 965, 995, 1024, 1054, 1083, 1113, 1142, 1172, 1201, 1231, 1260, 1290, 1320, 1350, 1379, 1409, 1438, 1468, 1497, 1527, 1556, 1586, 1615, 1645, 1674, 1704, 1733, 1763, 1792, 1822, 1851, 1881, 1910, 1940, 1969, 1999, 2028, 2058, 2087, 2117, 2146, 2176, 2205, 2235, 2264, 2294, 2323, 2353, 2383, 2413, 2442, 2472, 2501, 2531, 2560, 2590, 2619, 2649, 2678, 2708, 2737, 2767, 2796, 2826, 2855, 2885, 2914, 2944, 2973, 3003, 3032, 3062, 3091, 3121, 3150, 3180, 3209, 3239, 3268, 3298, 3327, 3357, 3386, 3416, 3446, 3476, 3505, 3535, 3564, 3594, 3623, 3653, 3682, 3712, 3741, 3771, 3800, 3830, 3859, 3889, 3918, 3948, 3977, 4007, 4036, 4066, 4095, 4125, 4155, 4185, 4214, 4244, 4273, 4303, 4332, 4362, 4391, 4421, 4450, 4480, 4509, 4539, 4568, 4598, 4627, 4657, 4686, 4716, 4745, 4775, 4804, 4834, 4863, 4893, 4922, 4952, 4981, 5011, 5040, 5070, 5099, 5129, 5158, 5188, 5218, 5248, 5277, 5307, 5336, 5366, 5395, 5425, 5454, 5484, 5513, 5543, 5572, 5602, 5631, 5661, 5690, 5720, 5749, 5779, 5808, 5838, 5867, 5897, 5926, 5956, 5985, 6015, 6044, 6074, 6103, 6133, 6162, 6192, 6221, 6251, 6281, 6311, 6340, 6370, 6399, 6429, 6458, 6488, 6517, 6547, 6576, 6606, 6635, 6665, 6694, 6724, 6753, 6783, 6812, 6842, 6871, 6901, 6930, 6960, 6989, 7019, 7048, 7078, 7107, 7137, 7166, 7196, 7225, 7255, 7284, 7314, 7344, 7374, 7403, 7433, 7462, 7492, 7521, 7551, 7580, 7610, 7639, 7669, 7698, 7728, 7757, 7787, 7816, 7846, 7875, 7905, 7934, 7964, 7993, 8023, 8053, 8083, 8112, 8142, 8171, 8201, 8230, 8260, 8289, 8319, 8348, 8378, 8407, 8437, 8466, 8496, 8525, 8555, 8584, 8614, 8643, 8673, 8702, 8732, 8761, 8791, 8821, 8850, 8880, 8909, 8938, 8968, 8997, 9027, 9056, 9086, 9115, 9145, 9175, 9205, 9234, 9264, 9293, 9322, 9352, 9381, 9410, 9440, 9470, 9499, 9529, 9559, 9589, 9618, 9648, 9677, 9706, 9736, 9765, 9794, 9824, 9853, 9883, 9913, 9943, 9972, 10002, 10032, 10061, 10090, 10120, 10149, 10178, 10208, 10237, 10267, 10297, 10326, 10356, 10386, 10415, 10445, 10474, 10504, 10533, 10562, 10592, 10621, 10651, 10680, 10710, 10740, 10770, 10799, 10829, 10858, 10888, 10917, 10947, 10976, 11005, 11035, 11064, 11094, 11124, 11153, 11183, 11213, 11242, 11272, 11301, 11331, 11360, 11389, 11419, 11448, 11478, 11507, 11537, 11567, 11596, 11626, 11655, 11685, 11715, 11744, 11774, 11803, 11832, 11862, 11891, 11921, 11950, 11980, 12010, 12039, 12069, 12099, 12128, 12158, 12187, 12216, 12246, 12275, 12304, 12334, 12364, 12393, 12423, 12453, 12483, 12512, 12542, 12571, 12600, 12630, 12659, 12688, 12718, 12747, 12777, 12807, 12837, 12866, 12896, 12926, 12955, 12984, 13014, 13043, 13072, 13102, 13131, 13161, 13191, 13220, 13250, 13280, 13310, 13339, 13368, 13398, 13427, 13456, 13486, 13515, 13545, 13574, 13604, 13634, 13664, 13693, 13723, 13752, 13782, 13811, 13840, 13870, 13899, 13929, 13958, 13988, 14018, 14047, 14077, 14107, 14136, 14166, 14195, 14224, 14254, 14283, 14313, 14342, 14372, 14401, 14431, 14461, 14490, 14520, 14550, 14579, 14609, 14638, 14667, 14697, 14726, 14756, 14785, 14815, 14844, 14874, 14904, 14933, 14963, 14993, 15021, 15051, 15081, 15110, 15140, 15169, 15199, 15228, 15258, 15287, 15317, 15347, 15377, 15406, 15436, 15465, 15494, 15524, 15553, 15582, 15612, 15641, 15671, 15701, 15731, 15760, 15790, 15820, 15849, 15878, 15908, 15937, 15966, 15996, 16025, 16055, 16085, 16114, 16144, 16174, 16204, 16233, 16262, 16292, 16321, 16350, 16380, 16409, 16439, 16468, 16498, 16528, 16558, 16587, 16617, 16646, 16676, 16705, 16734, 16764, 16793, 16823, 16852, 16882, 16912, 16941, 16971, 17001, 17030, 17060, 17089, 17118, 17148, 17177, 17207, 17236, 17266, 17295, 17325, 17355, 17384, 17414, 17444, 17473, 17502, 17532, 17561, 17591, 17620, 17650, 17679, 17709, 17738, 17768, 17798, 17827, 17857, 17886, 17916, 17945, 17975, 18004, 18034, 18063, 18093, 18122, 18152, 18181, 18211, 18241, 18270, 18300, 18330, 18359, 18388, 18418, 18447, 18476, 18506, 18535, 18565, 18595, 18625, 18654, 18684, 18714, 18743, 18772, 18802, 18831, 18860, 18890, 18919, 18949, 18979, 19008, 19038, 19068, 19098, 19127, 19156, 19186, 19215, 19244, 19274, 19303, 19333, 19362, 19392, 19422, 19452, 19481, 19511, 19540, 19570, 19599, 19628, 19658, 19687, 19717, 19746, 19776, 19806, 19836, 19865, 19895, 19924, 19954, 19983, 20012, 20042, 20071, 20101, 20130, 20160, 20190, 20219, 20249, 20279, 20308, 20338, 20367, 20396, 20426, 20455, 20485, 20514, 20544, 20573, 20603, 20633, 20662, 20692, 20721, 20751, 20780, 20810, 20839, 20869, 20898, 20928, 20957, 20987, 21016, 21046, 21076, 21105, 21135, 21164, 21194, 21223, 21253, 21282, 21312, 21341, 21371, 21400, 21430, 21459, 21489, 21519, 21548, 21578, 21607, 21637, 21666, 21696, 21725, 21754, 21784, 21813, 21843, 21873, 21902, 21932, 21962, 21991, 22021, 22050, 22080, 22109, 22138, 22168, 22197, 22227, 22256, 22286, 22316, 22346, 22375, 22405, 22434, 22464, 22493, 22522, 22552, 22581, 22611, 22640, 22670, 22700, 22730, 22759, 22789, 22818, 22848, 22877, 22906, 22936, 22965, 22994, 23024, 23054, 23083, 23113, 23143, 23173, 23202, 23232, 23261, 23290, 23320, 23349, 23379, 23408, 23438, 23467, 23497, 23527, 23556, 23586, 23616, 23645, 23674, 23704, 23733, 23763, 23792, 23822, 23851, 23881, 23910, 23940, 23970, 23999, 24029, 24058, 24088, 24117, 24147, 24176, 24206, 24235, 24265, 24294, 24324, 24353, 24383, 24413, 24442, 24472, 24501, 24531, 24560, 24590, 24619, 24648, 24678, 24707, 24737, 24767, 24796, 24826, 24856, 24885, 24915, 24944, 24974, 25003, 25032, 25062, 25091, 25121, 25150, 25180, 25210, 25240, 25269, 25299, 25328, 25358, 25387, 25416, 25446, 25475, 25505, 25534, 25564, 25594, 25624, 25653, 25683, 25712, 25742, 25771, 25800, 25830, 25859, 25888, 25918, 25948, 25977, 26007, 26037, 26067, 26096, 26126, 26155, 26184, 26214, 26243, 26272, 26302, 26332, 26361, 26391, 26421, 26451, 26480, 26510, 26539, 26568, 26598, 26627, 26656, 26686, 26715, 26745, 26775, 26805, 26834, 26864, 26893, 26923, 26952, 26982, 27011, 27041, 27070, 27099, 27129, 27159, 27188, 27218, 27248, 27277, 27307, 27336, 27366, 27395, 27425, 27454, 27484, 27513, 27542, 27572, 27602, 27631, 27661, 27691, 27720, 27750, 27779, 27809, 27838, 27868, 27897, 27926, 27956, 27985, 28015, 28045, 28074, 28104, 28134, 28163, 28193, 28222, 28252, 28281, 28310, 28340, 28369, 28399, 28428, 28458, 28488, 28517, 28547, 28577, // From 1356 28607, 28636, 28665, 28695, 28724, 28754, 28783, 28813, 28843, 28872, 28901, 28931, 28960, 28990, 29019, 29049, 29078, 29108, 29137, 29167, 29196, 29226, 29255, 29285, 29315, 29345, 29375, 29404, 29434, 29463, 29492, 29522, 29551, 29580, 29610, 29640, 29669, 29699, 29729, 29759, 29788, 29818, 29847, 29876, 29906, 29935, 29964, 29994, 30023, 30053, 30082, 30112, 30141, 30171, 30200, 30230, 30259, 30289, 30318, 30348, 30378, 30408, 30437, 30467, 30496, 30526, 30555, 30585, 30614, 30644, 30673, 30703, 30732, 30762, 30791, 30821, 30850, 30880, 30909, 30939, 30968, 30998, 31027, 31057, 31086, 31116, 31145, 31175, 31204, 31234, 31263, 31293, 31322, 31352, 31381, 31411, 31441, 31471, 31500, 31530, 31559, 31589, 31618, 31648, 31676, 31706, 31736, 31766, 31795, 31825, 31854, 31884, 31913, 31943, 31972, 32002, 32031, 32061, 32090, 32120, 32150, 32180, 32209, 32239, 32268, 32298, 32327, 32357, 32386, 32416, 32445, 32475, 32504, 32534, 32563, 32593, 32622, 32652, 32681, 32711, 32740, 32770, 32799, 32829, 32858, 32888, 32917, 32947, 32976, 33006, 33035, 33065, 33094, 33124, 33153, 33183, 33213, 33243, 33272, 33302, 33331, 33361, 33390, 33420, 33450, 33479, 33509, 33539, 33568, 33598, 33627, 33657, 33686, 33716, 33745, 33775, 33804, 33834, 33863, 33893, 33922, 33952, 33981, 34011, 34040, 34069, 34099, 34128, 34158, 34187, 34217, 34247, 34277, 34306, 34336, 34365, 34395, 34424, 34454, 34483, 34512, 34542, 34571, 34601, 34631, 34660, 34690, 34719, 34749, 34778, 34808, 34837, 34867, 34896, 34926, 34955, 34985, 35015, 35044, 35074, 35103, 35133, 35162, 35192, 35222, 35251, 35280, 35310, 35340, 35370, 35399, 35429, 35458, 35488, 35517, 35547, 35576, 35605, 35635, 35665, 35694, 35723, 35753, 35782, 35811, 35841, 35871, 35901, 35930, 35960, 35989, 36019, 36048, 36078, 36107, 36136, 36166, 36195, 36225, 36254, 36284, 36314, 36343, 36373, 36403, 36433, 36462, 36492, 36521, 36551, 36580, 36610, 36639, 36669, 36698, 36728, 36757, 36786, 36816, 36845, 36875, 36904, 36934, 36963, 36993, 37022, 37052, 37081, 37111, 37141, 37170, 37200, 37229, 37259, 37288, 37318, 37347, 37377, 37406, 37436, 37465, 37495, 37524, 37554, 37584, 37613, 37643, 37672, 37701, 37731, 37760, 37790, 37819, 37849, 37878, 37908, 37938, 37967, 37997, 38027, 38056, 38085, 38115, 38144, 38174, 38203, 38233, 38262, 38292, 38322, 38351, 38381, 38410, 38440, 38469, 38499, 38528, 38558, 38587, 38617, 38646, 38676, 38705, 38735, 38764, 38794, 38823, 38853, 38882, 38912, 38941, 38971, 39001, 39030, 39059, 39089, 39118, 39148, 39178, 39208, 39237, 39267, 39297, 39326, 39355, 39385, 39414, 39444, 39473, 39503, 39532, 39562, 39592, 39621, 39650, 39680, 39709, 39739, 39768, 39798, 39827, 39857, 39886, 39916, 39946, 39975, 40005, 40035, 40064, 40094, 40123, 40153, 40182, 40212, 40241, 40271, 40300, 40330, 40359, 40389, 40418, 40448, 40477, 40507, 40536, 40566, 40595, 40625, 40655, 40685, 40714, 40744, 40773, 40803, 40832, 40862, 40892, 40921, 40951, 40980, 41009, 41039, 41068, 41098, 41127, 41157, 41186, 41216, 41245, 41275, 41304, 41334, 41364, 41393, 41422, 41452, 41481, 41511, 41540, 41570, 41599, 41629, 41658, 41688, 41718, 41748, 41777, 41807, 41836, 41865, 41894, 41924, 41953, 41983, 42012, 42042, 42072, 42102, 42131, 42161, 42190, 42220, 42249, 42279, 42308, 42337, 42367, 42397, 42426, 42456, 42485, 42515, 42545, 42574, 42604, 42633, 42662, 42692, 42721, 42751, 42780, 42810, 42839, 42869, 42899, 42929, 42958, 42988, 43017, 43046, 43076, 43105, 43135, 43164, 43194, 43223, 43253, 43283, 43312, 43342, 43371, 43401, 43430, 43460, 43489, 43519, 43548, 43578, 43607, 43637, 43666, 43696, 43726, 43755, 43785, 43814, 43844, 43873, 43903, 43932, 43962, 43991, 44021, 44050, 44080, 44109, 44139, 44169, 44198, 44228, 44258, 44287, 44317, 44346, 44375, 44405, 44434, 44464, 44493, 44523, 44553, 44582, 44612, 44641, 44671, 44700, 44730, 44759, 44788, 44818, 44847, 44877, 44906, 44936, 44966, 44996, 45025, 45055, 45084, 45114, 45143, 45172, 45202, 45231, 45261, 45290, 45320, 45350, 45380, 45409, 45439, 45468, 45498, 45527, 45556, 45586, 45615, 45644, 45674, 45704, 45733, 45763, 45793, 45823, 45852, 45882, 45911, 45940, 45970, 45999, 46028, 46058, 46088, 46117, 46147, 46177, 46206, 46236, 46265, 46295, 46324, 46354, 46383, 46413, 46442, 46472, 46501, 46531, 46560, 46590, 46620, 46649, 46679, 46708, 46738, 46767, 46797, 46826, 46856, 46885, 46915, 46944, 46974, 47003, 47033, 47063, 47092, 47122, 47151, 47181, 47210, 47240, 47269, 47298, 47328, 47357, 47387, 47417, 47446, 47476, 47506, 47535, 47565, 47594, 47624, 47653, 47682, 47712, 47741, 47771, 47800, 47830, 47860, 47890, 47919, 47949, 47978, 48008, 48037, 48066, 48096, 48125, 48155, 48184, 48214, 48244, 48273, 48303, 48333, 48362, 48392, 48421, 48450, 48480, 48509, 48538, 48568, 48598, 48627, 48657, 48687, 48717, 48746, 48776, 48805, 48834, 48864, 48893, 48922, 48952, 48982, 49011, 49041, 49071, 49100, 49130, 49160, 49189, 49218, 49248, 49277, 49306, 49336, 49365, 49395, 49425, 49455, 49484, 49514, 49543, 49573, 49602, 49632, 49661, 49690, 49720, 49749, 49779, 49809, 49838, 49868, 49898, 49927, 49957, 49986, 50016, 50045, 50075, 50104, 50133, 50163, 50192, 50222, 50252, 50281, 50311, 50340, 50370, 50400, 50429, 50459, 50488, 50518, 50547, 50576, 50606, 50635, 50665, 50694, 50724, 50754, 50784, 50813, 50843, 50872, 50902, 50931, 50960, 50990, 51019, 51049, 51078, 51108, 51138, 51167, 51197, 51227, 51256, 51286, 51315, 51345, 51374, 51403, 51433, 51462, 51492, 51522, 51552, 51582, 51611, 51641, 51670, 51699, 51729, 51758, 51787, 51816, 51846, 51876, 51906, 51936, 51965, 51995, 52025, 52054, 52083, 52113, 52142, 52171, 52200, 52230, 52260, 52290, 52319, 52349, 52379, 52408, 52438, 52467, 52497, 52526, 52555, 52585, 52614, 52644, 52673, 52703, 52733, 52762, 52792, 52822, 52851, 52881, 52910, 52939, 52969, 52998, 53028, 53057, 53087, 53116, 53146, 53176, 53205, 53235, 53264, 53294, 53324, 53353, 53383, 53412, 53441, 53471, 53500, 53530, 53559, 53589, 53619, 53648, 53678, 53708, 53737, 53767, 53796, 53825, 53855, 53884, 53913, 53943, 53973, 54003, 54032, 54062, 54092, 54121, 54151, 54180, 54209, 54239, 54268, 54297, 54327, 54357, 54387, 54416, 54446, 54476, 54505, 54535, 54564, 54593, 54623, 54652, 54681, 54711, 54741, 54770, 54800, 54830, 54859, 54889, 54919, 54948, 54977, 55007, 55036, 55066, 55095, 55125, 55154, 55184, 55213, 55243, 55273, 55302, 55332, 55361, 55391, 55420, 55450, 55479, 55508, 55538, 55567, 55597, 55627, 55657, 55686, 55716, 55745, 55775, 55804, 55834, 55863, 55892, 55922, 55951, 55981, 56011, 56040, 56070, 56100, 56129, 56159, 56188, 56218, 56247, 56276, 56306, 56335, 56365, 56394, 56424, 56454, 56483, 56513, 56543, 56572, 56601, 56631, 56660, 56690, 56719, 56749, 56778, 56808, 56837, 56867, 56897, 56926, 56956, 56985, 57015, 57044, 57074, 57103, 57133, 57162, 57192, 57221, 57251, 57280, 57310, 57340, 57369, 57399, 57429, 57458, 57487, 57517, 57546, 57576, 57605, 57634, 57664, 57694, 57723, 57753, 57783, 57813, 57842, 57871, 57901, 57930, 57959, 57989, 58018, 58048, 58077, 58107, 58137, 58167, 58196, 58226, 58255, 58285, 58314, 58343, 58373, 58402, 58432, 58461, 58491, 58521, 58551, 58580, 58610, 58639, 58669, 58698, 58727, 58757, 58786, 58816, 58845, 58875, 58905, 58934, 58964, 58994, 59023, 59053, 59082, 59111, 59141, 59170, 59200, 59229, 59259, 59288, 59318, 59348, 59377, 59407, 59436, 59466, 59495, 59525, 59554, 59584, 59613, 59643, 59672, 59702, 59731, 59761, 59791, 59820, 59850, 59879, 59909, 59939, 59968, 59997, 60027, 60056, 60086, 60115, 60145, 60174, 60204, 60234, 60264, 60293, 60323, 60352, 60381, 60411, 60440, 60469, 60499, 60528, 60558, 60588, 60618, 60648, 60677, 60707, 60736, 60765, 60795, 60824, 60853, 60883, 60912, 60942, 60972, 61002, 61031, 61061, 61090, 61120, 61149, 61179, 61208, 61237, 61267, 61296, 61326, 61356, 61385, 61415, 61445, 61474, 61504, 61533, 61563, 61592, 61621, 61651, 61680, 61710, 61739, 61769, 61799, 61828, 61858, 61888, 61917, 61947, 61976, 62006, 62035, 62064, 62094, 62123, 62153, 62182, 62212, 62242, 62271, 62301, 62331, 62360, 62390, 62419, 62448, 62478, 62507, 62537, 62566, 62596, 62625, 62655, 62685, 62715, 62744, 62774, 62803, 62832, 62862, 62891, 62921, 62950, 62980, 63009, 63039, 63069, 63099, 63128, 63157, 63187, 63216, 63246, 63275, 63305, 63334, 63363, 63393, 63423, 63453, 63482, 63512, 63541, 63571, 63600, 63630, 63659, 63689, 63718, 63747, 63777, 63807, 63836, 63866, 63895, 63925, 63955, 63984, 64014, 64043, 64073, 64102, 64131, 64161, 64190, 64220, 64249, 64279, 64309, 64339, 64368, 64398, 64427, 64457, 64486, 64515, 64545, 64574, 64603, 64633, 64663, 64692, 64722, 64752, 64782, 64811, 64841, 64870, 64899, 64929, 64958, 64987, 65017, 65047, 65076, 65106, 65136, 65166, 65195, 65225, 65254, 65283, 65313, 65342, 65371, 65401, 65431, 65460, 65490, 65520, 65549, 65579, 65608, 65638, 65667, 65697, 65726, 65755, 65785, 65815, 65844, 65874, 65903, 65933, 65963, 65992, 66022, 66051, 66081, 66110, 66140, 66169, 66199, 66228, 66258, 66287, 66317, 66346, 66376, 66405, 66435, 66465, 66494, 66524, 66553, 66583, 66612, 66641, 66671, 66700, 66730, 66760, 66789, 66819, 66849, 66878, 66908, 66937, 66967, 66996, 67025, 67055, 67084, 67114, 67143, 67173, 67203, 67233, 67262, 67292, 67321, 67351, 67380, 67409, 67439, 67468, 67497, 67527, 67557, 67587, 67617, 67646, 67676, 67705, 67735, 67764, 67793, 67823, 67852, 67882, 67911, 67941, 67971, 68000, 68030, 68060, 68089, 68119, 68148, 68177, 68207, 68236, 68266, 68295, 68325, 68354, 68384, 68414, 68443, 68473, 68502, 68532, 68561, 68591, 68620, 68650, 68679, 68708, 68738, 68768, 68797, 68827, 68857, 68886, 68916, 68946, 68975, 69004, 69034, 69063, 69092, 69122, 69152, 69181, 69211, 69240, 69270, 69300, 69330, 69359, 69388, 69418, 69447, 69476, 69506, 69535, 69565, 69595, 69624, 69654, 69684, 69713, 69743, 69772, 69802, 69831, 69861, 69890, 69919, 69949, 69978, 70008, 70038, 70067, 70097, 70126, 70156, 70186, 70215, 70245, 70274, 70303, 70333, 70362, 70392, 70421, 70451, 70481, 70510, 70540, 70570, 70599, 70629, 70658, 70687, 70717, 70746, 70776, 70805, 70835, 70864, 70894, 70924, 70954, 70983, 71013, 71042, 71071, 71101, 71130, 71159, 71189, 71218, 71248, 71278, 71308, 71337, 71367, 71397, 71426, 71455, 71485, 71514, 71543, 71573, 71602, 71632, 71662, 71691, 71721, 71751, 71781, 71810, 71839, 71869, 71898, 71927, 71957, 71986, 72016, 72046, 72075, 72105, 72135, 72164, 72194, 72223, 72253, 72282, 72311, 72341, 72370, 72400, 72429, 72459, 72489, 72518, 72548, 72577, 72607, 72637, 72666, 72695, 72725, 72754, 72784, 72813, 72843, 72872, 72902, 72931, 72961, 72991, 73020, 73050, 73080, 73109, 73139, 73168, 73197, 73227, 73256, 73286, 73315, 73345, 73375, 73404, 73434, 73464, 73493, 73523, 73552, 73581, 73611, 73640, 73669, 73699, 73729, 73758, 73788, 73818, 73848, 73877, 73907, 73936, 73965, 73995, 74024, 74053, 74083, 74113, 74142, 74172, 74202, 74231, 74261, 74291, 74320, 74349, 74379, 74408, 74437, 74467, 74497, 74526, 74556, 74586, 74615, 74645, 74675, 74704, 74733, 74763, 74792, 74822, 74851, 74881, 74910, 74940, 74969, 74999, 75029, 75058, 75088, 75117, 75147, 75176, 75206, 75235, 75264, 75294, 75323, 75353, 75383, 75412, 75442, 75472, 75501, 75531, 75560, 75590, 75619, 75648, 75678, 75707, 75737, 75766, 75796, 75826, 75856, 75885, 75915, 75944, 75974, 76003, 76032, 76062, 76091, 76121, 76150, 76180, 76210, 76239, 76269, 76299, 76328, 76358, 76387, 76416, 76446, 76475, 76505, 76534, 76564, 76593, 76623, 76653, 76682, 76712, 76741, 76771, 76801, 76830, 76859, 76889, 76918, 76948, 76977, 77007, 77036, 77066, 77096, 77125, 77155, 77185, 77214, 77243, 77273, 77302, 77332, 77361, 77390, 77420, 77450, 77479, 77509, 77539, 77569, 77598, 77627, 77657, 77686, 77715, 77745, 77774, 77804, 77833, 77863, 77893, 77923, 77952, 77982, 78011, 78041, 78070, 78099, 78129, 78158, 78188, 78217, 78247, 78277, 78307, 78336, 78366, 78395, 78425, 78454, 78483, 78513, 78542, 78572, 78601, 78631, 78661, 78690, 78720, 78750, 78779, 78808, 78838, 78867, 78897, 78926, 78956, 78985, 79015, 79044, 79074, 79104, 79133, 79163, 79192, 79222, 79251, 79281, 79310, 79340, 79369, 79399, 79428, 79458, 79487, 79517, 79546, 79576, 79606, 79635, 79665, 79695, 79724, 79753, 79783, 79812, 79841, 79871, 79900, 79930, 79960, 79990]; /***/ }), /***/ "7ad0": /***/ (function(module, exports) { module.exports = perspective; /** * Generates a perspective projection matrix with the given bounds * * @param {mat4} out mat4 frustum matrix will be written into * @param {number} fovy Vertical field of view in radians * @param {number} aspect Aspect ratio. typically viewport width/height * @param {number} near Near bound of the frustum * @param {number} far Far bound of the frustum * @returns {mat4} out */ function perspective(out, fovy, aspect, near, far) { var f = 1.0 / Math.tan(fovy / 2), nf = 1 / (near - far); out[0] = f / aspect; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = f; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = (far + near) * nf; out[11] = -1; out[12] = 0; out[13] = 0; out[14] = (2 * far * near) * nf; out[15] = 0; return out; }; /***/ }), /***/ "7ae4": /***/ (function(module, exports) { module.exports = lerp /** * Performs a linear interpolation between two vec4's * * @param {vec4} out the receiving vector * @param {vec4} a the first operand * @param {vec4} b the second operand * @param {Number} t interpolation amount between the two inputs * @returns {vec4} out */ function lerp (out, a, b, t) { var ax = a[0], ay = a[1], az = a[2], aw = a[3] out[0] = ax + t * (b[0] - ax) out[1] = ay + t * (b[1] - ay) out[2] = az + t * (b[2] - az) out[3] = aw + t * (b[3] - aw) return out } /***/ }), /***/ "7b0b": /***/ (function(module, exports, __webpack_require__) { var requireObjectCoercible = __webpack_require__("1d80"); // `ToObject` abstract operation // https://tc39.github.io/ecma262/#sec-toobject module.exports = function (argument) { return Object(requireObjectCoercible(argument)); }; /***/ }), /***/ "7b1c": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * @module update-diff */ module.exports = function updateDiff (obj, diff, mappers) { if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2) for (var i = 0, l = mappers.length; i < l; i++) { var dict = mappers[i] for (var prop in dict) { if (diff[prop] !== undefined && !Array.isArray(diff[prop]) && obj[prop] === diff[prop]) continue if (prop in diff) { var result if (dict[prop] === true) result = diff[prop] else if (dict[prop] === false) continue else if (typeof dict[prop] === 'function') { result = dict[prop](diff[prop], obj, diff) if (result === undefined) continue } obj[prop] = result } } } return obj } /***/ }), /***/ "7ba3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { sunburstcolorway: { valType: 'colorlist', editType: 'calc', }, extendsunburstcolors: { valType: 'boolean', dflt: true, editType: 'calc', } }; /***/ }), /***/ "7bb3": /***/ (function(module, exports) { module.exports = dot /** * Calculates the dot product of two vec4's * * @param {vec4} a the first operand * @param {vec4} b the second operand * @returns {Number} dot product of a and b */ function dot (a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3] } /***/ }), /***/ "7bbc": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = alphaComplex var delaunay = __webpack_require__("2357") var circumradius = __webpack_require__("8662") function alphaComplex(alpha, points) { return delaunay(points).filter(function(cell) { var simplex = new Array(cell.length) for(var i=0; i 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; } } /***/ }), /***/ "7c4a": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__("ff55")() ? globalThis : __webpack_require__("c2c0"); /***/ }), /***/ "7c67": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = permutationSign var BRUTE_FORCE_CUTOFF = 32 var pool = __webpack_require__("cea5") function permutationSign(p) { var n = p.length if(n < BRUTE_FORCE_CUTOFF) { //Use quadratic algorithm for small n var sgn = 1 for(var i=0; i 7) { result.push(seg.splice(0, 7)) seg.unshift('C') } break case 'S': // default control point var cx = x var cy = y if (prev == 'C' || prev == 'S') { cx += cx - bezierX // reflect the previous command's control cy += cy - bezierY // point relative to the current point } seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]] break case 'T': if (prev == 'Q' || prev == 'T') { quadX = x * 2 - quadX // as with 'S' reflect previous control point quadY = y * 2 - quadY } else { quadX = x quadY = y } seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]) break case 'Q': quadX = seg[1] quadY = seg[2] seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]) break case 'L': seg = line(x, y, seg[1], seg[2]) break case 'H': seg = line(x, y, seg[1], y) break case 'V': seg = line(x, y, x, seg[1]) break case 'Z': seg = line(x, y, startX, startY) break } // update state prev = command x = seg[seg.length - 2] y = seg[seg.length - 1] if (seg.length > 4) { bezierX = seg[seg.length - 4] bezierY = seg[seg.length - 3] } else { bezierX = x bezierY = y } result.push(seg) } return result } function line(x1, y1, x2, y2){ return ['C', x1, y1, x2, y2, x2, y2] } function quadratic(x1, y1, cx, cy, x2, y2){ return [ 'C', x1/3 + (2/3) * cx, y1/3 + (2/3) * cy, x2/3 + (2/3) * cx, y2/3 + (2/3) * cy, x2, y2 ] } // This function is ripped from // github.com/DmitryBaranovskiy/raphael/blob/4d97d4/raphael.js#L2216-L2304 // which references w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // TODO: make it human readable function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { if (!recursive) { var xy = rotate(x1, y1, -angle) x1 = xy.x y1 = xy.y xy = rotate(x2, y2, -angle) x2 = xy.x y2 = xy.y var x = (x1 - x2) / 2 var y = (y1 - y2) / 2 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry) if (h > 1) { h = Math.sqrt(h) rx = h * rx ry = h * ry } var rx2 = rx * rx var ry2 = ry * ry var k = (large_arc_flag == sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))) if (k == Infinity) k = 1 // neutralize var cx = k * rx * y / ry + (x1 + x2) / 2 var cy = k * -ry * x / rx + (y1 + y2) / 2 var f1 = Math.asin(((y1 - cy) / ry).toFixed(9)) var f2 = Math.asin(((y2 - cy) / ry).toFixed(9)) f1 = x1 < cx ? π - f1 : f1 f2 = x2 < cx ? π - f2 : f2 if (f1 < 0) f1 = π * 2 + f1 if (f2 < 0) f2 = π * 2 + f2 if (sweep_flag && f1 > f2) f1 = f1 - π * 2 if (!sweep_flag && f2 > f1) f2 = f2 - π * 2 } else { f1 = recursive[0] f2 = recursive[1] cx = recursive[2] cy = recursive[3] } // greater than 120 degrees requires multiple segments if (Math.abs(f2 - f1) > _120) { var f2old = f2 var x2old = x2 var y2old = y2 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1) x2 = cx + rx * Math.cos(f2) y2 = cy + ry * Math.sin(f2) var res = arc(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]) } var t = Math.tan((f2 - f1) / 4) var hx = 4 / 3 * rx * t var hy = 4 / 3 * ry * t var curve = [ 2 * x1 - (x1 + hx * Math.sin(f1)), 2 * y1 - (y1 - hy * Math.cos(f1)), x2 + hx * Math.sin(f2), y2 - hy * Math.cos(f2), x2, y2 ] if (recursive) return curve if (res) curve = curve.concat(res) for (var i = 0; i < curve.length;) { var rot = rotate(curve[i], curve[i+1], angle) curve[i++] = rot.x curve[i++] = rot.y } return curve } function rotate(x, y, rad){ return { x: x * Math.cos(rad) - y * Math.sin(rad), y: x * Math.sin(rad) + y * Math.cos(rad) } } function radians(degress){ return degress * (π / 180) } /***/ }), /***/ "7c73": /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__("825a"); var defineProperties = __webpack_require__("37e8"); var enumBugKeys = __webpack_require__("7839"); var hiddenKeys = __webpack_require__("d012"); var html = __webpack_require__("1be4"); var documentCreateElement = __webpack_require__("cc12"); var sharedKey = __webpack_require__("f772"); var GT = '>'; var LT = '<'; var PROTOTYPE = 'prototype'; var SCRIPT = 'script'; var IE_PROTO = sharedKey('IE_PROTO'); var EmptyConstructor = function () { /* empty */ }; var scriptTag = function (content) { return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; }; // Create object with fake `null` prototype: use ActiveX Object with cleared prototype var NullProtoObjectViaActiveX = function (activeXDocument) { activeXDocument.write(scriptTag('')); activeXDocument.close(); var temp = activeXDocument.parentWindow.Object; activeXDocument = null; // avoid memory leak return temp; }; // Create object with fake `null` prototype: use iframe Object with cleared prototype var NullProtoObjectViaIFrame = function () { // Thrash, waste and sodomy: IE GC bug var iframe = documentCreateElement('iframe'); var JS = 'java' + SCRIPT + ':'; var iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); // https://github.com/zloirock/core-js/issues/475 iframe.src = String(JS); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(scriptTag('document.F=Object')); iframeDocument.close(); return iframeDocument.F; }; // Check for document.domain and active x support // No need to use active x approach when document.domain is not set // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 // avoid IE GC bug var activeXDocument; var NullProtoObject = function () { try { /* global ActiveXObject */ activeXDocument = document.domain && new ActiveXObject('htmlfile'); } catch (error) { /* ignore */ } NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame(); var length = enumBugKeys.length; while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; return NullProtoObject(); }; hiddenKeys[IE_PROTO] = true; // `Object.create` method // https://tc39.github.io/ecma262/#sec-object.create module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { EmptyConstructor[PROTOTYPE] = anObject(O); result = new EmptyConstructor(); EmptyConstructor[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = NullProtoObject(); return Properties === undefined ? result : defineProperties(result, Properties); }; /***/ }), /***/ "7c9f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { moduleType: 'component', name: 'images', layoutAttributes: __webpack_require__("d72e"), supplyLayoutDefaults: __webpack_require__("4b6a"), includeBasePlot: __webpack_require__("37d1")('images'), draw: __webpack_require__("ff49"), convertCoords: __webpack_require__("6174") }; /***/ }), /***/ "7d72": /***/ (function(module, exports, __webpack_require__) { "use strict"; // Exports true if environment provides native `WeakMap` implementation, whatever that is. module.exports = (function () { if (typeof WeakMap !== "function") return false; return Object.prototype.toString.call(new WeakMap()) === "[object WeakMap]"; }()); /***/ }), /***/ "7d88": /***/ (function(module, exports, __webpack_require__) { "use strict"; var safeToString = __webpack_require__("1e0a"); var reNewLine = /[\n\r\u2028\u2029]/g; module.exports = function (value) { var string = safeToString(value); if (string === null) return ""; // Trim if too long if (string.length > 100) string = string.slice(0, 99) + "…"; // Replace eventual new lines string = string.replace(reNewLine, function (char) { switch (char) { case "\n": return "\\n"; case "\r": return "\\r"; case "\u2028": return "\\u2028"; case "\u2029": return "\\u2029"; /* istanbul ignore next */ default: throw new Error("Unexpected character"); } }); return string; }; /***/ }), /***/ "7dbb": /***/ (function(module, exports, __webpack_require__) { (function(aa,ia){ true?module.exports=ia():undefined})(this,function(){function aa(a,b){this.id=Ab++;this.type=a;this.data=b}function ia(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1>>=b;c=(255>>=c;b|=c;c=(15>>=c;b|=c;c=(3>>c>>1}function cb(){function a(a){a:{for(var b=16;268435456>=b;b*=16)if(a<=b){a=b;break a}a=0}b=c[bb(a)>>2];return 0>2].push(a)}var c=J(8,function(){return[]});return{alloc:a,free:b,allocType:function(b,c){var d=null;switch(b){case 5120:d=new Int8Array(a(c),0,c);break;case 5121:d=new Uint8Array(a(c),0,c);break;case 5122:d=new Int16Array(a(2*c),0,c);break;case 5123:d=new Uint16Array(a(2*c),0,c);break;case 5124:d=new Int32Array(a(4*c),0,c);break;case 5125:d=new Uint32Array(a(4*c),0,c);break;case 5126:d=new Float32Array(a(4*c),0,c);break;default:return null}return d.length!== c?d.subarray(0,c):d},freeType:function(a){b(a.buffer)}}}function ma(a){return!!a&&"object"===typeof a&&Array.isArray(a.shape)&&Array.isArray(a.stride)&&"number"===typeof a.offset&&a.shape.length===a.stride.length&&(Array.isArray(a.data)||M(a.data))}function db(a,b,c,e,g,d){for(var p=0;pd&&(d=e.buffer.byteLength,5123===f?d>>=1:5125===f&&(d>>=2));e.vertCount=d;d=h;0>h&&(d=4,h=e.buffer.dimension,1===h&&(d=0),2===h&&(d=1),3===h&&(d=4));e.primType=d}function p(a){e.elementsCount--;delete f[a.id];a.buffer.destroy();a.buffer=null}var f={},r=0,q={uint8:5121, uint16:5123};b.oes_element_index_uint&&(q.uint32=5125);g.prototype.bind=function(){this.buffer.bind()};var t=[];return{create:function(a,b){function k(a){if(a)if("number"===typeof a)h(a),l.primType=4,l.vertCount=a|0,l.type=5121;else{var b=null,c=35044,e=-1,g=-1,f=0,m=0;if(Array.isArray(a)||M(a)||ma(a))b=a;else if("data"in a&&(b=a.data),"usage"in a&&(c=jb[a.usage]),"primitive"in a&&(e=Sa[a.primitive]),"count"in a&&(g=a.count|0),"type"in a&&(m=q[a.type]),"length"in a)f=a.length|0;else if(f=g,5123=== m||5122===m)f*=2;else if(5125===m||5124===m)f*=4;d(l,b,c,e,g,f,m)}else h(),l.primType=4,l.vertCount=0,l.type=5121;return k}var h=c.create(null,34963,!0),l=new g(h._buffer);e.elementsCount++;k(a);k._reglType="elements";k._elements=l;k.subdata=function(a,b){h.subdata(a,b);return k};k.destroy=function(){p(l)};return k},createStream:function(a){var b=t.pop();b||(b=new g(c.create(null,34963,!0,!1)._buffer));d(b,a,35040,-1,-1,0,0);return b},destroyStream:function(a){t.push(a)},getElements:function(a){return"function"=== typeof a&&a._elements instanceof g?a._elements:null},clear:function(){S(f).forEach(p)}}}function kb(a){for(var b=x.allocType(5123,a.length),c=0;c>>31<<15,d=(e<<1>>>24)-127,e=e>>13&1023;b[c]=-24>d?g:-14>d?g+(e+1024>>-14-d):15>=e,c.height>>=e,C(c,d[e]),a.mipmask|=1<b;++b)a.images[b]=null;return a}function ib(a){for(var b=a.images,c=0;cb){for(var c=0;c=--this.refCount&&A(this)}});p.profile&&(d.getTotalTextureSize=function(){var a=0;Object.keys(X).forEach(function(b){a+=X[b].stats.size});return a});return{create2D:function(b,c){function e(a,b){var c=f.texInfo;z.call(c);var d=D();"number"===typeof a?"number"===typeof b? v(d,a|0,b|0):v(d,a|0,a|0):a?(O(c,a),N(d,a)):v(d,1,1);c.genMipmaps&&(d.mipmask=(d.width<<1)-1);f.mipmask=d.mipmask;r(f,d);f.internalformat=d.internalformat;e.width=d.width;e.height=d.height;T(f);B(d,3553);R(c,3553);Aa();ib(d);p.profile&&(f.stats.size=Ja(f.internalformat,f.type,d.width,d.height,c.genMipmaps,!1));e.format=J[f.internalformat];e.type=da[f.type];e.mag=oa[c.magFilter];e.min=za[c.minFilter];e.wrapS=ka[c.wrapS];e.wrapT=ka[c.wrapT];return e}var f=new F(3553);X[f.id]=f;d.textureCount++;e(b, c);e.subimage=function(a,b,c,d){b|=0;c|=0;d|=0;var n=h();r(n,f);n.width=0;n.height=0;C(n,a);n.width=n.width||(f.width>>d)-b;n.height=n.height||(f.height>>d)-c;T(f);k(n,3553,b,c,d);Aa();l(n);return e};e.resize=function(b,c){var d=b|0,h=c|0||d;if(d===f.width&&h===f.height)return e;e.width=f.width=d;e.height=f.height=h;T(f);for(var n,w=f.channels,y=f.type,I=0;f.mipmask>>I;++I){var fa=d>>I,ga=h>>I;if(!fa||!ga)break;n=x.zero.allocType(y,fa*ga*w);a.texImage2D(3553,I,f.format,fa,ga,0,f.format,f.type,n); n&&x.zero.freeType(n)}Aa();p.profile&&(f.stats.size=Ja(f.internalformat,f.type,d,h,!1,!1));return e};e._reglType="texture2d";e._texture=f;p.profile&&(e.stats=f.stats);e.destroy=function(){f.decRef()};return e},createCube:function(b,c,e,f,g,ua){function A(a,b,c,d,e,f){var H,Y=m.texInfo;z.call(Y);for(H=0;6>H;++H)n[H]=D();if("number"===typeof a||!a)for(a=a|0||1,H=0;6>H;++H)v(n[H],a,a);else if("object"===typeof a)if(b)N(n[0],a),N(n[1],b),N(n[2],c),N(n[3],d),N(n[4],e),N(n[5],f);else if(O(Y,a),q(m,a),"faces"in a)for(a=a.faces,H=0;6>H;++H)r(n[H],m),N(n[H],a[H]);else for(H=0;6>H;++H)N(n[H],a);r(m,n[0]);m.mipmask=Y.genMipmaps?(n[0].width<<1)-1:n[0].mipmask;m.internalformat=n[0].internalformat;A.width=n[0].width;A.height=n[0].height;T(m);for(H=0;6>H;++H)B(n[H],34069+H);R(Y,34067);Aa();p.profile&&(m.stats.size=Ja(m.internalformat,m.type,A.width,A.height,Y.genMipmaps,!0));A.format=J[m.internalformat];A.type=da[m.type];A.mag=oa[Y.magFilter];A.min=za[Y.minFilter];A.wrapS=ka[Y.wrapS];A.wrapT=ka[Y.wrapT];for(H=0;6> H;++H)ib(n[H]);return A}var m=new F(34067);X[m.id]=m;d.cubeCount++;var n=Array(6);A(b,c,e,f,g,ua);A.subimage=function(a,b,c,n,d){c|=0;n|=0;d|=0;var e=h();r(e,m);e.width=0;e.height=0;C(e,b);e.width=e.width||(m.width>>d)-c;e.height=e.height||(m.height>>d)-n;T(m);k(e,34069+a,c,n,d);Aa();l(e);return A};A.resize=function(b){b|=0;if(b!==m.width){A.width=m.width=b;A.height=m.height=b;T(m);for(var c=0;6>c;++c)for(var n=0;m.mipmask>>n;++n)a.texImage2D(34069+c,n,m.format,b>>n,b>>n,0,m.format,m.type,null);Aa(); p.profile&&(m.stats.size=Ja(m.internalformat,m.type,A.width,A.height,!1,!0));return A}};A._reglType="textureCube";A._texture=m;p.profile&&(A.stats=m.stats);A.destroy=function(){m.decRef()};return A},clear:function(){for(var b=0;bc;++c)if(0!==(b.mipmask&1<>c,b.height>>c,0,b.internalformat,b.type,null);else for(var d=0;6>d;++d)a.texImage2D(34069+d,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);R(b.texInfo,b.target)})}}}function Ob(a,b,c,e,g,d){function p(a,b,c){this.target=a;this.texture=b;this.renderbuffer=c;var d=a=0;b?(a=b.width,d=b.height):c&&(a=c.width,d=c.height); this.width=a;this.height=d}function f(a){a&&(a.texture&&a.texture._texture.decRef(),a.renderbuffer&&a.renderbuffer._renderbuffer.decRef())}function r(a,b,c){a&&(a.texture?a.texture._texture.refCount+=1:a.renderbuffer._renderbuffer.refCount+=1)}function q(b,c){c&&(c.texture?a.framebufferTexture2D(36160,b,c.target,c.texture._texture.texture,0):a.framebufferRenderbuffer(36160,b,36161,c.renderbuffer._renderbuffer.renderbuffer))}function t(a){var b=3553,c=null,d=null,e=a;"object"===typeof a&&(e=a.data, "target"in a&&(b=a.target|0));a=e._reglType;"texture2d"===a?c=e:"textureCube"===a?c=e:"renderbuffer"===a&&(d=e,b=36161);return new p(b,c,d)}function m(a,b,c,d,f){if(c)return a=e.create2D({width:a,height:b,format:d,type:f}),a._texture.refCount=0,new p(3553,a,null);a=g.create({width:a,height:b,format:d});a._renderbuffer.refCount=0;return new p(36161,null,a)}function C(a){return a&&(a.texture||a.renderbuffer)}function k(a,b,c){a&&(a.texture?a.texture.resize(b,c):a.renderbuffer&&a.renderbuffer.resize(b, c),a.width=b,a.height=c)}function h(){this.id=O++;R[this.id]=this;this.framebuffer=a.createFramebuffer();this.height=this.width=0;this.colorAttachments=[];this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function l(a){a.colorAttachments.forEach(f);f(a.depthAttachment);f(a.stencilAttachment);f(a.depthStencilAttachment)}function u(b){a.deleteFramebuffer(b.framebuffer);b.framebuffer=null;d.framebufferCount--;delete R[b.id]}function v(b){var d;a.bindFramebuffer(36160,b.framebuffer); var e=b.colorAttachments;for(d=0;dd;++d){for(m=0;ma;++a)c[a].resize(d);b.width=b.height=d;return b},_reglType:"framebufferCube",destroy:function(){c.forEach(function(a){a.destroy()})}})}, clear:function(){S(R).forEach(u)},restore:function(){B.cur=null;B.next=null;B.dirty=!0;S(R).forEach(function(b){b.framebuffer=a.createFramebuffer();v(b)})}})}function ub(){this.w=this.z=this.y=this.x=this.state=0;this.buffer=null;this.size=0;this.normalized=!1;this.type=5126;this.divisor=this.stride=this.offset=0}function Pb(a,b,c,e){a=c.maxAttributes;b=Array(a);for(c=0;ca&&(a=b.stats.uniformsCount)});return a},c.getMaxAttributesCount=function(){var a=0;C.forEach(function(b){b.stats.attributesCount>a&&(a=b.stats.attributesCount)});return a});return{clear:function(){var b=a.deleteShader.bind(a);S(q).forEach(b);q={};S(t).forEach(b);t={};C.forEach(function(b){a.deleteProgram(b.program)}); C.length=0;m={};c.shaderCount=0},program:function(a,b,d){var e=m[b];e||(e=m[b]={});var g=e[a];g||(g=new f(b,a),c.shaderCount++,r(g,d),e[a]=g,C.push(g));return g},restore:function(){q={};t={};for(var a=0;a"+b+"?"+e+".constant["+b+"]:0;"}).join(""),"}}else{","if(",g,"(",e,".buffer)){",y,"=",n,".createStream(",34962,",",e,".buffer);","}else{",y,"=",n,".getBuffer(",e,".buffer);","}",k,'="type" in ',e,"?",f.glTypes,"[",e,".type]:",y,".dtype;", w.normalized,"=!!",e,".normalized;");d("size");d("offset");d("stride");d("divisor");c("}}");c.exit("if(",w.isStream,"){",n,".destroyStream(",y,");","}");return w})});return f}function M(a){var b=a["static"],c=a.dynamic,d={};Object.keys(b).forEach(function(a){var c=b[a];d[a]=D(function(a,b){return"number"===typeof c||"boolean"===typeof c?""+c:a.link(c)})});Object.keys(c).forEach(function(a){var b=c[a];d[a]=P(b,function(a,c){return a.invoke(c,b)})});return d}function A(a,b,c,d,e){var f=z(a,e),g=x(a, f,e),h=O(a,e),k=R(a,e),m=E(a,e),ba=g.viewport;ba&&(k.viewport=ba);ba=l("scissor.box");(g=g[ba])&&(k[ba]=g);g=0>1)",v],");")}function b(){c(u,".drawArraysInstancedANGLE(",[q,r,t,v],");")}p?da?a():(c("if(",p,"){"),a(),c("}else{"),b(),c("}")):b()}function g(){function a(){c(k+".drawElements("+[q,t,C,r+"<<(("+C+"-5121)>>1)"]+");")}function b(){c(k+".drawArrays("+[q,r,t]+");")}p?da?a():(c("if(",p,"){"),a(),c("}else{"),b(),c("}")):b()}var h=a.shared,k=h.gl,m=h.draw,l=d.draw,p=function(){var e=l.elements,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(m, ".","elements");e&&f("if("+e+")"+k+".bindBuffer(34963,"+e+".buffer.buffer);");return e}(),q=e("primitive"),r=e("offset"),t=function(){var e=l.count,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(m,".","count");return e}();if("number"===typeof t){if(0===t)return}else c("if(",t,"){"),c.exit("}");var v,u;ea&&(v=e("instances"),u=a.instancing);var C=p+".type",da=l.elements&&va(l.elements);ea&&("number"!==typeof v||0<=v)?"string"===typeof v?(c("if(",v,">0){"),f(), c("}else if(",v,"<0){"),g(),c("}")):f():g()}function ca(a,b,c,d,e){b=N();e=b.proc("body",e);ea&&(b.instancing=e.def(b.shared.extensions,".angle_instanced_arrays"));a(b,e,c,d);return b.compile().body}function L(a,b,c,d){wa(a,b);U(a,b,c,d.attributes,function(){return!0});W(a,b,c,d.uniforms,function(){return!0});S(a,b,b,c)}function da(a,b){var c=a.proc("draw",1);wa(a,c);ua(a,c,b.context);K(a,c,b.framebuffer);V(a,c,b);Q(a,c,b.state);G(a,c,b,!1,!0);var d=b.shader.progVar.append(a,c);c(a.shared.gl,".useProgram(", d,".program);");if(b.shader.program)L(a,c,b,b.shader.program);else{var e=a.global.def("{}"),f=c.def(d,".id"),g=c.def(e,"[",f,"]");c(a.cond(g).then(g,".call(this,a0);")["else"](g,"=",e,"[",f,"]=",a.link(function(c){return ca(L,a,b,c,1)}),"(",d,");",g,".call(this,a0);"))}0=--this.refCount&&p(this)};g.profile&&(e.getTotalRenderbufferSize=function(){var a=0;Object.keys(t).forEach(function(b){a+=t[b].stats.size});return a});return{create:function(b,c){function k(b,c){var d=0,e=0,m=32854;"object"===typeof b&&b?("shape"in b?(e=b.shape,d=e[0]|0,e=e[1]|0):("radius"in b&&(d=e=b.radius|0),"width"in b&&(d=b.width|0),"height"in b&&(e=b.height|0)),"format"in b&&(m=f[b.format])):"number"=== typeof b?(d=b|0,e="number"===typeof c?c|0:d):b||(d=e=1);if(d!==h.width||e!==h.height||m!==h.format)return k.width=h.width=d,k.height=h.height=e,h.format=m,a.bindRenderbuffer(36161,h.renderbuffer),a.renderbufferStorage(36161,m,d,e),g.profile&&(h.stats.size=Q[h.format]*h.width*h.height),k.format=r[h.format],k}var h=new d(a.createRenderbuffer());t[h.id]=h;e.renderbufferCount++;k(b,c);k.resize=function(b,c){var d=b|0,e=c|0||d;if(d===h.width&&e===h.height)return k;k.width=h.width=d;k.height=h.height=e; a.bindRenderbuffer(36161,h.renderbuffer);a.renderbufferStorage(36161,h.format,d,e);g.profile&&(h.stats.size=Q[h.format]*h.width*h.height);return k};k._reglType="renderbuffer";k._renderbuffer=h;g.profile&&(k.stats=h.stats);k.destroy=function(){h.decRef()};return k},clear:function(){S(t).forEach(p)},restore:function(){S(t).forEach(function(b){b.renderbuffer=a.createRenderbuffer();a.bindRenderbuffer(36161,b.renderbuffer);a.renderbufferStorage(36161,b.format,b.width,b.height)});a.bindRenderbuffer(36161, null)}}},Wa=[];Wa[6408]=4;Wa[6407]=3;var Na=[];Na[5121]=1;Na[5126]=4;Na[36193]=2;var Da=["x","y","z","w"],Ub="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),Ga={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771, "one minus constant alpha":32772,"src alpha saturate":776},Xa={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},Pa={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},wb={cw:2304,ccw:2305},xb=new Z(!1,!1,!1,function(){}),Xb=function(a,b){function c(){this.endQueryIndex=this.startQueryIndex=-1;this.sum=0;this.stats= null}function e(a,b,d){var e=p.pop()||new c;e.startQueryIndex=a;e.endQueryIndex=b;e.sum=0;e.stats=d;f.push(e)}if(!b.ext_disjoint_timer_query)return null;var g=[],d=[],p=[],f=[],r=[],q=[];return{beginQuery:function(a){var c=g.pop()||b.ext_disjoint_timer_query.createQueryEXT();b.ext_disjoint_timer_query.beginQueryEXT(35007,c);d.push(c);e(d.length-1,d.length,a)},endQuery:function(){b.ext_disjoint_timer_query.endQueryEXT(35007)},pushScopeStats:e,update:function(){var a,c;a=d.length;if(0!==a){q.length= Math.max(q.length,a+1);r.length=Math.max(r.length,a+1);r[0]=0;var e=q[0]=0;for(c=a=0;c=G.length&&e()}var c=yb(G,a);G[c]=b}}}function q(){var a=S.viewport,b=S.scissor_box;a[0]=a[1]=b[0]=b[1]=0;O.viewportWidth=O.framebufferWidth=O.drawingBufferWidth=a[2]=b[2]=k.drawingBufferWidth;O.viewportHeight=O.framebufferHeight=O.drawingBufferHeight=a[3]=b[3]=k.drawingBufferHeight}function t(){O.tick+=1;O.time=z(); q();V.procs.poll()}function m(){q();V.procs.refresh();B&&B.update()}function z(){return(zb()-D)/1E3}a=Eb(a);if(!a)return null;var k=a.gl,h=k.getContextAttributes();k.isContextLost();var l=Fb(k,a);if(!l)return null;var u=Bb(),v={bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0},x=l.extensions,B=Xb(k,x),D=zb(),J=k.drawingBufferWidth,P=k.drawingBufferHeight,O={tick:0,time:0,viewportWidth:J,viewportHeight:P,framebufferWidth:J, framebufferHeight:P,drawingBufferWidth:J,drawingBufferHeight:P,pixelRatio:a.pixelRatio},R=Vb(k,x),J=Pb(k,x,R,u),F=Gb(k,v,a,J),T=Hb(k,x,F,v),Q=Qb(k,u,v,a),A=Kb(k,x,R,function(){V.procs.poll()},O,v,a),M=Wb(k,x,R,v,a),K=Ob(k,x,R,A,M,v),V=Tb(k,u,x,R,F,T,A,K,{},J,Q,{elements:null,primitive:4,count:-1,offset:0,instances:-1},O,B,a),u=Rb(k,K,V.procs.poll,O,h,x,R),S=V.next,L=k.canvas,G=[],U=[],W=[],Z=[a.onDestroy],ca=null;L&&(L.addEventListener("webglcontextlost",g,!1),L.addEventListener("webglcontextrestored", d,!1));var aa=K.setFBO=p({framebuffer:la.define.call(null,1,"framebuffer")});m();h=E(p,{clear:function(a){if("framebuffer"in a)if(a.framebuffer&&"framebufferCube"===a.framebuffer_reglType)for(var b=0;6>b;++b)aa(E({framebuffer:a.framebuffer.faces[b]},a),f);else aa(a,f);else f(null,a)},prop:la.define.bind(null,1),context:la.define.bind(null,2),"this":la.define.bind(null,3),draw:p({}),buffer:function(a){return F.create(a,34962,!1,!1)},elements:function(a){return T.create(a,!1)},texture:A.create2D,cube:A.createCube, renderbuffer:M.create,framebuffer:K.create,framebufferCube:K.createCube,attributes:h,frame:r,on:function(a,b){var c;switch(a){case "frame":return r(b);case "lost":c=U;break;case "restore":c=W;break;case "destroy":c=Z}c.push(b);return{cancel:function(){for(var a=0;a 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; } } /***/ }), /***/ "7e25": /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var R = typeof Reflect === 'object' ? Reflect : null var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); } var ReflectOwnKeys if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target) .concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; } function EventEmitter() { EventEmitter.init.call(this); } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } /***/ }), /***/ "7e55": /***/ (function(module, exports, __webpack_require__) { var tarjan = __webpack_require__("53cc"); module.exports = function findCircuits(edges) { var circuits = []; // Output var stack = []; var blocked = []; var B = {}; var Ak = []; var s; function unblock(u) { blocked[u] = false; if(B.hasOwnProperty(u)) { Object.keys(B[u]).forEach(function(w) { delete B[u][w]; if(blocked[w]) {unblock(w);} }); } } function circuit(v) { var found = false; stack.push(v); blocked[v] = true; // L1 var i; var w; for(i = 0; i < Ak[v].length; i++) { w = Ak[v][i]; if(w === s) { output(s, stack); found = true; } else if(!blocked[w]) { found = circuit(w); } } // L2 if(found) { unblock(v); } else { for(i = 0; i < Ak[v].length; i++) { w = Ak[v][i]; var entry = B[w]; if(!entry) { entry = {}; B[w] = entry; } entry[w] = true; } } stack.pop(); return found; } function output(start, stack) { var cycle = [].concat(stack).concat(start); circuits.push(cycle); } function subgraph(minId) { // Remove edges with indice smaller than minId for(var i = 0; i < edges.length; i++) { if(i < minId) edges[i] = []; edges[i] = edges[i].filter(function(i) { return i >= minId; }); } } function adjacencyStructureSCC(from) { // Make subgraph starting from vertex minId subgraph(from); var g = edges; // Find strongly connected components using Tarjan algorithm var sccs = tarjan(g); // Filter out trivial connected components (ie. made of one node) var ccs = sccs.components.filter(function(scc) { return scc.length > 1; }); // Find least vertex var leastVertex = Infinity; var leastVertexComponent; for(var i = 0; i < ccs.length; i++) { for(var j = 0; j < ccs[i].length; j++) { if(ccs[i][j] < leastVertex) { leastVertex = ccs[i][j]; leastVertexComponent = i; } } } var cc = ccs[leastVertexComponent]; if(!cc) return false; // Return the adjacency list of first component var adjList = edges.map(function(l, index) { if(cc.indexOf(index) === -1) return []; return l.filter(function(i) { return cc.indexOf(i) !== -1; }); }); return { leastVertex: leastVertex, adjList: adjList }; } s = 0; var n = edges.length; while(s < n) { // find strong component with least vertex in // subgraph starting from vertex `s` var p = adjacencyStructureSCC(s); // Its least vertex s = p.leastVertex; // Its adjacency list Ak = p.adjList; if(Ak) { for(var i = 0; i < Ak.length; i++) { for(var j = 0; j < Ak[i].length; j++) { var vertexId = Ak[i][j]; blocked[+vertexId] = false; B[vertexId] = {}; } } circuit(s); s = s + 1; } else { s = n; } } return circuits; }; /***/ }), /***/ "7e91": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = createAttributeWrapper var GLError = __webpack_require__("a3fd") function ShaderAttribute( gl , wrapper , index , locations , dimension , constFunc) { this._gl = gl this._wrapper = wrapper this._index = index this._locations = locations this._dimension = dimension this._constFunc = constFunc } var proto = ShaderAttribute.prototype proto.pointer = function setAttribPointer( type , normalized , stride , offset) { var self = this var gl = self._gl var location = self._locations[self._index] gl.vertexAttribPointer( location , self._dimension , type || gl.FLOAT , !!normalized , stride || 0 , offset || 0) gl.enableVertexAttribArray(location) } proto.set = function(x0, x1, x2, x3) { return this._constFunc(this._locations[this._index], x0, x1, x2, x3) } Object.defineProperty(proto, 'location', { get: function() { return this._locations[this._index] } , set: function(v) { if(v !== this._locations[this._index]) { this._locations[this._index] = v|0 this._wrapper.program = null } return v|0 } }) //Adds a vector attribute to obj function addVectorAttribute( gl , wrapper , index , locations , dimension , obj , name) { //Construct constant function var constFuncArgs = [ 'gl', 'v' ] var varNames = [] 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 } /***/ }), /***/ "7e96": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Axes = __webpack_require__("0642"); 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'); labels.xLabel = Axes.tickText(xa, cdi.x, true).text; labels.yLabel = Axes.tickText(ya, cdi.y, true).text; return labels; }; /***/ }), /***/ "7eee": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var overrideAll = __webpack_require__("cb34").overrideAll; var attributes = __webpack_require__("8c2d"); 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__("2015"), calc: __webpack_require__("db3f"), makeComputeError: __webpack_require__("3c31"), plot: __webpack_require__("553a"), style: __webpack_require__("afdd"), 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; } } /***/ }), /***/ "7f20": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** @module color-rgba */ var parse = __webpack_require__("e7cb") var hsl = __webpack_require__("13c3") var clamp = __webpack_require__("53a5") module.exports = function rgba (color) { var values, i, l //attempt to parse non-array arguments var parsed = parse(color) if (!parsed.space) return [] values = Array(3) values[0] = clamp(parsed.values[0], 0, 255) values[1] = clamp(parsed.values[1], 0, 255) values[2] = clamp(parsed.values[2], 0, 255) if (parsed.space[0] === 'h') { values = hsl.rgb(values) } values.push(clamp(parsed.alpha, 0, 1)) return values } /***/ }), /***/ "7f6b": /***/ (function(module, exports, __webpack_require__) { "use strict"; var ndarray = __webpack_require__("b5bb") var do_convert = __webpack_require__("c808") module.exports = function convert(arr, result) { var shape = [], c = arr, sz = 1 while(Array.isArray(c)) { shape.push(c.length) sz *= c.length c = c[0] } if(shape.length === 0) { return ndarray() } if(!result) { result = ndarray(new Float64Array(sz), shape) } do_convert(result, arr) return result } /***/ }), /***/ "7f9a": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("da84"); var inspectSource = __webpack_require__("8925"); var WeakMap = global.WeakMap; module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap)); /***/ }), /***/ "7f9b": /***/ (function(module, exports, __webpack_require__) { var createShaderWrapper = __webpack_require__("28dd") var glslify = __webpack_require__("e98f") var perspectiveVertSrc = 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 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) } /***/ }), /***/ "7f9e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Axes = __webpack_require__("0642"); var binFunctions = __webpack_require__("6dcc"); var normFunctions = __webpack_require__("c005"); var doAvg = __webpack_require__("9547"); var getBinSpanLabelRound = __webpack_require__("5913"); var calcAllAutoBins = __webpack_require__("0c39").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; } /***/ }), /***/ "7fb7": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 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' }; /***/ }), /***/ "7fbb": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Axes = __webpack_require__("0642"); var extendFlat = __webpack_require__("9092").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 })); } 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 })); } } 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 })); } 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 })); } } 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 })); } } }; /***/ }), /***/ "7fc3": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var hover = __webpack_require__("e812").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(); } }; /***/ }), /***/ "7fcc": /***/ (function(module, exports, __webpack_require__) { "use strict"; function compileSearch(funcName, predicate, reversed, extraArgs, useNdarray, earlyOut) { var code = [ "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), ";while(l<=h){\ var m=(l+h)>>>1,x=a", useNdarray ? ".get(m)" : "[m]"] if(earlyOut) { if(predicate.indexOf("c") < 0) { code.push(";if(x===y){return m}else if(x<=y){") } else { code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){") } } else { code.push(";if(", predicate, "){i=m;") } if(reversed) { code.push("l=m+1}else{h=m-1}") } else { code.push("h=m-1}else{l=m+1}") } code.push("}") if(earlyOut) { code.push("return -1};") } else { code.push("return i};") } return code.join("") } function compileBoundsSearch(predicate, reversed, suffix, earlyOut) { var result = new Function([ compileSearch("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut), compileSearch("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut), compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut), compileSearch("Q", "c(x,y)" + predicate + "0", reversed, ["y", "c"], true, earlyOut), "function dispatchBsearch", suffix, "(a,y,c,l,h){\ if(a.shape){\ if(typeof(c)==='function'){\ return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)\ }else{\ return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)\ }}else{\ if(typeof(c)==='function'){\ return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)\ }else{\ return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)\ }}}\ return dispatchBsearch", suffix].join("")) return result() } module.exports = { ge: compileBoundsSearch(">=", false, "GE"), gt: compileBoundsSearch(">", false, "GT"), lt: compileBoundsSearch("<", true, "LT"), le: compileBoundsSearch("<=", true, "LE"), eq: compileBoundsSearch("-", true, "EQ", true) } /***/ }), /***/ "7fda": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Axes = __webpack_require__("0642"); var mergeArray = __webpack_require__("fc26").mergeArray; var calcSelection = __webpack_require__("4136"); var BADNUM = __webpack_require__("e806").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; if(trace.orientation === 'h') { size = xa.makeCalcdata(trace, 'x'); pos = ya.makeCalcdata(trace, 'y'); } else { size = ya.makeCalcdata(trace, 'y'); pos = xa.makeCalcdata(trace, 'x'); } // 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(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; }; /***/ }), /***/ "8062": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Drawing = __webpack_require__("83d1"); var Color = __webpack_require__("d115"); var DESELECTDIM = __webpack_require__("72a4").DESELECTDIM; var barStyle = __webpack_require__("2df3"); var resizeText = __webpack_require__("93a6").resizeText; var styleTextPoints = barStyle.styleTextPoints; function style(gd, cd, sel) { var s = sel ? sel : d3.select(gd).selectAll('g.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 }; /***/ }), /***/ "806e": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var subTypes = __webpack_require__("de81"); var helpers = __webpack_require__("2969f"); 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 = []; 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)) { els.push(i); selection.push({ pointNumber: i, x: x[i], y: y[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; }; /***/ }), /***/ "8173": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Registry = __webpack_require__("371e"); var Lib = __webpack_require__("fc26"); 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'); }; /***/ }), /***/ "81f0": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var extendFlat = __webpack_require__("9092").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.attributes = 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.defaults = 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(); }; /***/ }), /***/ "821b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * 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}); }); } }; /***/ }), /***/ "824b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var isNumeric = __webpack_require__("19b2"); var BADNUM = __webpack_require__("e806").BADNUM; var calcMarkerColorscale = __webpack_require__("09bd"); var arraysToCalcdata = __webpack_require__("106b"); var calcSelection = __webpack_require__("4136"); var _ = __webpack_require__("fc26")._; function isNonBlankString(v) { return v && typeof v === 'string'; } module.exports = function calc(gd, trace) { var hasLocationData = Array.isArray(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; }; /***/ }), /***/ "825a": /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__("861d"); module.exports = function (it) { if (!isObject(it)) { throw TypeError(String(it) + ' is not an object'); } return it; }; /***/ }), /***/ "8260": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var scatterPlot = __webpack_require__("f118"); var BADNUM = __webpack_require__("e806").BADNUM; module.exports = function plot(gd, subplot, moduleCalcData) { var mlayer = subplot.layers.frontplot.select('g.scatterlayer'); var plotinfo = { xaxis: subplot.xaxis, yaxis: subplot.yaxis, 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++) { 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); }; /***/ }), /***/ "8298": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var Lib = __webpack_require__("fc26"); var Drawing = __webpack_require__("83d1"); var boxPlot = __webpack_require__("d34f"); var linePoints = __webpack_require__("9cf1"); var helpers = __webpack_require__("0681"); module.exports = function plot(gd, plotinfo, cdViolins, violinLayer) { var fullLayout = gd._fullLayout; var xa = plotinfo.xaxis; var ya = plotinfo.yaxis; function makePath(pts) { var segments = linePoints(pts, { xaxis: xa, yaxis: ya, 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', '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); } 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); } 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', '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); }); }; /***/ }), /***/ "82a5": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); 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.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); } } /***/ }), /***/ "82b5": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * 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 }; }; /***/ }), /***/ "82d4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var colorscaleDefaults = __webpack_require__("4183"); var attributes = __webpack_require__("be2a"); 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'); // 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; }; /***/ }), /***/ "82d7": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var fontAttrs = __webpack_require__("9845"); var baseAttrs = __webpack_require__("a876"); var colorAttrs = __webpack_require__("dfb3"); var fxAttrs = __webpack_require__("a462"); var domainAttrs = __webpack_require__("81f0").attributes; var hovertemplateAttrs = __webpack_require__("94d5").hovertemplateAttrs; var colorAttributes = __webpack_require__("f4e9"); var templatedArray = __webpack_require__("a651").templatedArray; var extendFlat = __webpack_require__("9092").extendFlat; var overrideAll = __webpack_require__("cb34").overrideAll; var FORMAT_LINK = __webpack_require__("78df").FORMAT_LINK; 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', }, valuesuffix: { valType: 'string', dflt: '', }, arrangement: { valType: 'enumerated', values: ['snap', 'perpendicular', 'freeform', 'fixed'], dflt: 'snap', }, textfont: fontAttrs({ }), 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, }, 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'] }), }, link: { label: { valType: 'data_array', dflt: [], }, color: { valType: 'color', arrayOk: true, }, 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; /***/ }), /***/ "82e4": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("f90d"); /***/ }), /***/ "831f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = __webpack_require__("0382"); /***/ }), /***/ "8378": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Color = __webpack_require__("d115"); var Template = __webpack_require__("a651"); var basePlotLayoutAttributes = __webpack_require__("a685"); var layoutAttributes = __webpack_require__("d798"); var handleTypeDefaults = __webpack_require__("b5e2"); var handleAxisDefaults = __webpack_require__("7118"); var handleConstraintDefaults = __webpack_require__("6add").handleConstraintDefaults; var handlePositionDefaults = __webpack_require__("f3a2"); var axisIds = __webpack_require__("3c1c"); var id2name = axisIds.id2name; var name2id = axisIds.name2id; var Registry = __webpack_require__("371e"); 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 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); var axName, axLetter, axLayoutIn, axLayoutOut; 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; } var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; var allAxisIds = counterAxes.x.concat(counterAxes.y); 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; } // first pass creates the containers, determines types, and handles most of the settings for(i = 0; i < axNames.length; i++) { axName = axNames[i]; axLetter = axName.charAt(0); if(!Lib.isPlainObject(layoutIn[axName])) { layoutIn[axName] = {}; } axLayoutIn = layoutIn[axName]; axLayoutOut = Template.newContainer(layoutOut, axName, axLetter + 'axis'); var traces = ax2traces[axName] || []; axLayoutOut._traceIndices = traces.map(function(t) { return t._expandedIndex; }); axLayoutOut._annIndices = []; axLayoutOut._shapeIndices = []; axLayoutOut._imgIndices = []; axLayoutOut._subplotsWith = []; axLayoutOut._counterAxes = []; // set up some private properties axLayoutOut._name = axLayoutOut._attr = axName; var id = axLayoutOut._id = name2id(axName); var overlayableAxes = getOverlayableAxes(axLetter, axName); 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 = { letter: axLetter, font: layoutOut.font, outerTicks: outerTicks[axName], showGrid: !noGrids[axName], data: traces, bgColor: bgColor, calendar: layoutOut.calendar, automargin: true, visibleDflt: visibleDflt, reverseDflt: reverseDflt, splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[id] }; coerce('uirevision', layoutOut.uirevision); handleTypeDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions); handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); var spikecolor = coerce2('spikecolor'); var spikethickness = coerce2('spikethickness'); var spikedash = coerce2('spikedash'); var spikemode = coerce2('spikemode'); var spikesnap = coerce2('spikesnap'); var showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); if(!showSpikes) { delete axLayoutOut.spikecolor; delete axLayoutOut.spikethickness; delete axLayoutOut.spikedash; delete axLayoutOut.spikemode; delete axLayoutOut.spikesnap; } handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, { letter: axLetter, counterAxes: counterAxes[axLetter], overlayableAxes: overlayableAxes, grid: layoutOut.grid }); coerce('title.standoff'); 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). // sets of axes linked by `scaleanchor` along with the scaleratios compounded // together, populated in handleConstraintDefaults var constraintGroups = layoutOut._axisConstraintGroups = []; // similar to _axisConstraintGroups, but for matching axes var matchGroups = layoutOut._axisMatchGroups = []; for(i = 0; i < axNames.length; i++) { axName = axNames[i]; axLetter = axName.charAt(0); axLayoutIn = layoutIn[axName]; axLayoutOut = layoutOut[axName]; var scaleanchorDflt; if(axLetter === 'y' && !axLayoutIn.hasOwnProperty('scaleanchor') && axHasImage[axName]) { scaleanchorDflt = axLayoutOut.anchor; } else {scaleanchorDflt = undefined;} var constrainDflt; if(!axLayoutIn.hasOwnProperty('constrain') && axHasImage[axName]) { constrainDflt = 'domain'; } else {constrainDflt = undefined;} handleConstraintDefaults(axLayoutIn, axLayoutOut, coerce, { allAxisIds: allAxisIds, layoutOut: layoutOut, scaleanchorDflt: scaleanchorDflt, constrainDflt: constrainDflt }); } for(i = 0; i < matchGroups.length; i++) { var group = matchGroups[i]; var rng = null; var autorange = null; var axId; // find 'matching' range attrs for(axId in group) { axLayoutOut = layoutOut[id2name(axId)]; if(!axLayoutOut.matches) { rng = axLayoutOut.range; autorange = axLayoutOut.autorange; } } // if `ax.matches` values are reciprocal, // pick values of first axis in group if(rng === null || autorange === null) { for(axId in group) { axLayoutOut = layoutOut[id2name(axId)]; rng = axLayoutOut.range; autorange = axLayoutOut.autorange; break; } } // apply matching range attrs for(axId in group) { axLayoutOut = layoutOut[id2name(axId)]; if(axLayoutOut.matches) { axLayoutOut.range = rng.slice(); axLayoutOut.autorange = autorange; } axLayoutOut._matchGroup = group; } // remove matching axis from scaleanchor constraint groups (for now) if(constraintGroups.length) { for(axId in group) { for(j = 0; j < constraintGroups.length; j++) { var group2 = constraintGroups[j]; for(var axId2 in group2) { if(axId === axId2) { Lib.warn('Axis ' + axId2 + ' is set with both ' + 'a *scaleanchor* and *matches* constraint; ' + 'ignoring the scale constraint.'); delete group2[axId2]; if(Object.keys(group2).length < 2) { constraintGroups.splice(j, 1); } } } } } } } }; /***/ }), /***/ "838d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { attributes: __webpack_require__("1590"), supplyDefaults: __webpack_require__("2513"), crossTraceDefaults: __webpack_require__("722f"), calc: __webpack_require__("0625"), plot: __webpack_require__("fa8a"), layerName: 'heatmaplayer', colorbar: __webpack_require__("fcb3"), style: __webpack_require__("c437"), hoverPoints: __webpack_require__("9236"), eventData: __webpack_require__("6f09"), moduleType: 'trace', name: 'histogram2d', basePlotModule: __webpack_require__("91cd"), categories: ['cartesian', 'svg', '2dMap', 'histogram', 'showLegend'], meta: { } }; /***/ }), /***/ "83ab": /***/ (function(module, exports, __webpack_require__) { var fails = __webpack_require__("d039"); // Thank's IE8 for his funny defineProperty module.exports = !fails(function () { return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7; }); /***/ }), /***/ "83c1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Fx = __webpack_require__("a5c4"); var Lib = __webpack_require__("fc26"); var getTraceColor = __webpack_require__("feed"); var fillText = Lib.fillText; var BADNUM = __webpack_require__("e806").BADNUM; 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 subplot = pointData.subplot; // 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; 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[0]) + ', ' + format(lonlat[1]) + ')'); } 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('
'); } /***/ }), /***/ "83d1": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var d3 = __webpack_require__("6e58"); var isNumeric = __webpack_require__("19b2"); var tinycolor = __webpack_require__("66cb"); var Registry = __webpack_require__("371e"); var Color = __webpack_require__("d115"); var Colorscale = __webpack_require__("c258"); var Lib = __webpack_require__("fc26"); var svgTextUtils = __webpack_require__("0379"); var xmlnsNamespaces = __webpack_require__("73c9"); var alignment = __webpack_require__("63dc"); var LINE_SPACING = alignment.LINE_SPACING; var DESELECTDIM = __webpack_require__("72a4").DESELECTDIM; var subTypes = __webpack_require__("de81"); var makeBubbleSizeFn = __webpack_require__("1978"); var appendArrayPointValue = __webpack_require__("c4c7").appendArrayPointValue; var drawing = module.exports = {}; // ----------------------------------------------------- // styling functions for plot elements // ----------------------------------------------------- drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) if(Lib.isPlainObject(family)) { color = family.color; size = family.size; family = family.family; } if(family) s.style('font-family', family); if(size + 1) s.style('font-size', size + 'px'); if(color) s.call(Color.fill, color); }; /* * 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', 'translate(' + 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; }; // Same as fillGroupStyle, except in this case the selection may be a transition drawing.singleFillStyle = function(sel) { var node = d3.select(sel.node()); var data = node.data(); var fillcolor = (((data[0] || [])[0] || {}).trace || {}).fillcolor; if(fillcolor) { sel.call(Color.fill, fillcolor); } }; drawing.fillGroupStyle = function(s) { 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) { shape.call(Color.fill, d[0].trace.fillcolor); } }); }; var SYMBOLDEFS = __webpack_require__("3350"); drawing.symbolNames = []; drawing.symbolFuncs = []; 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, k, n + 100, k + '-open' ); drawing.symbolNames[n] = k; drawing.symbolFuncs[n] = symDef.f; if(symDef.needLine) { drawing.symbolNeedLines[n] = true; } if(symDef.noDot) { drawing.symbolNoDot[n] = true; } else { drawing.symbolList.push( n + 200, k + '-dot', 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(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) { var base = symbolNumber % 100; return drawing.symbolFuncs[base](r) + (symbolNumber >= 200 ? DOTPATH : ''); } var HORZGRADIENT = {x1: 1, x2: 0, y1: 0, y2: 0}; var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; var stopFormatter = d3.format('~.1f'); var gradientInfo = { radial: {node: 'radialGradient'}, radialreversed: {node: 'radialGradient', reversed: true}, horizontal: {node: 'linearGradient', attrs: HORZGRADIENT}, horizontalreversed: {node: 'linearGradient', attrs: HORZGRADIENT, reversed: true}, vertical: {node: 'linearGradient', attrs: VERTGRADIENT}, verticalreversed: {node: 'linearGradient', attrs: VERTGRADIENT, 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 len = colorscale.length; var info = gradientInfo[type]; 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); var className2query = function(s) { return '.' + s.attr('class').replace(/\s/g, '.'); }; var k = className2query(d3.select(sel.node().parentNode)) + '>' + className2query(sel); fullLayout._gradientUrlQueryParts[k] = 1; }; /* * 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(); // initialize stash of query parts filled in Drawing.gradient, // used to fix URL strings during image exports fullLayout._gradientUrlQueryParts = {}; }; drawing.pointStyle = function(s, trace, gd) { if(!s.size()) return; var fns = drawing.makePointStyleFns(trace); s.each(function(d) { drawing.singlePointStyle(d, d3.select(this), trace, fns, gd); }); }; drawing.singlePointStyle = function(d, sel, trace, fns, gd) { var marker = trace.marker; var markerLine = marker.line; 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; sel.attr('d', makePointPath(x, r)); } 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 || '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(Array.isArray(gradientType)) { gradientType = gradientType[0]; if(!gradientInfo[gradientType]) gradientType = 0; } 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 { 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)); // 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) { 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); group.attr('transform', 'translate(' + 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 labels = trace._module.formatLabels ? trace._module.formatLabels(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, d.tf || trace.textfont.family, fontSize, 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); textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc); }); }; // 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; }; 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 [ [ d3.round(thispt[0] + (denom1 && numx / denom1), 2), d3.round(thispt[1] + (denom1 && numy / denom1), 2) ], [ d3.round(thispt[0] - (denom2 && numx / denom2), 2), d3.round(thispt[1] - (denom2 && numy / denom2), 2) ] ]; } // step paths - returns a generator function for paths // with the given step shape var STEPPATH = { hv: function(p0, p1) { return 'H' + d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2); }, vh: function(p0, p1) { return 'V' + d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2); }, hvh: function(p0, p1) { return 'H' + d3.round((p0[0] + p1[0]) / 2, 2) + 'V' + d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2); }, vhv: function(p0, p1) { return 'V' + d3.round((p0[1] + p1[1]) / 2, 2) + 'H' + d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2); } }; var STEPLINEAR = function(p0, p1) { return 'L' + d3.round(p1[0], 2) + ',' + d3.round(p1[1], 2); }; drawing.steps = function(shape) { var onestep = STEPPATH[shape] || STEPLINEAR; return function(pts) { var path = 'M' + d3.round(pts[0][0], 2) + ',' + d3.round(pts[0][1], 2); for(var i = 1; i < pts.length; i++) { path += onestep(pts[i - 1], pts[i]); } return path; }; }; // 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 'url(\'' + baseUrl + '#' + 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 += ' translate(' + 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 = [ 'translate(' + x + ',' + y + ')', 'scale(' + xScale + ',' + yScale + ')', 'translate(' + (-x) + ',' + (-y) + ')', ]; } if(existingTransform) { transforms.push(existingTransform); } el.attr('transform', transforms.join(' ')); }); }; /***/ }), /***/ "8418": /***/ (function(module, exports, __webpack_require__) { "use strict"; var toPrimitive = __webpack_require__("c04e"); var definePropertyModule = __webpack_require__("9bf2"); var createPropertyDescriptor = __webpack_require__("5c6c"); module.exports = function (object, key, value) { var propertyKey = toPrimitive(key); if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value)); else object[propertyKey] = value; }; /***/ }), /***/ "849d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); // 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) }); } /***/ }), /***/ "84a1": /***/ (function(module, exports) { module.exports = function () { for (var i = 0; i < arguments.length; i++) { if (arguments[i] !== undefined) return arguments[i]; } }; /***/ }), /***/ "84af": /***/ (function(module, exports, __webpack_require__) { "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; j 0) { 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 /***/ }), /***/ "84d3": /***/ (function(module, exports, __webpack_require__) { "use strict"; var isValue = __webpack_require__("936a") , isObject = __webpack_require__("5edd") , stringCoerce = __webpack_require__("eae0") , toShortString = __webpack_require__("7d88"); var resolveMessage = function (message, value) { return message.replace("%v", toShortString(value)); }; module.exports = function (value, defaultMessage, inputOptions) { if (!isObject(inputOptions)) throw new TypeError(resolveMessage(defaultMessage, value)); if (!isValue(value)) { if ("default" in inputOptions) return inputOptions["default"]; if (inputOptions.isOptional) return null; } var errorMessage = stringCoerce(inputOptions.errorMessage); if (!isValue(errorMessage)) errorMessage = defaultMessage; throw new TypeError(resolveMessage(errorMessage, value)); }; /***/ }), /***/ "84df": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); 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; 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 hiddenSlices = fullLayout.hiddenlabels ? fullLayout.hiddenlabels.slice() : []; var legendItem = g.data()[0][0]; var fullData = gd._fullData; var fullTrace = legendItem.trace; var legendgroup = fullTrace.legendgroup; var i, j, kcont, key, keys, val; var attrUpdate = {}; var attrIndices = []; var carrs = []; var carrIdx = []; function insertUpdate(traceIndex, key, value) { var attrIndex = attrIndices.indexOf(traceIndex); var valueArray = attrUpdate[key]; if(!valueArray) { valueArray = attrUpdate[key] = []; } if(attrIndices.indexOf(traceIndex) === -1) { attrIndices.push(traceIndex); attrIndex = attrIndices.length - 1; } valueArray[attrIndex] = value; return attrIndex; } function setVisibility(fullTrace, visibility) { var fullInput = fullTrace._fullInput; if(Registry.hasTransform(fullInput, 'groupby')) { var kcont = carrs[fullInput.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[fullInput.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[fullInput.index] = insertUpdate(fullInput.index, 'visible', 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; insertUpdate(fullInput.index, 'visible', nextVisibility); } } if(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') { hiddenSlices = []; gd.calcdata[0].forEach(function(d) { if(thisLabel !== d.label) { hiddenSlices.push(d.label); } }); if(gd._fullLayout.hiddenlabels && gd._fullLayout.hiddenlabels.length === hiddenSlices.length && thisLabelIndex === -1) { hiddenSlices = []; } } Registry.call('_guiRelayout', gd, 'hiddenlabels', hiddenSlices); } else { var hasLegendgroup = legendgroup && legendgroup.length; var traceIndicesInGroup = []; var tracei; if(hasLegendgroup) { for(i = 0; i < fullData.length; i++) { tracei = fullData[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) { for(i = 0; i < fullData.length; i++) { if(fullData[i].visible !== false && fullData[i].legendgroup === legendgroup) { setVisibility(fullData[i], 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; var isIsolated = true; for(i = 0; i < fullData.length; i++) { isClicked = fullData[i] === fullTrace; notInLegend = fullData[i].showlegend !== true; if(isClicked || notInLegend) continue; isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); if(!isInGroup && fullData[i].visible === true && !Registry.traceIs(fullData[i], 'notLegendIsolatable')) { isIsolated = false; break; } } for(i = 0; i < fullData.length; i++) { // False is sticky; we don't change it. if(fullData[i].visible === false) continue; if(Registry.traceIs(fullData[i], 'notLegendIsolatable')) { continue; } switch(fullTrace.visible) { case 'legendonly': setVisibility(fullData[i], true); break; case true: otherState = isIsolated ? true : 'legendonly'; isClicked = fullData[i] === fullTrace; // N.B. consider traces that have a set legendgroup as toggleable notInLegend = (fullData[i].showlegend !== true && !fullData[i].legendgroup); isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); setVisibility(fullData[i], (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 = attrUpdate[key] = attrUpdate[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(attrUpdate); for(i = 0; i < keys.length; i++) { key = keys[i]; for(j = 0; j < attrIndices.length; j++) { // Use hasOwnPropety to protect against falsey values: if(!attrUpdate[key].hasOwnProperty(j)) { attrUpdate[key][j] = undefined; } } } Registry.call('_guiRestyle', gd, attrUpdate, attrIndices); } }; /***/ }), /***/ "850f": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = function eventData(out, pt) { out.lon = pt.lon; out.lat = pt.lat; out.z = pt.z; return out; }; /***/ }), /***/ "855b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Events = __webpack_require__("8741"); var throttle = __webpack_require__("7df2"); var getGraphDiv = __webpack_require__("1b88").getGraphDiv; var hoverConstants = __webpack_require__("7fb7"); 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 && 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 }); } }; /***/ }), /***/ "8568": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Lib = __webpack_require__("fc26"); var Axes = __webpack_require__("0642"); var calcCommon = __webpack_require__("bb14").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 x = xa.makeCalcdata(trace, 'x'); var cd = calcCommon(gd, trace, 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, }; } /***/ }), /***/ "8586": /***/ (function(module, exports, __webpack_require__) { module.exports = tokenize var literals100 = __webpack_require__("1936") , operators = __webpack_require__("6a25") , builtins100 = __webpack_require__("5ecd") , literals300es = __webpack_require__("f5f2") , builtins300es = __webpack_require__("0648") var NORMAL = 999 // <-- never emitted , TOKEN = 9999 // <-- never emitted , BLOCK_COMMENT = 0 , LINE_COMMENT = 1 , PREPROCESSOR = 2 , OPERATOR = 3 , INTEGER = 4 , FLOAT = 5 , IDENT = 6 , BUILTIN = 7 , KEYWORD = 8 , WHITESPACE = 9 , EOF = 10 , HEX = 11 var map = [ 'block-comment' , 'line-comment' , 'preprocessor' , 'operator' , 'integer' , 'float' , 'ident' , 'builtin' , 'keyword' , 'whitespace' , 'eof' , 'integer' ] function tokenize(opt) { var i = 0 , total = 0 , mode = NORMAL , c , last , content = [] , tokens = [] , token_idx = 0 , token_offs = 0 , line = 1 , col = 0 , start = 0 , isnum = false , isoperator = false , input = '' , len opt = opt || {} var allBuiltins = builtins100 var allLiterals = literals100 if (opt.version === '300 es') { allBuiltins = builtins300es allLiterals = literals300es } // cache by name var builtinsDict = {}, literalsDict = {} for (var i = 0; i < allBuiltins.length; i++) { builtinsDict[allBuiltins[i]] = true } for (var i = 0; i < allLiterals.length; i++) { literalsDict[allLiterals[i]] = true } return function(data) { tokens = [] if (data !== null) return write(data) return end() } function token(data) { if (data.length) { tokens.push({ type: map[mode] , data: data , position: start , line: line , column: col }) } } function write(chunk) { i = 0 if (chunk.toString) chunk = chunk.toString() input += chunk.replace(/\r\n/g, '\n') len = input.length var last while(c = input[i], i < len) { last = i switch(mode) { case BLOCK_COMMENT: i = block_comment(); break case LINE_COMMENT: i = line_comment(); break case PREPROCESSOR: i = preprocessor(); break case OPERATOR: i = operator(); break case INTEGER: i = integer(); break case HEX: i = hex(); break case FLOAT: i = decimal(); break case TOKEN: i = readtoken(); break case WHITESPACE: i = whitespace(); break case NORMAL: i = normal(); break } if(last !== i) { switch(input[last]) { case '\n': col = 0; ++line; break default: ++col; break } } } total += i input = input.slice(i) return tokens } function end(chunk) { if(content.length) { token(content.join('')) } mode = EOF token('(eof)') return tokens } function normal() { content = content.length ? [] : content if(last === '/' && c === '*') { start = total + i - 1 mode = BLOCK_COMMENT last = c return i + 1 } if(last === '/' && c === '/') { start = total + i - 1 mode = LINE_COMMENT last = c return i + 1 } if(c === '#') { mode = PREPROCESSOR start = total + i return i } if(/\s/.test(c)) { mode = WHITESPACE start = total + i return i } isnum = /\d/.test(c) isoperator = /[^\w_]/.test(c) start = total + i mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN return i } function whitespace() { if(/[^\s]/g.test(c)) { token(content.join('')) mode = NORMAL return i } content.push(c) last = c return i + 1 } function preprocessor() { if((c === '\r' || c === '\n') && last !== '\\') { token(content.join('')) mode = NORMAL return i } content.push(c) last = c return i + 1 } function line_comment() { return preprocessor() } function block_comment() { if(c === '/' && last === '*') { content.push(c) token(content.join('')) mode = NORMAL return i + 1 } content.push(c) last = c return i + 1 } function operator() { if(last === '.' && /\d/.test(c)) { mode = FLOAT return i } if(last === '/' && c === '*') { mode = BLOCK_COMMENT return i } if(last === '/' && c === '/') { mode = LINE_COMMENT return i } if(c === '.' && content.length) { while(determine_operator(content)); mode = FLOAT return i } if(c === ';' || c === ')' || c === '(') { if(content.length) while(determine_operator(content)); token(c) mode = NORMAL return i + 1 } var is_composite_operator = content.length === 2 && c !== '=' if(/[\w_\d\s]/.test(c) || is_composite_operator) { while(determine_operator(content)); mode = NORMAL return i } content.push(c) last = c return i + 1 } function determine_operator(buf) { var j = 0 , idx , res do { idx = operators.indexOf(buf.slice(0, buf.length + j).join('')) res = operators[idx] if(idx === -1) { if(j-- + buf.length > 0) continue res = buf.slice(0, 1).join('') } token(res) start += res.length content = content.slice(res.length) return content.length } while(1) } function hex() { if(/[^a-fA-F0-9]/.test(c)) { token(content.join('')) mode = NORMAL return i } content.push(c) last = c return i + 1 } function integer() { if(c === '.') { content.push(c) mode = FLOAT last = c return i + 1 } if(/[eE]/.test(c)) { content.push(c) mode = FLOAT last = c return i + 1 } if(c === 'x' && content.length === 1 && content[0] === '0') { mode = HEX content.push(c) last = c return i + 1 } if(/[^\d]/.test(c)) { token(content.join('')) mode = NORMAL return i } content.push(c) last = c return i + 1 } function decimal() { if(c === 'f') { content.push(c) last = c i += 1 } if(/[eE]/.test(c)) { content.push(c) last = c return i + 1 } if ((c === '-' || c === '+') && /[eE]/.test(last)) { content.push(c) last = c return i + 1 } if(/[^\d]/.test(c)) { token(content.join('')) mode = NORMAL return i } content.push(c) last = c return i + 1 } function readtoken() { if(/[^\d\w_]/.test(c)) { var contentstr = content.join('') if(literalsDict[contentstr]) { mode = KEYWORD } else if(builtinsDict[contentstr]) { mode = BUILTIN } else { mode = IDENT } token(content.join('')) mode = NORMAL return i } content.push(c) last = c return i + 1 } } /***/ }), /***/ "860b": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var mapboxgl = __webpack_require__("e192"); var Lib = __webpack_require__("fc26"); var getSubplotCalcData = __webpack_require__("ad62").getSubplotCalcData; var xmlnsNamespaces = __webpack_require__("73c9"); var d3 = __webpack_require__("6e58"); var Drawing = __webpack_require__("83d1"); var svgTextUtils = __webpack_require__("0379"); var Mapbox = __webpack_require__("3fca"); var MAPBOX = 'mapbox'; var constants = exports.constants = __webpack_require__("b5e4"); 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__("f7e9"); exports.supplyLayoutDefaults = __webpack_require__("f518"); 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', 'translate(' + (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', 'translate(-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', 'translate(' + offset[0] + ',' + offset[1] + ') scale(' + 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(isMapboxStyle(opts.style)) { if(token) { Lib.pushUnique(tokensUseful, token); } else { if(isMapboxStyle(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 isMapboxStyle(s) { return typeof s === 'string' && ( constants.styleValuesMapbox.indexOf(s) !== -1 || s.indexOf('mapbox://') === 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); } }; /***/ }), /***/ "861d": /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /***/ "865d": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var overrideAll = __webpack_require__("cb34").overrideAll; var getModuleCalcData = __webpack_require__("ad62").getModuleCalcData; var plot = __webpack_require__("c9ce"); var fxAttrs = __webpack_require__("927d"); var setCursor = __webpack_require__("0f37"); var dragElement = __webpack_require__("4efe"); var prepSelect = __webpack_require__("1876").prepSelect; var Lib = __webpack_require__("fc26"); var Registry = __webpack_require__("371e"); 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(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); } /***/ }), /***/ "8662": /***/ (function(module, exports, __webpack_require__) { module.exports = circumradius var circumcenter = __webpack_require__("fe94") function circumradius(points) { var center = circumcenter(points) var avgDist = 0.0 for(var i=0; i